JAVASCRIPT
Implement API Rate Limiting to Prevent Abuse in Express.js
Protect your Express.js API endpoints from brute-force attacks and excessive requests by implementing robust rate limiting using the `express-rate-limit` middleware.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Basic rate limiter configuration
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
});
// Apply the rate limiting middleware to specific routes or globally
// Example 1: Apply to all requests
// app.use(apiLimiter);
// Example 2: Apply to specific API endpoint
app.get('/api/data', apiLimiter, (req, res) => {
res.json({ message: 'This is some data from a rate-limited endpoint.' });
});
// Example 3: Different rate limit for a login endpoint
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Allow 5 login attempts per 5 minutes per IP
message: 'Too many login attempts from this IP, please try again after 5 minutes',
});
app.post('/api/login', loginLimiter, (req, res) => {
// Implement your login logic here
// For demonstration, just respond
res.status(200).json({ message: 'Login attempt received.' });
});
// Unrestricted endpoint
app.get('/', (req, res) => {
res.send('Welcome to the homepage (unlimited access)!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware. Rate limiting protects your application from brute-force attacks, denial-of-service attempts, and general API abuse by restricting the number of requests an IP address can make within a specified time window (`windowMs`). By applying different `max` limits to various endpoints, such as a stricter limit for login attempts, you can tailor your defenses to specific vulnerabilities and resource consumption patterns, returning a `429 Too Many Requests` status when limits are exceeded.