How to Implement Rate Limiting in a Node.js API with express-rate-limit

Rate limiting a Node.js API is one of those tasks that looks like a five-line job in a tutorial and turns into an incident at 3 a.m. in production. The middleware itself is easy. What breaks is everything around it: a load balancer that hides the real client IP, counters stored in memory while you run four containers, a 429 response with no Retry-After header, or a limit so aggressive that a legitimate mobile app gets locked out. This guide is the production version of the walkthrough. We go from a working baseline to per-route policies, shared Redis counters, correct proxy configuration, standards-compliant headers, and a rollout plan that does not block real users. Why rate limiting matters before you ship Rate limiting bounds how many requests a given subject (an IP address, an API key, a user ID) can make inside a time window. Without it, a single misbehaving client can: Brute-force login, password reset or OTP endpoints Exhaust your database connection pool and take down healthy traffic Scrape your entire catalogue in minutes Run up your bill on paid downstream APIs (email, SMS, LLM providers) Trigger an accidental self-DDoS from a buggy client retry loop Important framing: express-rate-limit is application-level protection. It is excellent against abuse, credential stuffing and runaway clients. It is not a replacement for a CDN or WAF against volumetric DDoS, because the request still reaches your Node.js process. Step 1: The baseline setup Install the middleware: npm install express-rate-limit Then wire a global limiter. This example uses ESM and the modern option names (limit instead of the deprecated max): import express from ‘express’; import { rateLimit } from ‘express-rate-limit’; const app = express(); const globalLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes limit: 1000, // requests per window per key standardHeaders: ‘draft-8’, legacyHeaders: false, message: { error: ‘too_many_requests’ }, }); app.use(globalLimiter); app.get(‘/api/health’, (req, res) => res.json({ ok: true })); app.listen(3000); That is the whole “hello world”. Everything below is what separates it from a configuration you can actually deploy. The options that actually matter Option What it does Production advice windowMs Length of the counting window in milliseconds Short windows (1 min) react faster and punish less. Long windows (15 min) are better for auth endpoints. limit Max requests per window per key Can be a function, so you can give paying tiers a higher ceiling. keyGenerator Decides what is being limited Default is the client IP. Prefer API key or user ID when authenticated. store Where counters live Memory by default. Must be Redis (or similar) as soon as you run more than one instance. standardHeaders Emits IETF RateLimit-* headers Use ‘draft-8’ on recent versions, or ‘draft-7’ if you are still on v7. legacyHeaders Old X-RateLimit-* headers Set to false unless existing clients depend on them. skip / skipFailedRequests / skipSuccessfulRequests Exclude requests from counting Great for health checks, internal networks and login endpoints. handler Custom response when the limit is hit Use it to return a consistent JSON error shape and to log the event. Step 2: Fix the proxy problem first This is the single most common cause of broken IP-based rate limiting in Node.js. If your app sits behind Nginx, a cloud load balancer, Cloudflare, Heroku, Render or a Kubernetes ingress, then req.ip returns the proxy address unless you tell Express otherwise. The result: every user in the world shares one counter and everyone gets a 429 at the same time. This article covers the same ground in more depth. // Number of proxies between the client and your app. // 1 = a single load balancer. 2 = CDN + load balancer. app.set(‘trust proxy’, 1); Never use app.set(‘trust proxy’, true) on a public API. It tells Express to trust the leftmost value of X-Forwarded-For, which any client can forge. An attacker simply rotates a fake header value and bypasses your limiter entirely. express-rate-limit even ships validation checks that will warn you in the logs about this exact misconfiguration. Safer patterns: Set the exact hop count: app.set(‘trust proxy’, 1) Trust only known proxy ranges: app.set(‘trust proxy’, [‘loopback’, ‘10.0.0.0/8’]) Behind Cloudflare, read the vetted header instead: use req.headers[‘cf-connecting-ip’] in your keyGenerator Verify it in 10 seconds app.get(‘/api/debug/ip’, (req, res) => { res.json({ ip: req.ip, xff: req.headers[‘x-forwarded-for’] }); }); Call it from an external network. If ip is your real public address and not 127.0.0.1 or an internal 10.x address, your trust proxy setting is correct. Remove the route afterwards. Much the same conclusion turns up on akashrajpurohit.com. Step 3: Per-route limits instead of one global number A single global limiter is a blunt instrument. A product search endpoint and a password reset endpoint have nothing in common. Build a small factory and apply tailored policies. // limiters.js import { rateLimit } from ‘express-rate-limit’; const base = { standardHeaders: ‘draft-8’, legacyHeaders: false, }; export const readLimiter = rateLimit({ …base, windowMs: 60 * 1000, limit: 300, }); export const writeLimiter = rateLimit({ …base, windowMs: 60 * 1000, limit: 60, }); export const authLimiter = rateLimit({ …base, windowMs: 15 * 60 * 1000, limit: 8, skipSuccessfulRequests: true, // only failed logins count }); export const expensiveLimiter = rateLimit({ …base, windowMs: 60 * 60 * 1000, limit: 20, // PDF export, report generation, AI calls }); Then mount them where they belong: app.use(‘/api/’, readLimiter); app.post(‘/api/orders’, writeLimiter, createOrder); app.post(‘/api/auth/login’, authLimiter, login); app.post(‘/api/auth/forgot-password’, authLimiter, forgotPassword); app.post(‘/api/reports/export’, expensiveLimiter, exportReport); Order matters. Express runs middleware in registration order, so a route-specific limiter placed after a global one simply adds a second, stricter layer. That layering is intentional and useful: a wide safety net plus a tight guard on sensitive endpoints. Suggested starting values Endpoint type Window Limit Key Public read / search 1 min 120 to 300 IP Authenticated read 1 min 600 to 1200 API key / user ID Write operations 1 min 30 to 60 User ID Login / password reset 15 min 5 to 10 failures IP + account identifier Email / SMS sending 1 hour 5 to 20 User ID

How to Implement Rate Limiting in a Node.js API with express-rate-limit Read More »