Node.js ยท Chapter 40 of 43

Rate Limiting

Rate limiting restricts how many requests a client can make in a given time window, protecting your API from abuse, brute-force attacks, and accidental overload.

The `express-rate-limit` package makes it easy to add rate limiting middleware to an Express app.

Configuring a limiter

You define a time window and a maximum number of requests; clients exceeding the limit receive a 429 Too Many Requests response.

Applying selectively

Rate limiting can be applied globally or only to sensitive routes like login, where brute-force protection matters most.

Example 1 (javascript)
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use(limiter);
Output
429 Too Many Requests (after exceeding the limit)

This allows a maximum of 100 requests per IP every 15 minutes.

Example 2 (javascript)
app.post('/login', loginLimiter, (req, res) => {
  // login logic
});
Output
429 if too many login attempts

Applying a stricter limiter just to /login helps prevent brute-force password guessing.

Key points

  • Rate limiting caps requests per client within a time window.
  • express-rate-limit is a common middleware for this in Express.
  • Exceeding the limit typically returns HTTP 429.
  • Apply stricter limits to sensitive endpoints like login.
๐Ÿ’ก Note: Rate limiting is one layer of defense โ€” combine it with strong authentication and monitoring.

๐Ÿ“ Quick Quiz

1. What HTTP status code indicates too many requests?

2. What does rate limiting primarily protect against?

3. Which route commonly benefits most from strict rate limiting?