How to implement rate limiting in Node.js
· Category: Node.js
Short answer
Use express-rate-limit middleware to restrict how many requests a client can make within a time window.
Steps
- Install the middleware:
npm install express-rate-limit. - Create a limiter:
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });. - Apply globally:
app.use(limiter);. - Apply to specific routes for stricter limits on authentication endpoints.
- Customize the handler for exceeded limits.
Tips
- Store rate limit counters in Redis when running multiple server instances behind a load balancer.
- Return
429 Too Many Requestswith aRetry-Afterheader.
Common issues
- Per-IP limiting is ineffective if all traffic comes through a proxy; use
trust proxyand key generators. - Aggressive limits can block legitimate users during traffic spikes.