Introduction to Express Rate Limit
Express Rate Limit is a middleware for Node.js that helps you control the rate of requests from users or IPs, protecting your application from abuse and ensuring smooth operation. This post explores the various APIs provided by express-rate-limit
, along with numerous examples to help you implement them in your applications.
Getting Started
First, you’ll need to install the express-rate-limit
package:
npm install express-rate-limit
Basic Rate Limiting
The basic usage of express-rate-limit allows you to limit the number of requests a client can make in a given period:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
Custom Message
You can customize the response sent to clients who exceed the rate limit:
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests from this IP, please try again after 15 minutes'
});
Custom Rate Limiting Function
Define a custom rate limiting function to implement more complex rules:
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: (req, res) => {
return req.user && req.user.premiumAccount ? 1000 : 100;
}
});
Skip Specific Requests
The skip function allows you to skip rate limiting for specific routes or conditions:
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
skip: (req, res) => req.url.includes('/public')
});
Dynamic Requests During Peak Time
Dynamically adjust the rate limit based on server load or time of day:
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: (req, res) => {
const currentHour = new Date().getHours();
return (currentHour >= 8 && currentHour <= 18) ? 200 : 100;
}
});
Applying Rate Limiting to Specific Routes
Apply rate limiting to only specific routes:
app.use('/api/', limiter);
Example Application
Here's a simple example application that demonstrates the usage of express-rate-limit:
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
});
app.use('/api/', limiter);
app.get('/api/', (req, res) => {
res.send('API endpoint with rate limiting.');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
By using express-rate-limit, you can easily control the rate of requests and protect your application from abuse. Experiment with different configurations and find what works best for your specific needs.
Hash: 84c857b54b924d84d55cd2c9e246b089792b5dcc6609d44a4909ab1101f0ed6a