Title: Express.
js Rate Limiter Guide
1. Introduction express-rate-limit is a middleware for [Link] that helps limit the number of
requests an IP can make to your server within a given time frame. It is used to prevent brute-force attacks,
API abuse, DDoS attacks, and ensures fair usage of server resources.
2. Installation
npm install express-rate-limit
3. Basic Usage
import rateLimit from "express-rate-limit";
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute window
max: 5, // limit each IP to 5 requests per window
message: "Too many requests, please try again later."
});
[Link]('/api/', limiter);
4. Custom Rate Limiter Example
import rateLimit from "express-rate-limit";
import { createResponse } from "../helpers/response";
export const throttleMiddleware = rateLimit({
windowMs: 1 * 30 * 1000, // 30 seconds window
max: 20000, // Limit each IP to 20000 requests per window
standardHeaders: false, // Disable RateLimit-* headers
legacyHeaders: false, // Disable X-RateLimit-* headers
handler: (req: any, res: any) => {
const resetTime = req?.rateLimit?.resetTime;
const remainingTime = resetTime
? Math?.ceil((resetTime?.getTime() - Date?.now()) / 1000)
: "Unknown";
1
const msg = `Too many requests. Please try again after ${remainingTime}
seconds.`;
return createResponse(res, 429, msg, [], false, true);
},
});
Explanation: - windowMs : Time frame in milliseconds for which requests are counted. Here, 30 seconds. -
max : Maximum number of requests allowed from a single IP in the window. Here, 20000. -
standardHeaders and legacyHeaders : Disable automatic rate-limit headers in response. - handler :
Custom function triggered when the rate limit is exceeded, sends a structured response using
createResponse .
5. Use Cases 1. Brute Force Protection: Limit login attempts per IP. 2. API Abuse Prevention: Control how
many API calls a user/IP can make. 3. DDoS Mitigation: Prevent server overload by limiting high-frequency
requests. 4. Fair Resource Usage: Ensures all users have fair access to server resources.
6. Example Implementation in Express
import express from 'express';
import { throttleMiddleware } from './middlewares/throttleMiddleware';
const app = express();
// Apply rate limiter to all /api routes
[Link]('/api/', throttleMiddleware);
[Link]('/api/data', (req, res) => {
[Link]({ message: 'Data fetched successfully.' });
});
[Link](3000, () => {
[Link]('Server running on port 3000');
});
References: - express-rate-limit Documentation - [Link] Security Best Practices