@prexjs/proxy-address
v1.0.0
Published
Determine the true client IP address of a proxied HTTP request based on configurable trust rules.
Readme
@prexjs/proxy-address
Determine the true client IP address of a proxied HTTP request based on configurable trust rules.
@prexjs/proxy-address determines the real client IP address behind reverse proxies (load balancers, CDNs, API gateways) by traversing X-Forwarded-For address chains and stopping at the first untrusted upstream hop.
Features
- Traverses reverse proxy IP chains (
X-Forwarded-For) backwards from the socket connection. - Built-in trust aliases:
'loopback','linklocal','uniquelocal'. - Flexible trust configurations (IP strings, CIDR subnets, arrays, or custom predicate functions).
- High-performance CIDR subnet evaluation via
@prexjs/ipaddress. - Dual ES Module (
.mjs) and CommonJS (.cjs) support with TypeScript definitions.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/proxy-address
# pnpm
pnpm add @prexjs/proxy-address
# Yarn
yarn add @prexjs/proxy-address
# Bun
bun add @prexjs/proxy-addressQuick start
import http from 'node:http';
import proxyAddress from '@prexjs/proxy-address';
const server = http.createServer((req, res) => {
// Trust loopback proxies and private local subnets
const clientIp = proxyAddress(req, ['loopback', 'uniquelocal']);
console.log('Client IP:', clientIp);
res.end(`Your verified client IP is ${clientIp}`);
});Both default and named exports are supported:
import proxyAddress, {
allAddress,
compile,
type TrustArgument,
type TrustFunction,
} from '@prexjs/proxy-address';Examples
Custom trust function
import proxyAddress from '@prexjs/proxy-address';
// Trust the first two proxy hops only
const clientIp = proxyAddress(req, (addr, i) => i < 2);Pre-compiling trust checkers
import { compile } from '@prexjs/proxy-address';
// Pre-compile trust rules for fast evaluation
const isTrusted = compile(['10.0.0.0/8', '172.16.0.0/12']);
console.log(isTrusted('10.1.2.3', 0)); // true
console.log(isTrusted('203.0.113.1', 0)); // falseCompatibility
@prexjs/proxy-address is designed for Node.js, Deno, and Bun HTTP servers and frameworks (Express, Connect, Koa).
License
This project is licensed under the MIT License. See LICENSE for the full license text.
Related projects
- prex.js — prex.js monorepo and ecosystem.
