JAVASCRIPT
Implement API Rate Limiting to Prevent Abuse
Protect your API endpoints from brute-force attacks and denial-of-service attempts by implementing robust rate limiting using the 'express-rate-limit' middleware in Express.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Create a rate limiter for general API requests
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per 15 minutes
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
});
// Create a stricter rate limiter for login attempts
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login attempts per 5 minutes
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the general API rate limiter to all routes starting with /api/
app.use('/api/', apiLimiter);
// Apply the stricter login rate limiter to the login endpoint
app.post('/api/login', loginLimiter, (req, res) => {
// Logic for login authentication
res.send('Login attempt processed.');
});
// A regular API endpoint
app.get('/api/data', (req, res) => {
res.send('Some valuable data.');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How it works: This snippet demonstrates how to implement API rate limiting in an Express.js application using the `express-rate-limit` middleware. Rate limiting is a crucial security measure that protects your backend from various forms of abuse, including brute-force attacks on login endpoints and denial-of-service (DoS) attacks. By setting a `windowMs` (time window) and `max` (maximum requests allowed per window), you can control how often a single IP address can interact with your API. Different limits can be applied to different routes, allowing for more granular protection, such as stricter limits on sensitive operations like logins.