JAVASCRIPT
Implement Basic Rate Limiting Middleware in Node.js
Protect your Node.js API from abuse, brute-force attacks, and denial-of-service attempts by implementing a simple, effective rate limiting middleware.
// In a real application, use a persistent store like Redis for production.
const requestCounts = {}; // Stores { ipAddress: { timestamp: ..., count: ... } }
const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute
const MAX_REQUESTS_PER_WINDOW = 10;
function rateLimitMiddleware(req, res, next) {
const ip = req.ip || req.connection.remoteAddress;
if (!requestCounts[ip]) {
requestCounts[ip] = {
timestamp: Date.now(),
count: 0
};
}
const now = Date.now();
const clientData = requestCounts[ip];
// Reset count if window has passed
if (now - clientData.timestamp > RATE_LIMIT_WINDOW_MS) {
clientData.timestamp = now;
clientData.count = 0;
}
clientData.count++;
if (clientData.count > MAX_REQUESTS_PER_WINDOW) {
res.status(429).send('Too Many Requests. Please try again later.');
// Optional: Log the rate-limited request for monitoring
console.warn(`Rate limit exceeded for IP: ${ip}`);
return;
}
// Set rate limit headers for client awareness
res.setHeader('X-RateLimit-Limit', MAX_REQUESTS_PER_WINDOW);
res.setHeader('X-RateLimit-Remaining', MAX_REQUESTS_PER_WINDOW - clientData.count);
res.setHeader('X-RateLimit-Reset', Math.ceil((clientData.timestamp + RATE_LIMIT_WINDOW_MS) / 1000));
next();
}
// Example usage with Express (conceptual, not full Express app)
// const express = require('express');
// const app = express();
// app.use(rateLimitMiddleware);
// app.get('/', (req, res) => res.send('Hello World!'));
// app.listen(3000, () => console.log('Server running on port 3000'));
module.exports = rateLimitMiddleware; // Export for use in Express/other frameworks
How it works: This Node.js snippet provides a basic rate limiting middleware to protect your API from excessive requests. It tracks the number of requests from each IP address within a defined time window. If an IP exceeds the `MAX_REQUESTS_PER_WINDOW` within the `RATE_LIMIT_WINDOW_MS`, it receives a `429 Too Many Requests` response. This helps prevent brute-force attacks, denial-of-service attempts, and general API abuse. For production, the `requestCounts` object should be replaced with a persistent store like Redis.