How to implement rate limiting on a Node.js API?
posée 3 months ago539 vuesen
Someone is hammering my login endpoint. How do I add rate limiting that also works when I run several instances of the API?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
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.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.