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

  1. Install the middleware: npm install express-rate-limit.
  2. Create a limiter: const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });.
  3. Apply globally: app.use(limiter);.
  4. Apply to specific routes for stricter limits on authentication endpoints.
  5. 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 Requests with a Retry-After header.

Common issues

  • Per-IP limiting is ineffective if all traffic comes through a proxy; use trust proxy and key generators.
  • Aggressive limits can block legitimate users during traffic spikes.