realaddr
v1.0.0
Published
Get the real client IP address in Next.js, Hono, Bun, Deno, Cloudflare Workers, Express and Node.js. Secure by default: forwarding headers are only believed from proxies you trust. A modern, typed alternative to request-ip.
Maintainers
Readme
realaddr
Get the real client IP address of a request in Next.js, Hono, Bun, Cloudflare Workers, Deno, Express and Node.js, safely.
Many apps need the IP address of the user: for rate limits, logs, fraud checks or a rough location. When your app runs behind a proxy (a server that receives the request first and passes it on, like nginx, a load balancer or Cloudflare), the proxy writes the user's address into a header such as X-Forwarded-For.
The problem: users can send that header too. Most IP libraries return the first address they find in a list of headers. So anyone can pretend to be anyone with one line:
curl -H "X-Forwarded-For: 192.0.2.66" https://your-app.example/This is called spoofing: faking where a request comes from. realaddr is secure by default. It only believes forwarding headers that come from proxies you say you trust. Everything else is ignored.
Features
- Secure by default. Without settings, forwarding headers are ignored and you get the address of the computer that actually connected to your server.
- A clear trust model. Tell realaddr what is in front of your app: a number of proxies, their IP ranges, a hosting platform, or your own rule.
- Platform presets for Cloudflare, Vercel, Fly.io, Netlify, Akamai and Fastly.
- Correct parsing. Reads
X-Forwarded-Forfrom the right, supports the standardForwardedheader (RFC 7239), removes ports and brackets, and turns::ffff:192.0.2.1into192.0.2.1. - Never returns junk. The result is always a valid, normalised IP address or
undefined. - Works everywhere. Web
Request, Next.jsNextRequest, Node.js and Express requests, and Hono'sContext. Runs in Node.js, Bun, Deno and edge runtimes. - Middleware for Express (
req.clientIp) and Hono (c.get('clientIp')). - Debug mode.
getClientIpDetails()tells you where the address came from and every address it looked at. - IP helpers.
isIP,normalizeIp,inRange(CIDR matching),isPrivate,isLoopbackand more. - Small and typed. About 3.5 KB compressed. TypeScript types included. No other packages needed.
Installation
If your project uses npm:
npm install realaddrOr with another package manager:
pnpm add realaddr
yarn add realaddr
bun add realaddrDeno:
import { getClientIp } from 'npm:realaddr'Quick start
Set it up in 3 steps
Step 1. Find out what is in front of your app. Do users connect straight to your server? Is there a proxy such as nginx or a load balancer? Or does a platform such as Vercel or Cloudflare handle the requests?
Step 2. Pick the matching trust setting from this short list (the full list is in Choose what to trust):
| What is in front of your app | Setting |
|---|---|
| Nothing. Users connect straight to your server. | no setting |
| One proxy or load balancer (nginx, Caddy, AWS ALB, Heroku) | { trust: 1 } |
| Vercel | { trust: 'vercel' } |
| Cloudflare Workers | { trust: 'cloudflare' } |
Step 3. Get the address.
import { getClientIp } from 'realaddr'
app.get('/', (req, res) => {
const ip = getClientIp(req, { trust: 1 }) // => '203.0.113.7'
res.send(`Your IP address is ${ip}`)
})That's it. If realaddr cannot know the address safely, it returns undefined instead of guessing.
Table of contents
Usage
Choose what to trust
Two words first:
- The peer address is the address of the computer that opened the connection to your server. Nobody can fake it. If there is a proxy in front of your app, the peer is the proxy.
- A hop is one proxy on the way from the user to your server.
The trust option tells realaddr which proxies may report the user's address. Without it, realaddr trusts no proxy and returns the peer address.
| Your setup | Setting | What realaddr does |
|---|---|---|
| Users connect straight to your server | no setting | Returns the peer address. Ignores all headers. |
| One proxy (nginx, Caddy, AWS ALB, Heroku router) | trust: 1 | Skips 1 hop and returns the next address in X-Forwarded-For. |
| Two proxies (for example a CDN and a load balancer) | trust: 2 | Skips 2 hops. |
| Proxies with known addresses | trust: ['10.0.0.0/8', '198.51.100.10'] | Skips every address in these ranges. |
| A proxy on the same machine | trust: 'loopback' | Skips 127.0.0.0/8 and ::1. |
| Proxies in your private network | trust: 'private' | Skips 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and fc00::/7. |
| Your own rule | trust: (ip, hopIndex) => boolean | Skips every address your function returns true for. |
| A hosting platform | trust: 'cloudflare', 'vercel', 'fly', 'netlify', 'akamai' or 'fastly' | Reads that platform's own header. See Presets. |
| Moving from request-ip, for now | trust: 'all' | Unsafe. The old request-ip behaviour. See Migrating from request-ip. |
A CIDR range like 10.0.0.0/8 is a short way to write a block of addresses. The number after / says how many leading bits must match: 10.0.0.0/8 means every address that starts with 10., and 192.0.2.0/24 means every address that starts with 192.0.2..
You can mix ranges and the keywords 'loopback', 'private' and 'linklocal' in one list:
getClientIp(req, { trust: ['loopback', 'private', '173.245.48.0/20'] })Get the hop count right. If you trust more hops than you have, users can fake their address again. If you trust fewer, you get your proxy's address instead of the user's. When in doubt, use getClientIpDetails() to see the whole chain.
Why not just read X-Forwarded-For?
X-Forwarded-For is a header that proxies use to pass on the user's address. Each proxy adds the address it received the request from to the end of the list. It never removes what is already there.
Say a user at 203.0.113.7 sends a fake header, and your app is behind one proxy at 10.0.0.2:
User sends: X-Forwarded-For: 192.0.2.66
Your proxy adds: X-Forwarded-For: 192.0.2.66, 203.0.113.7
Your app's peer: 10.0.0.2Only the right end of the list was written by servers you control. Everything to the left came from the user and can be anything. So:
- Reading the first address (what request-ip does) gives
192.0.2.66: the fake one. - realaddr starts at the right, skips the proxies you trust, and returns the first address that is not one of them:
203.0.113.7.
getClientIp(req) // => '10.0.0.2' no trust: the peer (your proxy)
getClientIp(req, { trust: 1 }) // => '203.0.113.7' the real userA spoofed address lets someone get around your rate limits, hide in your logs, or make another person look guilty. That is why realaddr ignores the header until you tell it which proxies to trust.
Express
import express from 'express'
import { getClientIp } from 'realaddr'
const app = express()
app.get('/', (req, res) => {
res.send(getClientIp(req)) // users connect straight to this server
})Behind nginx or a load balancer, trust one hop:
getClientIp(req, { trust: 1 })Or use the middleware. It sets req.clientIp on every request:
import { expressClientIp } from 'realaddr/express'
app.use(expressClientIp({ trust: 1 }))
app.get('/', (req, res) => {
res.send(req.clientIp)
})req.clientIp is typed in TypeScript as soon as you import realaddr/express.
Express also has its own req.ip with app.set('trust proxy', 1). realaddr uses the same model and gives the same result. Use realaddr when you want the same code in Express, Hono, Next.js and the rest, or when you need presets, the Forwarded header or the details of the chain.
Node.js http
import { createServer } from 'node:http'
import { getClientIp } from 'realaddr'
createServer((req, res) => {
const ip = getClientIp(req, { trust: 'loopback' }) // nginx on the same machine
res.end(`Your IP address is ${ip}`)
}).listen(3000)Fastify, Koa (ctx.req) and other Node.js frameworks work the same way: pass the Node.js request.
Next.js
In a route handler (app/api/ip/route.ts) on Vercel:
import { getClientIp } from 'realaddr'
export function GET(request: Request) {
const ip = getClientIp(request, { trust: 'vercel' })
return Response.json({ ip })
}In proxy.ts (called middleware.ts before Next.js 16):
import { NextResponse, type NextRequest } from 'next/server'
import { getClientIp } from 'realaddr'
const blocked = new Set(['192.0.2.66'])
export function proxy(request: NextRequest) {
const ip = getClientIp(request, { trust: 'vercel' })
if (ip && blocked.has(ip)) {
return new NextResponse('Forbidden', { status: 403 })
}
return NextResponse.next()
}In a server component or server action, pass the headers:
import { headers } from 'next/headers'
import { getClientIp } from 'realaddr'
const ip = getClientIp(await headers(), { trust: 'vercel' })Why the setting is required. Next.js gives you a Web Request. It has the headers, but not the peer address. So without a trust setting, realaddr returns undefined: there is nothing it can safely use.
Self-hosting Next.js (next start)? Put a proxy such as nginx in front and use { trust: 1 }. Without a proxy, there is no safe answer: Next.js keeps an X-Forwarded-For header sent by the user and only fills it in when it is missing, so a fake value cannot be told apart from a real one.
Hono
import { Hono } from 'hono'
import { getClientIp } from 'realaddr'
const app = new Hono()
app.get('/', (c) => {
const ip = getClientIp(c, { trust: 'cloudflare' })
return c.text(ip ?? 'unknown')
})Or use the middleware. It stores the address so you can read it with c.get('clientIp'):
import { Hono } from 'hono'
import { honoClientIp } from 'realaddr/hono'
const app = new Hono<{ Variables: { clientIp: string | undefined } }>()
app.use(honoClientIp({ trust: 'cloudflare' }))
app.get('/', (c) => c.text(c.get('clientIp') ?? 'unknown'))Pass the Hono context c (not c.req). realaddr then finds the peer address on its own when Hono runs on Node.js (@hono/node-server), Bun, Deno, Netlify or AWS Lambda.
Bun
Bun keeps the peer address on the server object. Pass it as remoteAddress:
import { getClientIp } from 'realaddr'
Bun.serve({
fetch(request, server) {
const ip = getClientIp(request, { remoteAddress: server.requestIP(request) })
return new Response(`Your IP address is ${ip}`)
},
})Behind a proxy, add a trust setting as well: { trust: 1, remoteAddress: server.requestIP(request) }.
Cloudflare Workers
A Worker only receives requests through Cloudflare, and Cloudflare sets the CF-Connecting-IP header itself:
import { getClientIp } from 'realaddr'
export default {
fetch(request: Request) {
const ip = getClientIp(request, { trust: 'cloudflare' })
return new Response(`Your IP address is ${ip}`)
},
}Workers run on an edge runtime: a small JavaScript runtime that runs your code close to your users. It has web APIs like Request, but no Node.js modules. realaddr's main entry uses no Node.js modules, so it runs there.
Deno
Deno passes the peer address as the second argument of your handler:
import { getClientIp } from 'npm:realaddr'
Deno.serve((request, info) => {
const ip = getClientIp(request, { remoteAddress: info.remoteAddr })
return new Response(`Your IP address is ${ip}`)
})Find out where an address came from
getClientIpDetails() returns the address, its source, and every address in the chain. The chain reads from the user (left) to your server (right). The peer address, when known, is last.
getClientIpDetails(req, { trust: 1 })
// => {
// ip: '203.0.113.7',
// source: 'x-forwarded-for',
// chain: ['192.0.2.66', '203.0.113.7', '10.0.0.2'],
// }source is 'socket' for the peer address, the header name (like 'x-forwarded-for' or 'cf-connecting-ip') for a header, or 'none' when nothing was found. Log this while you set things up, to check your trust setting.
IP helpers
The helpers that realaddr uses are exported too. They have no dependencies and run everywhere:
import { isIP, normalizeIp, inRange, isPrivate } from 'realaddr'
isIP('2001:db8::1') // => 6
normalizeIp('[2001:DB8:0:0::1]:443') // => '2001:db8::1'
normalizeIp('::ffff:203.0.113.7') // => '203.0.113.7'
inRange('198.51.100.20', '198.51.100.0/24') // => true
isPrivate('10.1.2.3') // => trueAPI
getClientIp(request, options?)
function getClientIp(request: RequestLike, options?: ClientIpOptions): string | undefinedReturns the client IP address, or undefined when it cannot be known safely. The result is always a valid IP address in its normalised form.
request can be:
| Request | Where it comes from | Peer address read from |
|---|---|---|
| Web Request | Next.js, Bun, Deno, Cloudflare Workers, Vercel Edge | none (pass remoteAddress) |
| NextRequest | Next.js route handlers and proxy.ts | none |
| Headers | Next.js await headers() | none |
| Node.js IncomingMessage | node:http, Express, Fastify, Koa's ctx.req | req.socket.remoteAddress |
| Hono Context | c in Hono handlers | c.env on Node.js, Bun, Deno, Netlify, AWS Lambda |
| Option | Type | Default | What it does |
|---|---|---|---|
| trust | TrustOption | not set | Which proxies or platform headers to believe. Not set means none. See Trust values. |
| remoteAddress | string \| { address } \| { hostname } | read from the request | The peer address. Use it in Bun (server.requestIP(req)) and Deno (info.remoteAddr). Replaces the address found on the request. |
| header | 'x-forwarded-for' \| 'forwarded' | 'x-forwarded-for' | Which forwarding header to walk when trust is a number, a list or a function. Use 'forwarded' if your proxy sets the standard Forwarded header. Only one is ever read, so a user cannot add the other one. |
Invalid options (such as trust: 'cloudfare' or trust: ['10.0.0.0/33']) throw a TypeError, so mistakes show up at once.
getClientIpDetails(request, options?)
function getClientIpDetails(request: RequestLike, options?: ClientIpOptions): ClientIpDetailsSame as getClientIp(), but returns more:
| Field | Type | What it is |
|---|---|---|
| ip | string \| undefined | The client address. |
| source | IpSource | Where ip came from: 'socket', a header name such as 'x-forwarded-for', 'forwarded' or 'cf-connecting-ip', or 'none'. |
| chain | string[] | Every valid address that was looked at, from the user (left) to your server (right). The peer address is last. |
Trust values
| Value | What it does |
|---|---|
| not set, 0, 'none' | Trust no proxy. Return the peer address. |
| a number, like 1 | Trust this many hops in front of your app. Hop 0 is the peer. |
| an IP or CIDR range, like '10.0.0.0/8' | Trust proxies with these addresses. |
| a list, like ['10.0.0.0/8', 'loopback'] | Trust every address in the list. IPs, ranges and keywords can be mixed. |
| 'loopback' | Trust 127.0.0.0/8 and ::1. |
| 'private' | Trust 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and fc00::/7. |
| 'linklocal' | Trust 169.254.0.0/16 and fe80::/10. |
| (ip, hopIndex) => boolean | Your own rule. hopIndex is 0 for the peer, 1 for the right-most X-Forwarded-For entry, and so on. Only true counts. |
| a preset name | Read a platform header. See Presets. |
| 'all' | Unsafe. request-ip's behaviour: the first valid address from a list of headers. Only for migration. |
How the walk works with a number, a list or a function: realaddr starts at the peer address and moves left through X-Forwarded-For (or Forwarded). It returns the first address that is not trusted. If every address is trusted, it returns the left-most one, like Express does.
Presets
A preset reads one header that the platform sets. If the header is missing or not a valid IP, realaddr falls back to the peer address.
Only use a preset when every request reaches your app through that platform. The platform must be the one setting the header. If users can reach your server directly, they can send the header themselves.
| Preset | Header | Notes |
|---|---|---|
| 'cloudflare' | CF-Connecting-IP | Set by Cloudflare on requests to Workers and to your origin server. If your origin server can also be reached without Cloudflare, block direct traffic, or use trust: [...] with Cloudflare's IP ranges instead (Cloudflare also adds to X-Forwarded-For). |
| 'vercel' | X-Real-IP, then the right-most X-Forwarded-For entry | Vercel's request headers documentation says both hold the user's public address, and that Vercel overwrites X-Forwarded-For so users cannot fake it. If you put another proxy in front of Vercel, this no longer holds. |
| 'fly' | Fly-Client-IP | Set by the Fly.io proxy to the address it accepted the connection from. |
| 'netlify' | X-NF-Client-Connection-IP | Set by Netlify. |
| 'akamai' | True-Client-IP | Only set when the True-Client-IP header is turned on in your Akamai property. Make sure Akamai is set to not let users send their own value. |
| 'fastly' | Fastly-Client-IP | Set by Fastly, but Fastly does not always replace a value the user sent. Overwrite it in your service, for example with set req.http.Fastly-Client-IP = client.ip; in VCL. |
expressClientIp(options?) (from realaddr/express)
import { expressClientIp } from 'realaddr/express'
function expressClientIp(options?: ExpressClientIpOptions): ExpressClientIpMiddlewareMiddleware for Express 4 and 5 and Connect. Sets req.clientIp.
| Option | Type | Default | What it does |
|---|---|---|---|
| property | string | 'clientIp' | The name of the property set on req. |
| trust, remoteAddress, header | | | Same as in getClientIp(). |
honoClientIp(options?) (from realaddr/hono)
import { honoClientIp } from 'realaddr/hono'
function honoClientIp(options?: HonoClientIpOptions): HonoClientIpMiddlewareMiddleware for Hono 4. Read the address with c.get('clientIp').
| Option | Type | Default | What it does |
|---|---|---|---|
| key | string | 'clientIp' | The name of the context variable. |
| trust, remoteAddress, header | | | Same as in getClientIp(). |
IP helpers
| Function | Returns | What it does |
|---|---|---|
| isIP(value) | 0 \| 4 \| 6 | 4 for IPv4, 6 for IPv6, 0 for anything else. The value must be the address only, without brackets or a port. |
| isIPv4(value) | boolean | true for an IPv4 address like 192.0.2.1. |
| isIPv6(value) | boolean | true for an IPv6 address like 2001:db8::1. |
| normalizeIp(value) | string \| undefined | Cleans up an address: removes spaces, [ ] and a port, turns ::ffff:192.0.2.1 into 192.0.2.1, writes IPv6 in short lower-case form. undefined if the value is not an IP. |
| inRange(ip, range) | boolean | true if ip is in a CIDR range, a single address, a keyword, or a list of these. Throws a TypeError for an invalid range. |
| parseCidr(value) | Cidr \| undefined | Parses '10.0.0.0/8' into { address: '10.0.0.0', prefix: 8, version: 4 }. |
| isPrivate(ip) | boolean | true for 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and fc00::/7. |
| isLoopback(ip) | boolean | true for 127.0.0.0/8 and ::1. |
| isLinkLocal(ip) | boolean | true for 169.254.0.0/16 and fe80::/10. |
Rules the helpers follow:
- IPv4 parts with leading zeros (
192.0.2.01) and short forms (127.1) are rejected, because programs read them in different ways. - IPv6 short forms are all supported:
::,::1,2001:db8::, and IPv4 at the end (::ffff:192.0.2.1). - An IPv6 zone id (the
%eth0infe80::1%eth0, which names a network card) is accepted byisIP()andisIPv6(), like Node.jsnet.isIP().normalizeIp()removes it. It is not allowed in CIDR ranges.
Types
TypeScript types are included: ClientIpOptions, ClientIpDetails, IpSource, TrustOption, TrustPreset, TrustFunction, RequestLike, WebRequestLike, NodeRequestLike, HonoContextLike, HeadersLike, RemoteAddressInput, Cidr, RangeKeyword. From realaddr/express: ExpressClientIpOptions, ExpressClientIpMiddleware. From realaddr/hono: HonoClientIpOptions, HonoClientIpMiddleware.
realaddr never imports Express, Hono or Next.js. It only looks at the shape of the objects you pass.
Comparison
| | request-ip | @supercharge/request-ip | realaddr |
|---|---|---|---|
| Ignores forwarding headers unless you trust a proxy | No | No | Yes |
| Trusted proxies by hop count, IP range or function | No | No | Yes |
| Reads X-Forwarded-For from the right | No | No | Yes |
| Presets for hosting platforms | No | No | Yes |
| Parses the standard Forwarded header (RFC 7239) | No | No | Yes |
| Works with Web Request objects (Next.js App Router, Hono, Bun, Deno, Workers) | No | No | Yes |
| No Node.js modules, so it loads on edge runtimes | Yes | No | Yes |
| Turns ::ffff:192.0.2.1 into 192.0.2.1 | No | No | Yes |
| Express middleware | Yes | No | Yes |
| Hono middleware | No | No | Yes |
| IP helpers (CIDR matching, private ranges) | No | No | Yes |
| TypeScript types included | No | Yes | Yes |
| ESM build | No | No | Yes |
| No other packages needed | Yes | Yes | Yes |
Checked against request-ip 3.3.0 and @supercharge/request-ip 1.2.0, both last published in 2022, using their READMEs, package.json files and published code. Types for request-ip are available separately in @types/request-ip.
Migrating from request-ip
Before:
const requestIp = require('request-ip')
app.use(requestIp.mw())
app.get('/', (req, res) => {
const ip = requestIp.getClientIp(req) // can be faked with any header
res.send(ip)
})After:
const { getClientIp } = require('realaddr')
const { expressClientIp } = require('realaddr/express')
app.use(expressClientIp({ trust: 1 }))
app.get('/', (req, res) => {
const ip = getClientIp(req, { trust: 1 })
res.send(ip)
})Do it in two steps if you want to change nothing at first:
- Replace request-ip with
{ trust: 'all' }. It reads the same headers in the same order as request-ip. - Then pick a real setting from Choose what to trust and remove
'all'.
| request-ip | realaddr |
|---|---|
| requestIp.getClientIp(req) | getClientIp(req, { trust: ... }) |
| requestIp.mw() | expressClientIp({ trust: ... }) from realaddr/express |
| requestIp.mw({ attributeName: 'ip' }) | expressClientIp({ property: 'ip' }) |
| returns null when nothing is found | returns undefined |
What trust: 'all' does: it checks X-Client-IP, X-Forwarded-For (the first valid entry), CF-Connecting-IP, Fastly-Client-IP, True-Client-IP, X-Real-IP, X-Cluster-Client-IP, X-Forwarded, Forwarded-For, Forwarded, X-AppEngine-User-IP and AppEngine-User-IP, in that order. Then the peer address, then Cf-Pseudo-IPv4. This is the order in request-ip's README. Small differences:
- Addresses are normalised (
::ffff:127.0.0.1becomes127.0.0.1). - A standard
Forwardedheader (for=192.0.2.1) is parsed. request-ip only accepts a bare address there. - hapi's
request.infoand the AWS Lambda event are not read. PassremoteAddressinstead.
trust: 'all' is unsafe. Any user can choose the address it returns. Use it only while you move over.
Notes and limitations
- A Web
Requesthas no peer address. In Next.js, Cloudflare Workers and other edge runtimes, the request object does not say who connected. Without atrustsetting orremoteAddress, realaddr returnsundefinedon purpose, because every header could be fake. - Hop counts and lists with a Web
Request. When the peer address is unknown, realaddr assumes the peer is your proxy (hop 0) and starts at the right-mostX-Forwarded-Forentry. PassremoteAddresswhen you can, so the peer is checked too. - Presets trust the header completely. They are only safe when users cannot reach your app without going through the platform.
- One forwarding header at a time. realaddr walks
X-Forwarded-Forby default, orForwardedwithheader: 'forwarded'. It never mixes them. - Bad entries are dropped. Values in
X-Forwarded-FororForwardedthat are not valid IP addresses, and hidden names such asfor=_hiddenorfor=unknown, are left out of the chain. - IPv6 with a port needs brackets.
[2001:db8::1]:443works. Without brackets,2001:db8::1:443is itself a valid IPv6 address, so it is read as one. - Cloudflare's IP ranges are not included, because they change. Copy them from cloudflare.com/ips if you need them.
- An IP address is not a person. Many users can share one address (offices, mobile networks, VPNs), and one user can change address. Keep this in mind for rate limits and bans.
Requirements
- Node.js 20 or newer, Bun, Deno, Cloudflare Workers, the Vercel Edge Runtime, or another runtime with standard JavaScript.
- Works with
importandrequire. - TypeScript types included. No other packages needed.
- The middleware works with Express 4 and 5 and with Hono 4. realaddr does not install them.
License
MIT
