Skip to content
API Guides

X-Forwarded-For: Get the Real Client IP Behind a Proxy

X-Forwarded-For lists the client and each proxy; clients can forge it: httpbin kept our fake 198.51.100.23. Read it right to left, skip trusted proxies.

ByGeoIPHub TeamPublishedReading time16 min read
A small glass figure sends a blue glass envelope along a ribbon through frosted white arches on a white base; a violet tag sits before the arches, pale blue tags after each one, and a large blue lens at the far right reads the ribbon
Output
X-Forwarded-For: <client>, <proxy>, ..., <proxyN> X-Forwarded-For: 45.33.32.156, 162.158.1.1

That is MDN's syntax plus one example, "assuming well-behaved client and proxies".

On 25 November 2026 GeoIPHub sent forged headers to public echo servers. httpbin.org kept our fake 198.51.100.23 and appended our real address after it. Three Cloudflare-served sites, geoiphub.com among them, answered a forged CF-Connecting-IP with HTTP 403 and a forged X-Forwarded-For (XFF from here on) with 200. A 76-line Node function that walks the list from the right picked the client out of a five-entry test chain, and its 11 tests pass (one fetches Cloudflare's lists live).

What the X-Forwarded-For header contains, and who writes each entry

Each proxy appends to the header the address that connected to it, and the client can send a starting value of its own, so only the rightmost entries come from proxies you trust. Take a stand-in stack. The client is 45.33.32.156, scanme.nmap.org, Nmap's public test host on Linode; it sent us nothing. 162.158.1.1 stands in for a Cloudflare edge (inside 162.158.0.0/15 on Cloudflare's list today), and 10.0.1.17 and 10.0.1.20 are stand-in private proxies.

  1. The client sends 198.51.100.23, 192.0.2.44 as its own header. Both are fake documentation addresses.
  2. Cloudflare's edge appends the address that connected to it: 45.33.32.156.
  3. Your first internal proxy, 10.0.1.17, appends the edge that connected to it: 162.158.1.1.
  4. Your second proxy, 10.0.1.20, appends 10.0.1.17 and opens the connection to your app.

Your app receives 198.51.100.23, 192.0.2.44, 45.33.32.156, 162.158.1.1, 10.0.1.17 on a connection from 10.0.1.20.

When a request carries several XFF header lines, MDN says the addresses "must be treated as a single list", first line first.

The connecting address (the socket peer: REMOTE_ADDR in PHP, req.socket.remoteAddress in Node, $remote_addr in nginx) is the one value a client can't forge at the HTTP layer, but behind a proxy it is your proxy, so you need the header.

X-Forwarded-For spoofing: what our forged requests showed

A forged XFF reaches your code unless something on the path removes it. We sent these on 25 November 2026, 05:32 to 05:33 UTC, with curl 8.7.1; <our address> is our own, replaced:

Output
$ curl -s -H "X-Forwarded-For: 198.51.100.23" https://httpbin.org/ip { "origin": "198.51.100.23,<our address>" } $ curl -s -H "X-Forwarded-For: 198.51.100.23" \ -H "X-Forwarded-For: 192.0.2.44" https://httpbin.org/ip { "origin": "198.51.100.23,192.0.2.44,<our address>" } $ curl -s -o /dev/null -w "%{http_code}\n" \ -H "CF-Connecting-IP: 203.0.113.9" https://geoiphub.com/robots.txt 403

What each endpoint did:

  • httpbin.org kept the forged entry and appended our address. Two header lines were joined in order, as MDN says servers must.
  • httpbin.org echoed a client-sent Cf-Connecting-Ip: 203.0.113.9 verbatim. Its responses carried no server: cloudflare or cf-ray header.
  • Three Cloudflare-served hostnames we tried (postman-echo.com, geoiphub.com, www.cloudflare.com) answered a forged CF-Connecting-IP with HTTP 403 (body error code: 1000 on postman-echo.com and geoiphub.com) and a forged XFF with 200. We saw status codes, not what reached their origins.
  • The 403 is an observation, not a documented feature. Cloudflare's Error 1000 page, "DNS points to prohibited IP" (dateModified 2026-05-06), is about loops and re-proxying, but lists "The request includes a CF-Connecting-IP header." Its two-XFF and over-100-characters causes both got 200 on geoiphub.com.
  • /cdn-cgi/trace on geoiphub.com and www.cloudflare.com showed our real connecting address under every forged header we sent.

