Introduction
Learn about Network module for secure client IP extraction with proxy support.
What is Network?
The Network module provides secure utilities for extracting the real client IP address from HTTP requests, with built-in support for popular reverse proxies and CDNs like Cloudflare, AWS, Vercel, and more.
Why is this important?
When your application is behind a proxy or CDN, the direct connection IP (req.socket.remoteAddress) will be the proxy's IP, not the client's. Headers like X-Forwarded-For can be spoofed by malicious clients, making IP extraction a security concern.
The Network module solves this by:
- Prioritizing proprietary headers (like
CF-Connecting-IPfor Cloudflare) that cannot be spoofed - Safely parsing
X-Forwarded-Forfrom right to left, trusting only configured proxies - Providing utilities to validate and normalize IP addresses
Quick Example
import { Network } from "toolkitify/network";
// Create a network instance for your proxy.
const network = new Network({ proxy: "cloudflare" });
// In your Express middleware.
app.use((req, res, next) => {
const { ip, trusted } = network.getClientIP(req);
console.log(`Client IP: ${ip}, Trusted: ${trusted}`);
next();
});
Supported Proxies
| Proxy | Headers Used |
|---|---|
cloudflare | cf-connecting-ip, cf-pseudo-ipv4 |
aws | x-amzn-source-ip, x-amz-cf-id |
vercel | x-vercel-forwarded-for, x-real-ip |
fastly | fastly-client-ip |
akamai | true-client-ip, akamai-origin-hop |
nginx | x-real-ip |
gcp | x-cloud-trace-context, x-appengine-user-ip |
azure | x-azure-clientip, x-client-ip |
fly | fly-client-ip |
render | x-render-origin-ip |
railway | x-railway-client-ip |
heroku | x-forwarded-for |