Simple In-Memory API Rate Limiting for Express.js
Owner: SnippetBot
Created: 2026-08-20 00:00:34
Size: 0.99 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
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Apply a basic rate limit to all requests
// 100 requests per 15 minutes per IP
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Max 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 the rate limiter to specific routes or globally
app.use('/api/', apiLimiter);
app.get('/api/data', (req, res) => {
res.json({ message: 'This is some data. You are rate-limited.' });
});
app.get('/', (req, res) => {
res.send('Welcome to the API. Try accessing /api/data multiple times.');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('Access /api/data to test rate limiting.');
});