javascript 47 lines · 9 steps

Building a rate-limiting middleware in Express

A configurable factory tracks per-IP request counts in memory and returns an Express middleware that throttles and temporarily blocks abusive clients.

Explained by highlit
1const RATE_LIMIT = 100;
2const WINDOW_MS = 60 * 1000;
3const BLOCK_MS = 5 * 60 * 1000;
4 
5function rateLimiter({ limit = RATE_LIMIT, windowMs = WINDOW_MS, blockMs = BLOCK_MS } = {}) {
6 const clients = new Map();
7 
8 setInterval(() => {
9 const now = Date.now();
10 for (const [key, entry] of clients) {
11 if (entry.blockedUntil < now && entry.resetAt < now) {
12 clients.delete(key);
13 }
14 }
15 }, windowMs).unref();
16 
17 return function (req, res, next) {
18 const key = req.ip;
19 const now = Date.now();
20 let entry = clients.get(key);
21 
22 if (!entry || entry.resetAt < now) {
23 entry = { count: 0, resetAt: now + windowMs, blockedUntil: 0 };
24 clients.set(key, entry);
25 }
26 
27 if (entry.blockedUntil > now) {
28 res.set('Retry-After', Math.ceil((entry.blockedUntil - now) / 1000));
29 return res.status(429).json({ error: 'Too many requests. You are temporarily blocked.' });
30 }
31 
32 entry.count += 1;
33 
34 if (entry.count > limit) {
35 entry.blockedUntil = now + blockMs;
36 res.set('Retry-After', Math.ceil(blockMs / 1000));
37 return res.status(429).json({ error: 'Rate limit exceeded.' });
38 }
39 
40 res.set('X-RateLimit-Limit', limit);
41 res.set('X-RateLimit-Remaining', Math.max(0, limit - entry.count));
42 res.set('X-RateLimit-Reset', Math.ceil(entry.resetAt / 1000));
43 next();
44 };
45}
46 
47module.exports = rateLimiter;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A factory function lets middleware capture private state in a closure while exposing tunable options via defaults.
  2. 2Sliding windows and temporary blocks can be modeled with just per-key timestamps and a counter in a Map.
  3. 3Periodic cleanup with an unref'd timer keeps memory bounded without keeping the process alive.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a rate-limiting middleware in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code