How to implement rate limiting on a Node.js API?
asked 2 months ago537 viewsen
Someone is hammering my login endpoint. How do I add rate limiting that also works when I run several instances of the API?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
In-memory limiters (the default express-rate-limit store) only count requests per process. With several instances you need a shared store, typically Redis:
import { rateLimit } from 'express-rate-limit';
import { RedisStore } from 'rate-limit-redis';
app.use('/auth/login', rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
standardHeaders: 'draft-7',
store: new RedisStore({ sendCommand: (...args) => redis.sendCommand(args) }),
}));
For login specifically, limit by both IP and target account (email). That slows credential stuffing from many IPs against one account.
Behind a proxy or load balancer, set app.set('trust proxy', 1) so the client IP is read correctly. Only trust X-Forwarded-For from your own proxy, or attackers can spoof it.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.