JAVASCRIPT
Rate Limiting API Endpoints to Prevent Abuse (Express.js)
Implement rate limiting for your Express.js API endpoints using 'express-rate-limit' to prevent brute-force attacks, DoS, and abusive usage.
const express = require('express');
const rateLimit = require('express-rate-limit'); // Middleware for rate limiting
const app = express();
// Apply rate limiting to all requests
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 rate limiting specifically to authentication routes (e.g., login)
const authLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login attempts per windowMs
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
app.use(apiLimiter);
// Apply the stricter auth limiter only to login/signup routes
app.post('/login', authLimiter, (req, res) => {
res.send('Login attempt processed.');
});
app.get('/', (req, res) => {
res.send('Welcome to the protected API!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: Rate limiting is essential for protecting API endpoints from brute-force attacks, denial-of-service (DoS) attempts, and general abuse. This Express.js snippet utilizes the `express-rate-limit` middleware to easily implement rate limiting. It demonstrates two different limiters: a general `apiLimiter` for all routes and a stricter `authLimiter` specifically for sensitive routes like login. By setting `windowMs` (time window) and `max` (maximum requests), you control how many requests an IP address can make within a given period, returning a 429 Too Many Requests status if exceeded.