JAVASCRIPT
Implement API Rate Limiting for Node.js Express Endpoints
Protect Node.js API endpoints from brute-force attacks, denial-of-service, and abuse by implementing effective rate limiting using the 'express-rate-limit' middleware with global and specific endpoint configurations.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Global rate limiter for all requests (e.g., 100 requests per 15 minutes)
const globalLimiter = 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
});
// Stricter rate limiter for sensitive endpoints (e.g., login, password reset)
const authLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 requests per windowMs
message: 'Too many authentication attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the global rate limiter to all routes
app.use(globalLimiter);
// Apply the stricter auth limiter to specific authentication routes
app.post('/login', authLimiter, (req, res) => {
// Handle login logic
res.send('Login attempt received.');
});
app.post('/register', authLimiter, (req, res) => {
// Handle registration logic
res.send('Registration attempt received.');
});
app.get('/api/data', (req, res) => {
res.send('Some public data.');
});
app.get('/api/protected', (req, res) => {
res.send('Some protected data.');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware. It shows how to apply a global rate limit to all requests and a more stringent limit to sensitive endpoints like login or registration, helping to protect against brute-force attacks, denial-of-service, and resource exhaustion. The configuration includes `windowMs` (time window), `max` (maximum requests), and custom `message` for exceeded limits, along with standard HTTP headers for conveying rate limit status to clients.