← All notes

2 min read

X-Forwarded-For is not your visitor's IP

Rate limiting by IP sounds simple until you ask where the IP comes from. Why the first X-Forwarded-For entry is whatever the client wants it to be.

On this page

The contact form and the admin login on this site are rate limited per IP address. When I moved the site to Railway, I had to decide again where that IP comes from, and it's a good reminder of a classic mistake.

The trap

Behind a proxy, your app doesn't see the visitor's connection. It sees the proxy. So proxies add headers, and the best-known one is X-Forwarded-For: a list of addresses, one appended by each proxy along the way.

The catch is the first entry. Many examples take it as "the client IP", but the client can send its own X-Forwarded-For header, and proxies append to it instead of replacing it. A request like this:

bash
curl -H "X-Forwarded-For: 203.0.113.7" https://example.com/api/contact

arrives with 203.0.113.7 as the first entry. An attacker who changes that value on every request gets a fresh rate limit every time. The limiter still runs. It just doesn't limit anything.

The fix

Use a header that only your own infrastructure can set. Railway's edge overwrites X-Real-IP on every public request, so whatever the client sends there is replaced:

client-ip.ts
/** * Client IP for rate limiting. Railway's edge overwrites X-Real-IP on every public * request, while X-Forwarded-For can carry client-supplied (spoofable) entries. */export function clientIp(headers: Headers): string {  return headers.get('x-real-ip')?.trim() || 'unknown';}

Which header is trustworthy depends entirely on your hosting. Other platforms use other headers, or the last entry of X-Forwarded-For, which the closest proxy added. Read your platform's documentation, then test it with a forged header like the curl above.

Every proxy in front changes the answer

This site's DNS is on Cloudflare, set to "DNS only". If Cloudflare proxied the traffic, Railway would see Cloudflare's servers as the client, and every visitor would share a handful of IPs and one rate limit.

Takeaways

  • The first X-Forwarded-For entry is client-controlled. Never rate limit by it.
  • Trust only headers your own edge sets or overwrites.
  • Test your limiter with a forged header. If it lets the request through, it's not a limiter.