How-To Guide

How to Handle Proxy Headers and Resolve Client IP Safely

Read X-Forwarded-For and Forwarded correctly, configure trusted proxies, and derive a client IP that cannot be spoofed by attackers.

On this page

  1. Introduction
  2. How forwarding headers are constructed
  3. Derive the client IP from the trusted position
  4. Prefer the standard Forwarded header
  5. Test that spoofing fails
  6. Use the derived IP carefully
  7. Conclusion

Introduction

Almost every production service sits behind something: a load balancer, a CDN, a reverse proxy, or a mesh sidecar. Those layers terminate the TCP connection and forward the request onward, which means the address the application sees in the socket is the proxy’s address, not the client’s. To recover the real client IP, proxies add forwarding headers. The trouble is that those headers are just strings, and a client can craft them. Trusting them blindly turns a rate limiter, an audit log, or an IP allowlist into a spoofable control.

This tutorial explains how forwarding headers are built, how to configure trust so the client IP is derived correctly, and how to test that a crafted header cannot override the real address. The examples use Node.js, but the reasoning applies to Go, Python, and Java services behind the same proxies.

How forwarding headers are constructed

The de facto header is X-Forwarded-For, a comma-separated list of addresses. When a proxy forwards a request it typically appends the address it received the connection from. So a request through one proxy yields X-Forwarded-For: client-ip, and through two yields client-ip, proxy1-ip. The header grows as it travels. If the original client sent its own X-Forwarded-For, and the first proxy appended rather than replaced, the spoofed value sits on the left and the true addresses are on the right.

The standardized alternative is Forwarded, defined in RFC 7239, which uses a key-value grammar such as for=192.0.2.60;proto=https;by=203.0.113.43. It carries more information and has a clearer grammar, but adoption is uneven, so production code often has to read both and prefer the standard one where present. Whatever the header, the trustworthy part of the chain is nearest the right, because only trusted infrastructure can add entries there.

function parseForwardedChain(header) {
  if (!header) return [];
  return header.split(',').map((entry) => {
    const m = /for=("?\[?)([^;\]"\[]+)/i.exec(entry.trim());
    if (!m) return null;
    return m[2].replace(/\]$/, '');
  }).filter(Boolean);
}

Derive the client IP from the trusted position

The safe algorithm is: know how many proxies you operate, treat their addresses as trusted, and pick the last address in the chain that is not a trusted proxy. With one trusted proxy, that is the rightmost entry. With two, it is the second from the right, because the rightmost is the last proxy that appended. This is why most frameworks expose a trusted-proxy count or a trusted CIDR list rather than a boolean trust flag: the boolean alone cannot tell you which entry to trust.

If your edge replaces the header rather than appending, the chain has exactly one entry and the algorithm is trivial. Replacing at the edge is the safest configuration: strip any inbound forwarding header, then add the single value the edge knows. This removes the ambiguity entirely and makes downstream parsing unnecessary.

import { isIP } from 'node:net';

function clientIp(req, trustedProxies) {
  const chain = parseForwardedChain(req.headers['x-forwarded-for']).filter(isIpAddress);
  // walk from the right, skipping trusted proxy addresses
  for (let i = chain.length - 1; i >= 0; i--) {
    if (!trustedProxies.has(chain[i])) return chain[i];
  }
  return req.socket.remoteAddress; // no untrusted hop -> connection address
}

function isIpAddress(v) {
  return isIP(v) === 4 || isIP(v) === 6;
}

Prefer the standard Forwarded header

When both Forwarded and X-Forwarded-For are present, prefer Forwarded for the proto and host information and use X-Forwarded-For only as a fallback for the address. Validate each entry strictly: an address must actually parse as IPv4 or IPv6, the port form is optional, and the obfuscated identifier form such as for=_hidden should be treated as unknown rather than as an address. Never treat a value that fails validation as a legitimate client address; fall through to the next candidate or to the connection address.

Do the same for scheme and host. X-Forwarded-Proto tells you whether the original request used https, which matters for building absolute URLs and for deciding whether to send a Secure cookie. Derive it from trusted infrastructure only; a client-supplied proto header can trick the app into marking a cookie Secure when the connection is actually plaintext, or into generating http links on an https site.

Test that spoofing fails

The test that matters is the adversarial one. Simulate a client sending a crafted X-Forwarded-For with a fake address, going through the trusted proxy. Assert the derived client IP is the real connection address or the edge-appended value, never the attacker’s injected one. Then repeat with several injected entries and with a malformed entry containing a newline, and confirm the parser ignores the invalid data rather than trusting it.

# attacker tries to spoof via a header; the edge replaces it, so the app sees the real ip
curl -s http://localhost:3000/whoami -H 'X-Forwarded-For: 203.0.113.9, 198.51.100.7'
# expect the address the edge appended, not 203.0.113.9

Use the derived IP carefully

The derived client IP feeds rate limits, audit logs, and geographic decisions, each with caveats. An IP is not a user: many people share a NAT address, and one user can rotate across many addresses. Use IP limits as coarse abuse controls and prefer authenticated identity for quotas. In audit logs, record the resolved IP but also note the trust boundary, because an IP-derived claim is only as strong as the proxy configuration behind it.

Keep the raw header out of place where it could be rendered or executed. A forwarding header with embedded newlines or markup is untrusted input; sanitize and length-cap it before it reaches a log viewer or an error page.

Conclusion

Forwarding headers are only as trustworthy as the proxies that write them. Know how many trusted hops precede your app, take the client IP from the rightmost untrusted entry, or have the edge replace the header entirely, and fall back to the socket address when the chain is empty. Prefer Forwarded where available, validate every entry as a real address, and never feed a client-supplied value into a security decision. Self-check with an adversarial test that injects a fake address and asserts it is ignored. Then use the resolved IP with the humility an address deserves: it identifies a connection, not a person.

Sources: MDN: X-Forwarded-For, RFC 7239: Forwarded HTTP Extension, MDN: Forwarded header.

FAQ

Why is taking the leftmost X-Forwarded-For value unsafe?
Any client can send its own X-Forwarded-For header. If the proxy appends to it rather than replacing it, the leftmost entry is attacker-supplied. Take the rightmost entry that is not from a trusted proxy, or have the edge replace the header entirely.
Should I log the raw forwarded header?
Treat it as untrusted input. Log it only after validation and length-capping, or log the resolved client IP with the trust boundary noted, so a spoofed value cannot pollute or overflow log fields.

Related Examples