How to implement rate limiting on a Node.js API?
poze 2 months ago536 gadeen
Someone is hammering my login endpoint. How do I add rate limiting that also works when I run several instances of the API?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.