-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient-ip.ts
More file actions
48 lines (37 loc) · 1.28 KB
/
client-ip.ts
File metadata and controls
48 lines (37 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import 'server-only';
import type { NextRequest } from 'next/server';
import { isIP } from 'node:net';
function envBool(name: string, fallback: boolean): boolean {
const raw = (process.env[name] ?? '').trim().toLowerCase();
if (!raw) return fallback;
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on')
return true;
if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off')
return false;
return fallback;
}
export function getClientIpFromHeaders(headers: Headers): string | null {
const trustForwarded = envBool(
'TRUST_FORWARDED_HEADERS',
process.env.NODE_ENV !== 'production'
);
const trustCf = envBool('TRUST_CF_CONNECTING_IP', false);
if (trustCf) {
const cf = (headers.get('cf-connecting-ip') ?? '').trim();
if (cf && isIP(cf)) return cf;
}
if (!trustForwarded) return null;
const xr = (headers.get('x-real-ip') ?? '').trim();
if (xr && isIP(xr)) return xr;
const xff = (headers.get('x-forwarded-for') ?? '').trim();
if (xff) {
for (const part of xff.split(',')) {
const candidate = part.trim();
if (candidate && isIP(candidate)) return candidate;
}
}
return null;
}
export function getClientIp(request: NextRequest): string | null {
return getClientIpFromHeaders(request.headers);
}