A forged address can dodge per-IP limits, enter an allowlist, or borrow a clean fraud score. On IPv6 even an honest client can rotate addresses, which is why we rate limit IPv6 by prefix.

Which X-Forwarded-For IP is the client, first or last? Walk from the right

When X-Forwarded-For holds multiple IPs, start at the rightmost entry, skip every address on your trusted proxy list, and stop at the first address that is not on it. If the connecting address is not a trusted proxy, ignore the header and use the connecting address.

MDN describes two ways: a trusted proxy count, searched "from the rightmost by that count minus one", or a trusted proxy list, "searched from the rightmost, skipping all addresses that are on the trusted proxy list."

Keep a list of trusted networks, not a hop count. A count breaks the day someone adds a CDN in front.

nginx does the same with real_ip_recursive on. MDN's caveat: that address "may belong to an untrusted intermediate proxy rather than the actual client, but it is the only IP suitable to identify a client for security purposes."

Glass tiles in a row above a glass track with markers pointing left; the rightmost tiles sit inside glowing blue brackets, a glass lens is stopped over the next tile, which glows solid blue, and the tiles to its left are grey and cracked
Read from the right, skip the hops you trust, and stop at the first one you don't.

In our chain the walk skips 10.0.1.17 and 162.158.1.1, both in the trusted list, and stops at 45.33.32.156. The forged entries to its left are never read.

A trusted-hop function in plain Node, with 11 passing tests

One function, no framework; it returns the connecting address whenever it can't be sure:

JavaScript
import { isIP } from "node:net"; export function normalize(raw) { let s = String(raw).trim(); const bracketed = s.match(/^\[([^\]]+)\](?::\d+)?$/); if (bracketed) s = bracketed[1]; else if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(s)) s = s.slice(0, s.lastIndexOf(":")); const mapped = s.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i); if (mapped) s = mapped[1]; return isIP(s) ? s.toLowerCase() : null; } function toBigInt(ip) { if (isIP(ip) === 4) { return { bits: 32, value: ip.split(".").reduce((v, p) => (v << 8n) | BigInt(p), 0n) }; } const [head, tail = ""] = ip.split("::"); const h = head ? head.split(":") : []; const t = tail ? tail.split(":") : []; const groups = ip.includes("::") ? [...h, ...Array(8 - h.length - t.length).fill("0"), ...t] : h; return { bits: 128, value: groups.reduce((v, g) => (v << 16n) | BigInt(parseInt(g, 16)), 0n) }; } export function parseCidrs(list) { return list.map((cidr) => { const [addr, len] = cidr.trim().split("/"); const net = toBigInt(normalize(addr)); const prefix = BigInt(len ?? net.bits); const mask = ((1n << BigInt(net.bits)) - 1n) ^ ((1n << (BigInt(net.bits) - prefix)) - 1n); return { bits: net.bits, mask, value: net.value & mask }; }); } export function inRanges(ip, ranges) { const ipn = normalize(ip); if (!ipn) return false; const t = toBigInt(ipn); return ranges.some((r) => r.bits === t.bits && (t.value & r.mask) === r.value); } export function forwardedList(headerValue) { const lines = Array.isArray(headerValue) ? headerValue : headerValue ? [headerValue] : []; return lines.flatMap((line) => line.split(",")).map((e) => e.trim()).filter(Boolean); } export function clientIp({ xff, socketAddress }, trusted) { const socket = normalize(socketAddress); if (!socket || !inRanges(socket, trusted)) return socket; const entries = forwardedList(xff); for (let i = entries.length - 1; i >= 0; i--) { const ip = normalize(entries[i]); if (!ip) return socket; if (!inRanges(ip, trusted)) return ip; } return socket; } export async function loadCloudflareRanges(fetchImpl = fetch) { const urls = ["https://www.cloudflare.com/ips-v4", "https://www.cloudflare.com/ips-v6"]; const texts = await Promise.all( urls.map(async (u) => { const res = await fetchImpl(u); if (!res.ok) throw new Error(`${u} returned ${res.status}`); return res.text(); }), ); const cidrs = texts.flatMap((t) => t.split("\n")).map((l) => l.trim()).filter(Boolean); return { cidrs, ranges: parseCidrs(cidrs) }; } export function cloudflareClientIp({ cfConnectingIp, socketAddress }, cloudflareRanges) { const socket = normalize(socketAddress); if (!socket || !inRanges(socket, cloudflareRanges)) return socket; if (typeof cfConnectingIp !== "string" || cfConnectingIp.includes(",")) return socket; return normalize(cfConnectingIp) ?? socket; }

