Get client IP from request headers for Vafast framework
Get the client ip address in Tirne.
It works with Bun, Cloudflare, Fastly and other runtimes.
Please consider starring the repository to show your ❤️ and support.
Requires Bun v1.0.4 or above.
Requires Tirne v1.0.9 or above.
``bash`
bun a @vafast/ip
This middleware adds an ip property to the context object. It contains the client ip address.
`ts
import { Server, json } from "tirne";
import { ip } from "@vafast/ip";
const ipMiddleware = ip();
const routes = [
{
method: "GET",
path: "/",
handler: (request: Request, context: any) => {
return json({ ip: context.ip });
},
middleware: [ipMiddleware],
},
];
const server = new Server(routes);
export default {
fetch: (req: Request) => server.fetch(req),
};
`
For Bun runtime, We use server.requestIP introduced in Bun v1.0.4 to get the client ip address and early return it.
It relies on headers for runtimes other than Bun.
Cloudflare and other providers send back specific headers, containing the IP address. For example CF-Connecting-IP for Cloudflare and Fastly-Client-IP for Fastly.
We also add support for X-Forwarded-For header (de-facto standard header) and other various headers.
Priority list:
1. User specified
2. X-Forwarded-For (de-facto standard header)X-Real-IP
3. (Apache)X-Client-IP
4. (Nginx)CF-Connecting-IP
5. (Cloudflare)Fastly-Client-IP
6. (Fastly)X-Cluster-Client-IP
7. (GCP)X-Forwarded
8. (RFC 7239)Forwarded-For
9. (RFC 7239)Forwarded
10. (RFC 7239)appengine-user-ip
11. (GCP)true-client-ip
12. (Akamai and Cloudflare)cf-pseudo-ipv4
13. (Cloudflare)
You can even specify your own headers if you want to as following
`ts
import { Server, json } from "tirne";
import { ip } from "@vafast/ip";
const ipMiddleware = ip({ checkHeaders: ["X-Forwarded-For", "X-Real-IP"] });
const routes = [
{
method: "GET",
path: "/",
handler: (request: Request, context: any) => {
return json({ ip: context.ip });
},
middleware: [ipMiddleware],
},
];
`
or
`ts
import { Server, json } from "tirne";
import { ip } from "@vafast/ip";
const ipMiddleware = ip({ checkHeaders: "X-Forwarded-For" });
const routes = [
{
method: "GET",
path: "/",
handler: (request: Request, context: any) => {
return json({ ip: context.ip });
},
middleware: [ipMiddleware],
},
];
`
You can also switch to Headers only mode by setting headersOnly to true. This will only check headers and not the server.requestIP property.
`ts
import { Server, json } from "tirne";
import { ip } from "@vafast/ip";
const ipMiddleware = ip({ headersOnly: true });
const routes = [
{
method: "GET",
path: "/",
handler: (request: Request, context: any) => {
return json({ ip: context.ip });
},
middleware: [ipMiddleware],
},
];
`
Please use run the command setting environment variable NODE_DEBUG to either * or @vafast/ip`
MIT
Copyright (c) 2023 Gaurish Sethia, All Rights Reserved.