Skip to content

Commit 7f07a94

Browse files
committed
headers only mode
1 parent 90d7217 commit 7f07a94

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,15 @@ import { ip } from "elysia-ip";
7575
new Elysia().use(ip({ checkHeaders: "X-Forwarded-For" })).get("/", ({ ip }) => ip).listen(3000);
7676
```
7777

78+
You can also switch to Headers only mode by setting `headersOnly` to `true`. This will only check headers and not the `server.requestIP` property.
79+
80+
```ts
81+
import { Elysia } from "elysia";
82+
import { ip } from "elysia-ip";
83+
84+
new Elysia().use(ip({ headersOnly: true })).get("/", ({ ip }) => ip).listen(3000);
85+
```
86+
7887
## License
7988
MIT
8089

src/index.ts

+11-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Elysia } from 'elysia';
33
export type IPHeaders = 'x-real-ip' | 'x-client-ip' | 'cf-connecting-ip' | 'fastly-client-ip' | 'x-cluster-client-ip' | 'x-forwarded' | 'forwarded-for' | 'forwarded' | 'x-forwarded' | 'appengine-user-ip' | 'true-client-ip' | 'cf-pseudo-ipv4' | (string & {})
44
export const headersToCheck: IPHeaders[] = [
55
'x-real-ip', // Nginx proxy/FastCGI
6-
'x-client-ip', // Apache https://httpd.apache.org/docs/2.4/mod/mod_remoteip.html#page-header
6+
'x-client-ip', // Apache https://httpd.apache.org/docs/2.4/mod/mod_remoteip.html#page-header
77
'cf-connecting-ip', // Cloudflare
88
'fastly-client-ip', // Fastly
99
'x-cluster-client-ip', // GCP
@@ -13,7 +13,7 @@ export const headersToCheck: IPHeaders[] = [
1313
'x-forwarded', // RFC 7239
1414
'appengine-user-ip', // GCP
1515
'true-client-ip', // Akamai and Cloudflare
16-
'cf-pseudo-ipv4', // Cloudflare
16+
'cf-pseudo-ipv4', // Cloudflare
1717
]
1818

1919
export const getIP = (headers: Headers, checkHeaders: IPHeaders[] = headersToCheck) => {
@@ -35,10 +35,17 @@ export const ip = (config: {
3535
* @default ['x-real-ip', 'x-client-ip', 'cf-connecting-ip', 'fastly-client-ip', 'x-cluster-client-ip', 'x-forwarded', 'forwarded-for', 'forwarded', 'x-forwarded', 'appengine-user-ip', 'true-client-ip', 'cf-pseudo-ipv4']
3636
*/
3737
checkHeaders?: IPHeaders[]
38-
} = {}) => (app: Elysia) => {
38+
/**
39+
* Only check headers regardless of the runtime environment
40+
* @default false
41+
*/
42+
headersOnly?: boolean
43+
} = {
44+
headersOnly: false
45+
}) => (app: Elysia) => {
3946
return app.derive({ as: 'global' }, ({ request }) => {
4047
// @ts-ignore
41-
if (globalThis.Bun) {
48+
if (!config.headersOnly && globalThis.Bun) {
4249
if (!app.server) throw new Error(`Elysia server is not initialized. Make sure to call Elyisa.listen()`)
4350
return {
4451
ip: app.server.requestIP(request)

0 commit comments

Comments
 (0)