Our trace script runs it on the five-entry chain, trusting 10.0.0.0/8 and 162.158.0.0/15:

Terminal
node trace.mjs
Output
socket 10.0.1.20 trusted=true 10.0.1.17 trusted, skip 162.158.1.1 trusted, skip 45.33.32.156 first untrusted, client clientIp: 45.33.32.156

The tests, run with node --test client-ip.test.mjs on Node 24.20.0, 25 November 2026:

Output
ℹ tests 11 ℹ pass 11 ℹ fail 0

Three choices are deliberate:

  • The connecting-address check comes first. From an untrusted address, the header is never read.
  • A missing header, or an unparseable entry inside the trusted part, returns the connecting address, not a guess further left.
  • Header lines are joined in order. Node's req.headers already joins duplicate header lines with ", " (we checked on Node 24.20.0); the array input is for req.headersDistinct or rawHeaders.

Clean the value before you use it: ports, brackets, ::ffff: and unknown

An entry isn't always a bare address. AWS's load balancer has a client-port option that writes 12.34.56.78:8080, and for IPv6 it adds brackets: [2001:db8:85a3:8d3:1319:8a2e:370:7348]:8080. IPv4-mapped ::ffff:10.0.1.20 is one of our test cases. unknown and obfuscated names such as _hidden are valid identifiers in the RFC 7239 Forwarded header. normalize strips ports, brackets and the mapped prefix, and returns null for names.

Skip this step and the lookup fails. On 25 November 2026 GeoIPHub's API answered all four raw forms below with HTTP 400:

Output
203.0.113.7:8080 {"message":"Invalid IP address format"} [2001:db8::1] {"message":"Invalid IP address format"} unknown {"message":"Invalid IP address format"} [2001:db8::1]:8080 {"message":"Invalid IP address format"}

We sent the brackets URL-encoded; with curl, use -g or %5B and %5D.

CF-Connecting-IP and True-Client-IP: check Cloudflare's ranges, then lock the origin

Trust CF-Connecting-IP only from Cloudflare's ranges, and know that this range check is required but not sufficient. Cloudflare recommends it over XFF because it has "a consistent format containing only one IP address." From Cloudflare's HTTP headers page (dateModified 2026-11-15):

  • Edge to origin: CF-Connecting-IP "will only be sent on the traffic from Cloudflare's edge to your origin web server."
  • True-Client-IP "is only available on an Enterprise plan" and differs only in name. In a stacked CDN, if you don't add it yourself, "its value can be spoofed to any value."
  • Pseudo IPv4 set to Overwrite Headers replaces CF-Connecting-IP and XFF "with a pseudo IPv4 address while preserving the real IPv6 address in CF-Connecting-IPv6 header."

The gap is Workers. Cloudflare: "For Worker subrequests destined for a non-Cloudflare customer zone, the Worker script controls the client IP headers: both CF-Connecting-IP and x-real-ip can be altered by the Worker." Someone else's Worker fetching your origin arrives from a Cloudflare address, so a range check accepts it. Cloudflare's fix: "use zone-level or per-hostname Authenticated Origin Pulls with your own certificate, or Cloudflare Tunnel." The range check keeps out direct clients; Authenticated Origin Pulls or Tunnel keep out other people's Workers.

In the file above, loadCloudflareRanges fetches ips-v4 and ips-v6 (15 and 7 ranges on 25 November 2026) and throws on a failed fetch; cloudflareClientIp reads the header only when the connecting address is Cloudflare's, and rejects a comma list. Keeping the last good list, and trusting no Cloudflare header if you never had one, is your caller's job. Cloudflare says the list "needs to be updated regularly"; its ranges page reads "Last updated: Sep 28, 2023". Refresh on a timer or at deploy, never inside the request.

