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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A factory function lets middleware capture private state in a closure while exposing tunable options via defaults.
- 2Sliding windows and temporary blocks can be modeled with just per-key timestamps and a counter in a Map.
- 3Periodic cleanup with an unref'd timer keeps memory bounded without keeping the process alive.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-rate-limiting-middleware-in-express-explained-javascript-2fe7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.