Demo, all content is generated
Question

express-rate-limit throws ValidationError about X-Forwarded-For on Replit

Open · 563 views · asked by mateo_g · edited

Added express-rate-limit to my Express API after ChatGPT recommended it. On Replit deployment the logs show:

ValidationError: The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.

And I think all users share the same limit now, because after a few people use it everybody gets 429.

What I’ve tried

ChatGPT said to add app.set('trust proxy', true). The error went away. But I read somewhere that it's insecure?

Comment
What does req.ip return right now? Probably the same address for everyone. chidi_eze · edited
Update: 1 was correct for my deployment, checked with the log trick. mateo_g · edited

3 answers

chidi_eze · edited

What happens: your app runs behind Replit's proxy, so every request's direct IP is the proxy's IP. All users look like one user → one shared limit → 429 for everyone.

trust proxy tells Express to read the real client IP from X-Forwarded-For. But true means 'trust the whole header', and a client can put anything in it, so an attacker rotates fake IPs and bypasses your limit.

Use a number instead, the count of proxies in front of you:

app.set('trust proxy', 1)

Then verify: add a temporary /ip route that returns req.ip, open it from your phone and laptop, you should see two different real IPs.

Comment
With 1 I see my real IP. With true I could fake it with curl, you're right. mateo_g · edited
grace_mw · edited

Also: if your users are logged in, key the limiter on user id (keyGenerator: (req) => req.user.id). IP limits hit people on shared networks, like a whole school or office behind one IP.

Comment
elif_y · edited

Before settling on 1, log req.headers['x-forwarded-for'] once in production. If you see two IPs added by the platform (client, proxy), you need 2. The right number depends on how many hops the host puts in front of you.

Comment