How GeoIPHub's API does it. It trusts only its own reverse proxy as a hop, then takes CF-Connecting-IP only when the connecting address is inside Cloudflare's published ranges and the header holds one valid IP; otherwise it uses the connecting address. The ranges are a hand-maintained copy, not a fetch on the request path, and on 25 November 2026 the copy matched Cloudflare's lists. The keyless limit is counted on that address. Between 05:38:08 and 05:38:15 UTC its x-ratelimit-remaining header read 29 with no forged header, then 28 and 27 with two different forged XFF values: the keyless counter kept falling. We have not tested whether another account's Worker can reach our origin.

X-Forwarded-For vs X-Real-IP vs Forwarded (RFC 7239)

XFF is a list that each proxy appends to, X-Real-IP holds one address that a proxy sets, and Forwarded (RFC 7239) is the standard version, which MDN says is "much less frequently used". Each is only as good as the proxy that wrote it.

X-Real-IP

  • The default real_ip_header in nginx's realip module.
  • Cloudflare strips it "when no Worker subrequest is triggered". A client can send one too.

Forwarded

  • RFC 7239, Standards Track, June 2014, with for=, by=, proto= and host= parameters.
  • IPv6 is quoted and bracketed: for="[2001:db8:cafe::17]".
  • XFF converts "by prepending each element with "for=""; §8.1 says the header "cannot be relied upon to be correct".

What Cloudflare, Vercel, AWS ALB and nginx do with a client-sent X-Forwarded-For

Cloudflare and AWS Application Load Balancer append to a client-sent XFF by default, Vercel overwrites it, and nginx does whatever its realip settings say, so the entry you trust depends on which of them is your last hop. Docs re-read 25 November 2026:

Cloudflare (HTTP headers, dateModified 2026-11-15)

  • With no incoming XFF, Cloudflare sets one "identical" to CF-Connecting-IP.
  • With one present, "Cloudflare will append the IP address of the HTTP proxy connecting to Cloudflare to the header."
  • Behind Cloudflare, read CF-Connecting-IP after the range check, and ignore XFF.

Vercel (request headers, last updated 2025-12-13)

  • Vercel overwrites XFF: "If you are trying to use Vercel behind a proxy, we currently overwrite the X-Forwarded-For header and do not forward external IPs."
  • On Vercel, read x-vercel-forwarded-for, documented as "identical to the x-forwarded-for header"; the latter "could be overwritten if you're using a proxy on top of Vercel".
  • Our reading of both docs, not tested: with Cloudflare in front of Vercel, that header holds the Cloudflare edge, and the client is in CF-Connecting-IP, safe only when the edge address is in Cloudflare's ranges.
  • Enterprise customers "can purchase and enable a trusted proxy" to allow a custom value.

AWS Application Load Balancer (X-Forwarded headers, undated)

  • AWS Application Load Balancer sets routing.http.xff_header_processing.mode to append by default, or to preserve or remove.
  • Our reading, not AWS's words: in append mode with the ALB as your last hop, the rightmost entry is the address that connected to the ALB.
  • AWS: entries "can only be considered trustworthy if added by systems that are properly secured within the network."

nginx (realip module)

  • The module "is not built by default" (--with-http_realip_module).
  • set_real_ip_from names trusted addresses; real_ip_header defaults to X-Real-IP.
  • In nginx, with real_ip_recursive off the realip module takes the last address in the header; with it on, the last non-trusted one.
  • When nginx proxies onward, $proxy_add_x_forwarded_for is the incoming header with $remote_addr appended. If nginx is the first hop from the internet, set the header to $remote_addr instead, so nothing a client wrote survives.

From nginx's documentation, not run by us:

nginx
set_real_ip_from 10.0.0.0/8; set_real_ip_from 162.158.0.0/15; real_ip_header X-Forwarded-For; real_ip_recursive on;

Add one set_real_ip_from line for each range on Cloudflare's lists.

Framework settings that decide which entry you get

In Express, trust proxy set to true takes the left-most entry, which a client can forge unless your last trusted proxy removes or overwrites the header; set it to your proxies' addresses instead and Express returns the untrusted address nearest the app. In Next.js on Vercel, read the header named in the Vercel block; on any other host, run the same walk. In PHP and Python, check the connecting address against your trusted list before you read the header.

Does a VPN or proxy show up in X-Forwarded-For?

A VPN does not show up in XFF, and a proxy shows up only if it adds the header. A transparent HTTP proxy may add XFF or Via, revealing the address behind it; an anonymous proxy is built not to. A VPN tunnels packets and does not edit HTTP headers, so the server sees the exit address. More on how HTTP proxies announce themselves.

