Express Rate Limiting Middleware

8.3.2 · active · verified Wed Apr 22

express-rate-limit is a middleware for Express.js that provides basic IP-based rate limiting to protect endpoints from abuse, such as brute-force attacks on login or password reset forms, or excessive API requests. The current stable version is 8.3.2, and the package maintains an active release cadence, with multiple minor and patch updates within recent months, indicating ongoing development and support. Key differentiators include its flexible configuration for `windowMs` and `limit`, support for various external data stores (beyond its built-in memory store), and compliance with the IETF RateLimit header specification (draft-6, draft-7, and draft-8), allowing for modern and standardized rate limiting headers. It also includes `ipv6Subnet` configuration for granular IPv6 handling and integrates well with related packages like `express-slow-down`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic rate limit for all requests under '/api/' using the `rateLimit` middleware, configuring its window, limit, and modern headers.

import express from 'express';
import { rateLimit } from 'express-rate-limit';

const app = express();

// Configure the rate limiter: 100 requests per IP every 15 minutes.
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  limit: 100, // Max 100 requests per IP per window
  standardHeaders: 'draft-8', // Uses the latest IETF RateLimit header draft
  legacyHeaders: false, // Disables the older X-RateLimit-* headers
  message: 'Too many requests from this IP, please try again after 15 minutes.',
  // store: new RedisStore({ /* ... config ... */ }), // Example of an external store
});

// Apply the rate limiting middleware to all API requests
app.use('/api/', apiLimiter);

// A public route that is not rate-limited
app.get('/', (req, res) => {
  res.send('Welcome! This route is not rate-limited.');
});

// A rate-limited API endpoint
app.get('/api/data', (req, res) => {
  res.json({ message: 'This is some data.' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

view raw JSON →