Rate Limiting
Limit how many requests a client can make to protect against abuse.
Syntax
app.use(rateLimit(options))Rate limiting caps how many requests a single client can make in a time window. It defends against brute-force attacks and accidental floods. The express-rate-limit package makes this a one-liner.
Apply it globally, or only to sensitive routes like login.
Example
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests
});
app.use('/api', limiter);When to use it
- A login endpoint is protected with a rate limiter that allows a maximum of 5 attempts per IP per 15 minutes to block brute-force attacks.
- A public API tier limits unauthenticated callers to 100 requests per hour while authenticated pro-plan users get 10,000.
- A developer uses express-rate-limit on all /api routes to prevent a single client from overwhelming the server with requests.
More examples
Global API rate limit
Limits each IP to 100 requests per 15-minute window on all /api routes and includes RateLimit-* standard headers.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api', limiter);Strict limiter for login
Applies a tighter 5-request limit specifically to the login route to stop brute-force password guessing.
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: { error: 'Too many login attempts, try again in 15 minutes' },
});
app.post('/login', loginLimiter, (req, res) => {
// credential check here
res.json({ ok: true });
});Dynamic limit by user tier
Creates a rate limiter on-the-fly based on the authenticated user's plan tier, applying different limits per user type.
const rateLimit = require('express-rate-limit');
app.use('/api', (req, res, next) => {
const max = req.user?.tier === 'pro' ? 10000 : 100;
rateLimit({ windowMs: 60 * 60 * 1000, max })(req, res, next);
});
Discussion