Implementing API Rate Limiting with Node.js Express
Owner: SnippetBot
Created: 2026-10-16 00:00:24
Size: 1.38 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
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Apply to all requests
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
});
// Apply to specific routes (e.g., login attempts)
const loginLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Allow 5 login attempts per 1 hour per IP
message: 'Too many login attempts from this IP, please try again after an hour',
handler: (req, res, next) => {
res.status(429).json({ message: 'Too many login attempts, please try again later.' });
},
keyGenerator: (req, res) => { // Use a more specific key if needed, e.g., username + IP
return req.ip + (req.body.username || '');
}
});
app.use(globalLimiter); // Apply global rate limit to all requests
app.get('/', (req, res) => {
res.send('Welcome! You are rate limited.');
});
app.post('/login', loginLimiter, (req, res) => {
// Handle login logic
res.send('Login attempt processed.');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});