0
0
ExpressHow-ToBeginner · 3 min read

How to Use express-rate-limit for Request Rate Limiting in Express

Use express-rate-limit by importing it and creating a rate limiter with options like windowMs and max. Then apply it as middleware to your Express routes to limit repeated requests from the same IP.
📐

Syntax

The express-rate-limit middleware is created by calling rateLimit() with an options object. Key options include:

  • windowMs: Time frame in milliseconds for which requests are checked.
  • max: Maximum number of requests allowed within the windowMs.
  • message: Response sent when the limit is exceeded.
  • standardHeaders: Whether to send rate limit info in RateLimit-* headers.
  • legacyHeaders: Whether to send deprecated X-RateLimit-* headers.

After creating the limiter, use it as middleware in your Express app or specific routes.

javascript
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests, please try again later.',
  standardHeaders: true, // Return rate limit info in the RateLimit-* headers
  legacyHeaders: false, // Disable the X-RateLimit-* headers
});

app.use(limiter);
💻

Example

This example shows a simple Express server using express-rate-limit to limit each IP to 5 requests per minute. When the limit is exceeded, the server responds with a 429 status and a message.

javascript
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();

const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 5, // limit each IP to 5 requests per windowMs
  message: 'Too many requests from this IP, please try again after a minute.',
  standardHeaders: true,
  legacyHeaders: false,
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // After 5 requests within 1 minute from the same IP, further requests get: // Status: 429 Too Many Requests // Body: "Too many requests from this IP, please try again after a minute."
⚠️

Common Pitfalls

  • Not applying the limiter middleware: Forgetting to use app.use(limiter) or applying it after routes means no rate limiting happens.
  • Too high or too low limits: Setting max too low can block normal users; too high may not protect well.
  • Using global limiter for all routes: Sometimes you want different limits per route; use limiter as route middleware instead of globally.
  • Not handling proxies: If your app is behind a proxy, set app.set('trust proxy', 1) so IPs are detected correctly.
javascript
/* Wrong: Limiter applied after routes - no effect */
app.get('/', (req, res) => {
  res.send('Hello');
});
app.use(limiter); // Too late

/* Right: Limiter applied before routes */
app.use(limiter);
app.get('/', (req, res) => {
  res.send('Hello');
});
📊

Quick Reference

Remember these key points when using express-rate-limit:

  • Set windowMs to define the time window for counting requests.
  • Set max to limit requests per IP in that window.
  • Use message to customize the response when limit is exceeded.
  • Apply the limiter middleware before your routes.
  • Set app.set('trust proxy', 1) if behind proxies to get correct IPs.

Key Takeaways

Create a rate limiter with rateLimit() and configure windowMs and max options.
Apply the limiter middleware before your routes using app.use(limiter).
Customize the limit exceeded message with the message option.
Set app.set('trust proxy', 1) if your app runs behind a proxy to detect client IPs correctly.
Use different limiters for different routes if needed instead of a global limiter.