0
0
ExpressHow-ToBeginner · 4 min read

How to Rate Limit API in Express: Simple Guide with Example

To rate limit an API in Express, use the express-rate-limit middleware which controls how many requests a client can make in a set time. Install it, configure limits like max requests and window time, then apply it as middleware to your routes or app.
📐

Syntax

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

  • windowMs: Time frame in milliseconds for the limit (e.g., 15 minutes).
  • max: Maximum number of requests allowed per windowMs.
  • message: Response sent when limit is exceeded.

Apply the limiter as middleware to 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.'
});

app.use(limiter);
💻

Example

This example shows a simple Express server with rate limiting applied globally. Each IP can make up to 5 requests every minute. If 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.'
});

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 - First 5 requests to '/' respond with 'Hello, world!' - 6th and later requests within 1 minute respond with 429 status and message 'Too many requests from this IP, please try again after a minute.'
⚠️

Common Pitfalls

Common mistakes when implementing rate limiting in Express include:

  • Not applying the limiter middleware before routes, so limits don't work.
  • Setting max too high or too low without considering real traffic.
  • Not customizing the message or status code, leading to confusing client responses.
  • Applying rate limiting globally when only some routes need protection, causing unnecessary blocking.

Always test your limits and adjust based on your API usage patterns.

javascript
/* Wrong: Applying limiter after routes */
app.get('/', (req, res) => {
  res.send('Hello');
});
app.use(limiter); // This won't limit '/' route

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

Quick Reference

Tips for effective rate limiting in Express:

  • Use express-rate-limit for easy setup.
  • Set windowMs and max based on your API's expected traffic.
  • Apply limiter only to routes that need protection to avoid blocking harmless requests.
  • Customize the message to inform users clearly when they are blocked.
  • Consider using other stores like Redis for distributed rate limiting in multi-server setups.

Key Takeaways

Use the express-rate-limit middleware to easily add rate limiting to your Express API.
Configure windowMs and max options to control request limits per time frame.
Apply the limiter middleware before your routes to ensure it works correctly.
Customize the response message to inform clients when they exceed limits.
Test and adjust limits based on your API's real usage patterns.