Express behind a proxy: fixing express-rate-limit when every user shares one limit
You add express-rate-limit, test it locally, and everything works.
Then you deploy to Render, Railway, Fly.io, or behind Nginx.
Suddenly, one of two things happens:
Your logs show ERR_ERL_UNEXPECTED_X_FORWARDED_FOR.
Your rate limiter starts treating multiple users as the same client, causing everyone to share one request limit.
The problem is often your Express proxy configuration.
When Express cannot identify the original client IP correctly, an IP-based rate limiter can end up counting requests against the proxy's address instead.
Here's why it happens, how to configure it, and what to check before deploying the fix.
Why it happens
When your Express application sits behind a reverse proxy, it doesn't communicate directly with the original client. The proxy forwards the request to your application.
The proxy may include the original client's IP address in the X-Forwarded-For header.
However, Express does not trust forwarded headers by default.
With trust proxy disabled:
req.ip is generally derived from the address of the immediate connection.
Multiple users connecting through the same proxy can appear to share the same IP.
An IP-based rate limiter may count those requests in one shared bucket.
Newer versions of express-rate-limit also check for common proxy misconfigurations.
For example, ERR_ERL_UNEXPECTED_X_FORWARDED_FOR can appear when the request contains an X-Forwarded-For header but Express has not been configured to trust the proxy.
The library is warning you that your IP-based rate limiting may not be working as intended.
The fix: configure trust proxy correctly
Express provides the trust proxy setting to determine which proxy addresses or hops it should trust.
For example:
import express from 'express';
import rateLimit from 'express-rate-limit';
const app = express();
// Example ONLY: use 1 when your verified proxy topology
// has exactly one trusted hop between the client and Express.
app.set('trust proxy', 1);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: true,
legacyHeaders: false,
});
app.use(limiter);
The important part is:
app.set('trust proxy', 1);
This tells Express to trust one proxy hop when determining the client IP.
Set it before registering middleware that depends on req.ip, including your rate limiter.
Important: 1 is an example, not a universal setting for every hosting provider.
How many proxies should you trust?
Don't guess.
The correct value depends on your actual network topology.
For example:
Client → Express: no reverse proxy.
Client → Platform proxy → Express: one proxy hop.
Client → CDN → Load balancer → Express: potentially multiple proxy hops.
However, counting hops alone isn't always sufficient.
Express specifically warns that numeric hop-based trust can be unsafe when different network paths have different numbers of proxies. A client might be able to influence the address Express identifies if the topology isn't consistent.
Where possible, use known trusted proxy IP addresses or subnets instead of blindly trusting a hop count.
If you use a numeric setting, verify that every path to your application has the expected number of trusted hops and that your ingress proxy handles forwarded headers correctly.
Official documentation:
Express: Behind Proxies
Verify the client IP
You can temporarily add a diagnostic endpoint:
app.get('/debug-ip', (req, res) => {
res.json({
ip: req.ip,
forwardedFor: req.headers['x-forwarded-for'],
});
});
Use it to inspect what Express sees when requests pass through your actual deployment infrastructure.
But don't rely on one successful request.
Check:
Whether req.ip represents the expected client address.
Whether your proxy overwrites or sanitizes forwarded headers.
Whether requests arriving through different network paths produce the expected result.
Whether a client can change the apparent IP by supplying a forged X-Forwarded-For header.
A single mobile-data test cannot prove that your configuration is secure.
Keep this endpoint temporary, restrict access while testing, and remove it before public release.
Don't blindly set trust proxy to true
You might see examples using:
app.set('trust proxy', true);
Avoid treating this as a universal solution.
With this setting, Express trusts the leftmost address in X-Forwarded-For.
If the last trusted proxy doesn't properly overwrite or sanitize forwarded headers, a client may be able to supply a fake address.
That can allow someone to rotate their apparent IP and bypass IP-based rate limits.
Use a configuration that matches your actual trusted infrastructure instead.
express-rate-limit also has a validation warning for permissive proxy configurations.
Making it configurable
Your local environment and deployed environment might have different proxy configurations.
An environment variable lets you configure the number of trusted hops without changing the application code.
For a numeric-hop configuration:
const rawTrustProxy = process.env.TRUST_PROXY;
if (rawTrustProxy === undefined || rawTrustProxy === '') {
app.set('trust proxy', false);
} else if (/^\d+$/.test(rawTrustProxy)) {
app.set('trust proxy', Number(rawTrustProxy));
} else {
throw new Error(
'TRUST_PROXY must be a non-negative integer'
);
}
Example:
TRUST_PROXY=1
Use the value that matches your verified deployment topology.
For local development without a reverse proxy, leave the variable empty.
This example deliberately supports numeric hop counts only. If your infrastructure requires trusted IP addresses or CIDR ranges, configure and validate those separately.
Never set the value just because a hosting tutorial uses it.
Add a stricter limit for authentication routes
A general API rate limit may not be enough for sensitive endpoints.
Login and password-reset routes often need their own, stricter limits.
For example:
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: true,
legacyHeaders: false,
message: {
error: 'Too many attempts. Try again later.',
},
});
app.use('/auth', authLimiter);
This example assumes your authentication routes are mounted under /auth.
Adjust the limits to your application's needs. A rate limit is an additional abuse-prevention measure, not a replacement for proper authentication and authorization.
One more thing: multiple server instances
There's another issue worth knowing about.
express-rate-limit uses an in-memory store by default.
That works for simple deployments, but its counters aren't shared between separate server instances.
For example, if your application runs on two instances, each instance can maintain its own rate-limit counter.
This means the effective limit can be inconsistent depending on which instance receives a request.
For deployments that need consistent rate limiting across multiple instances, use a shared external store such as Redis.
See the express-rate-limit store documentation.
Deployment checklist
Before deploying, check these things:
Configure trust proxy according to your actual infrastructure.
Don't blindly use true.
Set the proxy configuration before your rate limiter.
Verify that forwarded headers are handled correctly by your ingress proxy.
Test requests through your real deployment path.
Test whether forged forwarding headers can change the apparent client IP.
Use stricter limits for sensitive authentication endpoints.
Consider a shared store when running multiple application instances.
Want this already handled?
My Express + Supabase starter includes rate limiting on authentication routes and configurable TRUST_PROXY handling.
Disclosure: I'm the author. It's a paid starter, not a security audit. Check the deployment configuration against your own hosting infrastructure before using it.
https://shaameer.gumroad.com/l/SupabaseExpressjsBackend
The configuration examples above are free to use.
If you've run into a different proxy setup, share the details in the comments. It might help another Express developer avoid the same problem.