JAVASCRIPT
Implement API Rate Limiting in Node.js Express
Protect your Node.js Express API from brute-force attacks and abuse by implementing effective rate limiting using the `express-rate-limit` middleware.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// 1. Basic Rate Limiter for all routes
const apiLimiter = 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 after 15 minutes',
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
// 2. Stronger Limiter for sensitive routes (e.g., login, password reset)
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login attempts per windowMs
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the basic API limiter to all requests
app.use(apiLimiter);
app.get('/', (req, res) => {
res.send('Welcome to the main API. You have a general rate limit applied.');
});
// Apply the stronger login limiter specifically to the login route
app.post('/login', loginLimiter, (req, res) => {
// In a real application, process login here
res.send('Login attempt received.');
});
app.get('/public', (req, res) => {
res.send('This is a public endpoint, still under general rate limit.');
});
app.listen(3000, () => console.log('Server running on port 3000'));
// To test:
// For `/` or `/public`: Make more than 100 requests in 15 mins.
// For `/login`: Make more than 5 POST requests in 5 mins.
// Example: curl -X POST http://localhost:3000/login
How it works: This Node.js Express snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware. It sets up two different rate limiters: a `apiLimiter` that applies a general limit of 100 requests per 15 minutes to all routes, and a `loginLimiter` which is more restrictive, allowing only 5 requests per 5 minutes, specifically for the sensitive `/login` route. When an IP address exceeds the defined limit within the `windowMs` timeframe, the middleware automatically responds with a 429 Too Many Requests status and a custom message, effectively protecting your server from brute-force attacks, denial-of-service attempts, and general API abuse.