Implement rate limiting middleware to protect APIs from abuse and ensure fair usage
Build a rate limiting middleware that restricts the number of requests a client can make within a specified time window, protecting your API from abuse.
const rateLimit = {};
function createRateLimiter(maxRequests, windowMs) {
return (req, res, next) => {
const ip = req.ip;
const now = Date.now();
if (!rateLimit[ip]) {
rateLimit[ip] = { count: 1, resetTime: now + windowMs };
return next();
}
if (now > rateLimit[ip].resetTime) {
rateLimit[ip] = { count: 1, resetTime: now + windowMs };
return next();
}
if (rateLimit[ip].count >= maxRequests) {
return res.status(429).json({ error: 'Too many requests' });
}
rateLimit[ip].count++;
next();
};
}