This package is a middleware for Express.js that limits API requests per IP and blocks abusive clients. It also supports IP whitelisting for certain addresses that won't be rate-limited.
npm install express-rate-limiter-ip
const express = require('express');
const rateLimiter = require('express-rate-limiter-ip');
const app = express();
app.use(rateLimiter({
windowMs: 60000, // 1 minute window
maxRequests: 10, // Limit each IP to 10 requests per window
blockDuration: 300000, // Block for 5 minutes
message: 'Too many requests from this IP, please try again later.', // Custom message for rate limit exceeded
whitelist: ['123.456.789.000'], // Example IPs that won't be rate-limited
}));
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
const api1Limiter = rateLimiter({
windowMs: 1 * 60 * 1000, // 1-minute window
max: 10, // Limit each IP to 10 requests per minute
message: 'Too many requests from this IP for API 1, please try again later.',
whitelist: ['123.456.789.000'], // Example IP that won't be rate-limited for this API
});
const api2Limiter = rateLimiter({
windowMs: 1 * 60 * 1000, // 1-minute window
max: 5, // Limit each IP to 5 requests per minute
message: 'Too many requests from this IP for API 2, please try again later.',
whitelist: ['987.654.321.000'], // Example IP that won't be rate-limited for this API
});
app.use('/api/route1', api1Limiter);
app.use('/api/route2', api2Limiter);
-
Custom Message: Added a
message
option in the middleware configuration to provide feedback when the rate limit is exceeded. -
IP Whitelisting: Included a
whitelist
option that allows you to specify IP addresses that won't be subject to rate limiting.
Feel free to modify the example IP addresses in the whitelist
arrays to match your needs!