Implementing Rate Limiting with Node.js Express (express-rate-limit)
Owner: SnippetBot
Created: 2026-10-03 00:00:34
Size: 2.42 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;
// --- Global Rate Limiter ---
// Apply to all requests to prevent brute-force attacks and resource exhaustion.
// Limit to 100 requests per 15 minutes per IP address.
const globalLimiter = 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
});
// --- Stronger Rate Limiter for Login/Sensitive Routes ---
// Apply specifically to login attempts to deter brute-force password guessing.
// Limit to 5 requests per 5 minutes per IP address.
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',
handler: (req, res, next) => {
// Customize response for login failures
res.status(429).json({ error: 'Too many login attempts. Please try again later.' });
},
keyGenerator: (req) => {
// Optionally, use a combination of IP and username for more specific login rate limiting
// return req.ip + ':' + req.body.username; // Requires body-parser middleware
return req.ip;
},
standardHeaders: true,
legacyHeaders: false,
});
// Apply the global rate limiter to all requests
app.use(globalLimiter);
// Public route (also covered by globalLimiter)
app.get('/', (req, res) => {
res.send('Welcome! This endpoint has a global rate limit.');
});
// Login route with a stricter rate limit
app.post('/login', loginLimiter, (req, res) => {
// In a real application, you would validate credentials here
const { username, password } = req.body;
console.log(`Login attempt for user: ${username}`);
res.send(`Login request received for ${username}. (Credentials not verified)`);
});
// Example of another sensitive route
app.post('/reset-password', loginLimiter, (req, res) => {
// Logic for password reset
res.send('Password reset request received.');
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
console.log('Try sending more than 100 requests to / in 15 mins, or 5 requests to /login in 5 mins.');
});