Implement rate limiting middleware to protect APIs from abuse and ensure fair usage
Build a rate limiting system that restricts the number of requests a client can make within a time window, preventing API abuse and ensuring service stability.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP'
});
app.use('/api/', limiter);
// Custom rate limiter
const strictLimiter = rateLimit({
windowMs: 60 * 1000,
max: 5
});
app.post('/api/login', strictLimiter, loginHandler);