🔒 Rate Limiting in Express.js
Rate limiting is a critical part of modern web applications that helps prevent abuse by restricting the number of requests a user or IP can make within a certain timeframe. It's especially useful to defend against brute-force attacks, spamming, or denial-of-service (DoS) attempts.
🚀 What is Rate Limiting?
Rate limiting is a strategy used to control the amount of incoming traffic to a server. For example, you might allow 100 requests per 15 minutes for each IP address. If the limit is exceeded, the server returns a 429 (Too Many Requests) response.
🛠️ Installing express-rate-limit
Express provides a middleware called express-rate-limit
which makes implementation simple. First, install it using npm or your preferred package manager:
npm install express-rate-limit
⚙️ Basic Usage
Here's a simple implementation:
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Define the rate limit rule
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});
// Apply the limiter to all requests
app.use(limiter);
// A simple route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
🎯 Applying Rate Limiting to Specific Routes
You can also apply rate limiting only to specific routes instead of the entire app:
// Only apply rate limit to /api routes
app.use('/api', limiter);
📌 Customizing Response
You can fully customize the response returned when the limit is hit:
const customLimiter = rateLimit({
windowMs: 10 * 60 * 1000,
max: 20,
handler: (req, res) => {
res.status(429).json({
status: 'error',
message: 'You have exceeded the 20 requests in 10 mins limit!',
});
},
});
✅ Best Practices
- Use different limits for public APIs and user-authenticated routes.
- Combine with authentication and IP logging for enhanced protection.
- Use a distributed store like Redis if you're running multiple server instances.
📦 Bonus: Using Redis Store
To make rate limiting work across multiple servers, you can use a Redis store:
npm install rate-limit-redis
const RedisStore = require('rate-limit-redis');
const Redis = require('ioredis');
const limiterWithRedis = rateLimit({
store: new RedisStore({
sendCommand: (...args) => redisClient.call(...args),
}),
windowMs: 15 * 60 * 1000,
max: 100,
});
📘 Conclusion
Rate limiting is an essential tool to secure your Express.js apps. With the express-rate-limit
package, implementation is quick and customizable. Always consider adding it to your production apps to ensure safety and performance.