Skip to content

Commit 30378c8

Browse files
committed
Fixes Does not read the IP from x-forwarded-for #30
1 parent ed24145 commit 30378c8

File tree

2 files changed

+20
-21
lines changed

2 files changed

+20
-21
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "elysia-ip",
3-
"version": "1.0.7",
3+
"version": "1.0.8",
44
"type": "module",
55
"author": {
66
"name": "Gaurish Sethia",

src/services/getip.ts

+19-20
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,33 @@ export const getIP = (
66
headers: Headers,
77
checkHeaders: IPHeaders[] = headersToCheck,
88
) => {
9+
// User provided single header
910
if (typeof checkHeaders === "string" && headers.get(checkHeaders)) {
1011
debug(`getIP: Found ip from header ${checkHeaders}`);
11-
return headers.get(checkHeaders);
12+
return headers.get(checkHeaders)
1213
}
1314

14-
// X-Forwarded-For is the de-facto standard header
15-
if (!checkHeaders && headers.get("x-forwarded-for")) {
16-
debug("getIP: IP From Header x-forwarded-for");
17-
return headers.get("x-forwarded-for")?.split(",")[0];
15+
// check for x-forwaded-for only when user did not provide headers
16+
if (checkHeaders && checkHeaders === headersToCheck && headers.get("x-forwarded-for")) {
17+
debug("getIP: IP From Header x-forwarded-for");
18+
return headers.get("x-forwarded-for")?.split(",")[0];
19+
}
20+
21+
// User provided / default headers array
22+
if (Array.isArray(checkHeaders)) {
23+
let clientIP: string | undefined | null = null;
24+
for (const header of checkHeaders) {
25+
clientIP = headers.get(header);
26+
if (clientIP) {
27+
debug(`getIP: Found ip from header ${header}`);
28+
break;
29+
}
30+
}
31+
return clientIP
1832
}
1933

2034
if (!checkHeaders) {
2135
debug("getIP: No checkHeaders");
2236
return null;
2337
}
24-
25-
let clientIP: string | undefined | null = null;
26-
for (const header of checkHeaders) {
27-
clientIP = headers.get(header);
28-
if (clientIP) {
29-
debug(`getIP: Found ip from header ${header}`);
30-
break;
31-
}
32-
}
33-
34-
if (!clientIP) {
35-
debug("getIP: Failed to get ip from header!");
36-
return;
37-
}
38-
return clientIP;
3938
};

0 commit comments

Comments
 (0)