0
0
ExpressHow-ToBeginner · 4 min read

How to Use Rate Limiting in Express for API Protection

To use rate limiting in Express, install the express-rate-limit package and apply it as middleware to your routes. This middleware controls how many requests a client can make within a time window, helping prevent abuse and server overload.
📐

Syntax

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

  • windowMs: Time frame in milliseconds for counting requests.
  • max: Maximum number of requests allowed per windowMs.
  • message: Response sent when limit is exceeded.

Apply the 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 using express-rate-limit to limit clients to 5 requests every 10 seconds. 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: 10 * 1000, // 10 seconds
  max: 5, // limit each IP to 5 requests per windowMs
  message: 'Too many requests, slow down!'
});

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 10 seconds respond with status 429 and message 'Too many requests, slow down!'
⚠️

Common Pitfalls

Common mistakes when using rate limiting in Express include:

  • Not applying the middleware globally or to the correct routes, so limits don't work as expected.
  • Setting max too high or windowMs too long, making limits ineffective.
  • Not handling the 429 response properly on the client side.
  • Using rate limiting without considering trusted proxies, which can cause all requests to appear from the same IP.

Always test your rate limiting setup to ensure it behaves as intended.

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

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

Quick Reference

Key options for express-rate-limit:

OptionDescriptionExample
windowMsTime window in milliseconds15 * 60 * 1000 (15 minutes)
maxMax requests per window100
messageResponse when limit exceeded'Too many requests, please try again later.'
standardHeadersSend rate limit info in headerstrue
legacyHeadersSend deprecated headersfalse

Key Takeaways

Use the express-rate-limit package to add rate limiting middleware in Express.
Configure windowMs and max to control request limits per client IP.
Apply the middleware before your routes to ensure it works correctly.
Customize the message and status code for blocked requests.
Test your setup to avoid blocking legitimate users or ignoring abuse.