JAVASCRIPT
Implement Basic Rate Limiting to Prevent Abuse and Brute-Force in Express
Protect your Node.js API and website from denial-of-service and brute-force attacks by implementing effective server-side rate limiting middleware.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Basic rate limiter: 100 requests per 15 minutes per IP
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 to all requests
app.use(apiLimiter);
// More stringent limiter for login attempts: 5 requests per 5 minutes per IP
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login requests per windowMs
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the login limiter specifically to the login route
app.post('/login', loginLimiter, (req, res) => {
// Process login logic here
res.send('Login attempt processed.');
});
app.get('/public', (req, res) => {
res.send('This is a public endpoint.');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
How it works: This Node.js Express snippet demonstrates how to implement rate limiting using the `express-rate-limit` middleware. Rate limiting is a crucial security measure that prevents abuse, brute-force attacks, and denial-of-service (DoS) attempts by restricting the number of requests an IP address can make within a specified time window. The example shows a global rate limit for all API calls and a more stringent, specific rate limit for a login endpoint to deter credential stuffing attacks.