Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
express-rate-limit is a battle-tested middleware for Express.js applications that implements IP-based rate limiting to protect servers from abuse, brute-force attacks, and excessive API usage. With over 18 million weekly downloads, it's become the de facto standard for request throttling in the Express ecosystem. The package works by tracking the number of requests from each IP address within a configurable time window and blocking requests that exceed defined thresholds with a 429 status code.
The middleware addresses a critical security and infrastructure concern: preventing malicious actors from overwhelming your server with repeated requests, whether through credential stuffing attacks on login endpoints, scraping attempts, or simple denial-of-service scenarios. Without rate limiting, a single client can consume disproportionate server resources, degrading service for legitimate users or racking up costs in serverless environments.
Developers at companies of all sizes rely on express-rate-limit because it's lightweight, requires minimal configuration to get started, yet offers extensive customization for complex scenarios. It integrates seamlessly with existing Express applications and can be applied globally across all routes or granularly to specific endpoints that need protection. The package supports both in-memory storage for single-server deployments and external stores like Redis for distributed systems, making it suitable for everything from small APIs to large-scale production applications.
Version 8.x introduced breaking changes including TypeScript rewrites and improved async handling, so teams upgrading from older versions should review migration guides. The package is actively maintained with regular security updates and feature additions based on community feedback.
import express from 'express';
import rateLimit from 'express-rate-limit';
const app = express();
// General API rate limiter: 100 requests per 15 minutes
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: true,
legacyHeaders: false,
message: 'Too many requests from this IP, please try again later.',
// Skip rate limiting for successful requests to static assets
skip: (req) => req.path.startsWith('/public'),
});
// Strict limiter for authentication endpoints: 5 attempts per hour
const authLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
limit: 5,
skipSuccessfulRequests: true, // Only count failed login attempts
handler: (req, res) => {
res.status(429).json({
error: 'Too many login attempts. Please try again in an hour.',
retryAfter: req.rateLimit.resetTime,
});
},
});
// Apply general limiter to all API routes
app.use('/api/', apiLimiter);
// Apply strict limiter only to auth routes
app.post('/api/auth/login', authLimiter, (req, res) => {
// Authentication logic here
res.json({ success: true });
});
app.post('/api/auth/reset-password', authLimiter, (req, res) => {
// Password reset logic here
res.json({ success: true });
});
// Custom rate limiter based on API key instead of IP
const apiKeyLimiter = rateLimit({
windowMs: 60 * 1000,
limit: 10,
keyGenerator: (req) => {
return req.headers['x-api-key'] || req.ip;
},
});
app.get('/api/premium/data', apiKeyLimiter, (req, res) => {
res.json({ data: 'premium content' });
});
app.listen(3000);API endpoint protection: Apply rate limiting to public REST APIs to prevent individual users from consuming excessive resources. For example, limit API consumers to 100 requests per 15 minutes to ensure fair usage across all clients and prevent a single user from degrading service quality.
Authentication brute-force prevention: Protect login, password reset, and registration endpoints from credential stuffing and brute-force attacks. By limiting these sensitive endpoints to 5-10 attempts per hour per IP, you make automated attack tools impractical while rarely affecting legitimate users.
Webhook and callback endpoints: Rate limit incoming webhook requests from third-party services to prevent misconfigured or malicious integrations from overwhelming your server. This is particularly important when you don't control the calling service's retry logic.
Scraping and bot mitigation: Slow down automated scrapers and bots by implementing aggressive rate limits on content-heavy routes. Combined with other anti-bot measures, this makes large-scale data extraction economically unfeasible.
Cost control in serverless environments: In AWS Lambda or similar pay-per-invocation platforms, rate limiting prevents runaway costs from traffic spikes or attacks by capping the maximum number of function invocations from individual sources within a time window.
npm install express-rate-limitpnpm add express-rate-limitbun add express-rate-limit