Where header logic stops protecting you

Reading XFF or CF-Connecting-IP correctly protects you only while clients cannot reach your origin directly and your trusted list is current:

  • A directly reachable origin. MDN: if the server can be reached directly from the internet, "no part" of the list "can be considered trustworthy". Fix the network first (a Cloudflare IP allowlist, Authenticated Origin Pulls or Tunnel); no parser saves you.
  • A stale trusted list. Miss a new range and you lose the client; keep an old one and you may trust a stranger.
  • The first untrusted hop may be a corporate or third-party proxy, not the person.

Key your shared rate-limit counter on the address the walk returns, never the raw header, or every forged value starts a fresh count. And a forwarded address points at a person as much as the connecting address does, so keep it under the same retention rules.

Look up the client IP the walk returned

The API takes the address you picked in the path; it does not guess the caller. To check one address by hand, paste it into the IP lookup tool. Looked up 25 November 2026, 05:35:48 UTC, keyless, response trimmed:

Terminal
curl https://api.geoiphub.com/v1/lookup/45.33.32.156
JSON
{ "ip": "45.33.32.156", "asn": { "asn": 63949, "org": "AKAMAI-LINODE-AP - Akamai Connected Cloud" }, "geo": { "country_code": "US", "city": "Fremont" }, "detection": { "is_hosting": true, "hosting_provider": "Linode / Akamai", "hosting_type": "hosting" }, "scoring": { "fraud_score": 15, "recommended_action": "allow" } }

A hosting address scoring 15, allow: hosting alone isn't fraud. The response carried x-ratelimit-limit: 30; a free key in x-api-key gives 1,500 lookups a day, every field. The API's ip field echoes what was looked up, so a wrong hop shows at once. To call it at the right moments, add the lookup to signup, login and checkout; the request format is in the API reference.

httpbin kept the forged 198.51.100.23, and a leftmost read would have taken it; your walk skips it. Copy the function and its tests, run them against your own proxy list, then send the address it returns to the keyless endpoint.

Frequently Asked Questions

Can X-Forwarded-For be spoofed?

Yes. Any client can send the header with any value. On 25 November 2026 httpbin.org kept our forged 198.51.100.23 and appended our real address after it. Only entries added by proxies you trust are safe for rate limits, access control or fraud scoring.

Should I use the first or last IP in X-Forwarded-For?

Neither by default. If the connection came from a proxy you trust, start at the rightmost entry, skip the addresses of proxies you trust, and use the first one that isn't one of them. The leftmost is only what the client claims. With only one reverse proxy, MDN says the rightmost address should be used.

Does Cloudflare replace X-Forwarded-For?

Not by default. Cloudflare's documentation says it appends the address that connected to it; Pseudo IPv4 set to Overwrite Headers writes a pseudo IPv4 address instead, and the Remove visitor IP headers Managed Transform can trim it. Read CF-Connecting-IP, and only from Cloudflare's ranges.

What is the difference between X-Forwarded-For and X-Real-IP?

X-Forwarded-For is a list each proxy appends to; X-Real-IP holds one address that a proxy sets. nginx's realip module reads X-Real-IP by default, and Vercel documents it as identical to X-Forwarded-For.

Can a client send its own CF-Connecting-IP?

It can try. On 25 November 2026 three Cloudflare-served sites answered it with HTTP 403 (Cloudflare lists that header under Error 1000), while httpbin.org, which showed no sign of Cloudflare, echoed it back unchanged. GeoIPHub's API reads it only when the connection comes from Cloudflare's ranges; a Worker can also set it, so Authenticated Origin Pulls or Cloudflare Tunnel close that gap.

Which IP should I send to an IP lookup API?

The address your right to left walk returns, without ports or brackets. On 25 November 2026 GeoIPHub's API answered HTTP 400 to 203.0.113.7:8080, [2001:db8::1] and unknown, and its ip field echoes the address it looked up, so you can confirm you sent the right hop.

Written by

GeoIPHub Team

The team behind the GeoIPHub API

Written by the GeoIPHub team, the people who build the GeoIPHub IP intelligence API and its scanner. Drafts are prepared with AI assistance and edited by the team; API examples are real lookups against the live API unless labelled illustrative.

Share this article
More articles

Related posts