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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 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.