Linux & Web Servers

Behind nginx, express-rate-limit saw every visitor as one IP

when I put Nujoom’s Express backend behind nginx, express-rate-limit started throwing this:

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. See https://express-rate-limit.github.io/ERR_ERL_UNEXPECTED_X_FORWARDED_FOR/ for more information.
  ...
  code: 'ERR_ERL_UNEXPECTED_X_FORWARDED_FOR',

it reads like a crash. it isn’t one. reproduced with express 4.22 and express-rate-limit 7.5: the error is logged once, and the request is still served with a 200.

what’s actually wrong is in req.ip. without trust proxy, Express ignores X-Forwarded-For and uses the socket address, which behind a reverse proxy is the proxy:

200 ip=::ffff:127.0.0.1

express-rate-limit keys on req.ip. so every visitor counts against the same bucket, and once the limit is hit, it’s hit for everyone.

fix

// Trust nginx reverse proxy
app.set('trust proxy', 1);

same request now:

200 ip=203.0.113.9
trust proxy off: req.ip is the proxyvisitorsnginxone buckettrust proxy 1visitorsnginxclient's IP

1 means trust one hop: Express takes the client address from the entry the nginx in front appended. true trusts the whole header, including whatever the client put in it before nginx, and express-rate-limit warns about that one too, as ERR_ERL_PERMISSIVE_TRUST_PROXY.


see also: Nujoom