Building a REST API with Rate Limiting
Add rate limiting to a Node.js REST API with Express: per-route limits, Redis stores, proxy headers, 429 responses, and real commands you can run.
By Velloreth
Rate limiting is not a feature you add when traffic gets high. It is a guardrail you add before anyone can abuse an endpoint. A login endpoint without a limit is a brute-force waiting to happen. A public export endpoint without a limit is a scraper magnet. A signup endpoint without a limit is free inventory for someone creating ten thousand throwaway accounts.
This tutorial builds a small Express API and adds rate limiting at three levels: a global safety net, stricter limits on auth routes, and per-user limits for authenticated clients. Every command runs, and every configuration choice comes with a trade-off.
What you need
| Requirement | Version | Check with |
|---|---|---|
| Node.js | 22.12.0 or newer | node -v |
| npm | 10 or newer | npm -v |
| Redis (optional, for multi-instance) | 7 or newer | redis-cli ping |
Create the project:
mkdir rate-limit-demo && cd rate-limit-demo
npm init -y
npm install express express-rate-limit
npm install --save-dev @types/express @types/node typescript tsx
tsx lets you run TypeScript without a separate compile step, which keeps the examples quick to iterate on. The full source is plain JavaScript-compatible; TypeScript is only for type safety.
Step 1: A bare API
Create src/server.ts:
import express from 'express';
const app = express();
app.use(express.json());
const users = new Map<string, { id: string; passwordHash: string }>();
const posts = new Map<string, { id: string; title: string; authorId: string }>();
app.post('/auth/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'username and password required' });
}
if (users.has(username)) {
return res.status(409).json({ error: 'user already exists' });
}
users.set(username, { id: username, passwordHash: password });
res.status(201).json({ id: username });
});
app.post('/auth/login', (req, res) => {
const { username, password } = req.body;
const user = users.get(username);
if (!user || user.passwordHash !== password) {
return res.status(401).json({ error: 'invalid credentials' });
}
res.json({ token: 'dummy-token', userId: user.id });
});
app.get('/posts', (_req, res) => {
res.json([...posts.values()]);
});
app.post('/posts', (req, res) => {
const { title } = req.body;
const id = `post-${Date.now()}`;
posts.set(id, { id, title, authorId: 'me' });
res.status(201).json({ id });
});
app.listen(3000, () => {
console.log('http://localhost:3000');
});
Run it:
npx tsx src/server.ts
http://localhost:3000
In another terminal:
curl -s -X POST http://localhost:3000/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"alice","password":"secret"}'
{"id":"alice"}
It works, and right now there is nothing stopping someone from hitting /auth/register ten thousand times a minute. That is what we fix next.
Step 2: Add a global rate limit
express-rate-limit is the standard middleware for this. Its defaults are a 15-minute window and 100 requests per IP, backed by an in-memory store.
Update src/server.ts:
import express from 'express';
import { rateLimit } from 'express-rate-limit';
const app = express();
app.use(express.json());
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: 'draft-8',
legacyHeaders: false,
});
app.use(globalLimiter);
standardHeaders: 'draft-8' sends the combined RateLimit header (limit, remaining, reset) plus Retry-After when limited. legacyHeaders: false turns off the older X-RateLimit-* headers. Pick one header convention, not both.
Restart the server and inspect the headers:
curl -s -D - -o /dev/null http://localhost:3000/posts | grep -i ratelimit
ratelimit: limit=100, remaining=99, reset=173...
The global limit applies to every route. It is your blast-radius control: if any single endpoint becomes a target, the whole API does not fall over.
Step 3: Stricter limits on auth routes
Login and register deserve a much tighter window than browsing posts. Create a separate limiter and apply it only to those routes:
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
standardHeaders: 'draft-8',
legacyHeaders: false,
message: { error: 'too many attempts, try again later' },
});
app.post('/auth/register', authLimiter, (req, res) => { ... });
app.post('/auth/login', authLimiter, (req, res) => { ... });
Ten attempts per fifteen minutes per IP is strict but reasonable. An attacker guessing passwords from one address burns through it quickly. A legitimate user mistyping a password twice will not notice.
Now trigger the limit:
for i in $(seq 1 12); do
curl -s -o /dev/null -w "%{http_code} " -X POST http://localhost:3000/auth/login \
-H 'Content-Type: application/json' -d '{"username":"alice","password":"wrong"}'
done; echo
Expected output after the first ten:
200 200 200 200 200 200 200 200 200 200 429 429
The 429 response body:
{ "error": "too many attempts, try again later" }
And its headers include Retry-After, telling the client how many seconds to wait before the window resets.
Step 4: Identify the client correctly
By default, express-rate-limit keys limits on the IP address of the TCP connection. That breaks down the moment you sit behind a proxy, load balancer, or Cloudflare: every request appears to come from the proxy’s IP, so one abusive customer burns the quota for everyone behind it.
Fix it in two places. First, tell Express to trust the proxy:
app.set('trust proxy', true);
trust proxy makes Express read X-Forwarded-For and use the client’s real IP as req.ip. Without it, keyGenerator sees the proxy address for every request.
Second, customize the key generator. The default uses IP. For authenticated routes, key on the user instead:
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
keyGenerator: (req) => {
const authHeader = req.headers.authorization || '';
const token = authHeader.replace('Bearer ', '');
return token || req.ip;
},
...
});
Now a logged-in user is tracked by their token, not by the coffee-shop Wi-Fi address they share with twenty strangers. Anonymous requests still fall back to IP.
Be careful what you put in the key. A key based on a header the client controls (X-Api-Key supplied by the requester) lets a malicious client pick a different key per request and evade the limit entirely. Only key on values you validate or set yourself.
Step 5: Share state across instances
The default in-memory store lives inside a single Node process. If you run two API instances behind a load balancer, each instance counts separately, so a client effectively gets double the quota. Worse, restarting the server wipes every counter.
For anything beyond one instance, use an external store. express-rate-limit supports Redis stores. Install one:
npm install rate-limiter-flexible
Or use the official Redis store maintained by the project. Configure it:
import { RedisStore } from 'rate-limit-redis';
import { createClient } from 'redis';
const redisClient = createClient({ url: 'redis://localhost:6379' });
await redisClient.connect();
const globalLimiter = rateLimit({
store: new RedisStore({
sendCommand: (...args: string[]) => redisClient.sendCommand(args),
}),
windowMs: 15 * 60 * 1000,
limit: 100,
...
});
The exact import path depends on the store package version; check the store’s documentation. The important part is the shape: one Redis instance that every API process reads and writes, so the quota is global.
Two rules for Redis stores:
- Fail open or fail closed deliberately.
passOnStoreError: truelets traffic through if Redis is down;false(default) blocks it. For a public API, fail open is usually less damaging than a total outage. For an auth endpoint, fail closed may be safer. - Redis is not a substitute for application logic. Rate limiting slows an attacker down. It does not validate passwords, check permissions, or sanitize input.
Step 6: What the client needs to see
When a client is limited, respond with:
- HTTP
429 Too Many Requests Retry-After: <seconds>— when to try againRateLimit-Limit,RateLimit-Remaining,RateLimit-Reset— the quota state
express-rate-limit emits these automatically with standardHeaders: 'draft-8'. A client that respects them backs off instead of hammering harder, which is often what makes a DDoS attempt collapse on its own.
Customize the handler if you want a shaped response:
const authLimiter = rateLimit({
...
handler: (_req, res) => {
res.status(429).json({
error: 'rate limit exceeded',
retryAfter: res.getHeader('Retry-After'),
});
},
});
Do not return 200 with an error field. Clients, load balancers, and SDKs all look at the status code first. A 429 they can act on; a 200 they cannot.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Limit on IP only, behind a proxy | Every customer shares the proxy IP | app.set('trust proxy', true) + key generator |
| One limit for every route | Login and search do not need the same ceiling | Per-route limiters |
| In-memory store on multiple instances | Each instance counts separately | Redis-backed store |
| Blocking traffic when Redis is down | Redis outage becomes API outage | Set passOnStoreError deliberately |
| Returning 200 on limit | Clients never back off | Always 429 |
| Client-controlled key | Attacker picks a fresh key per request | Key on validated identity or IP |
What rate limiting cannot do
Rate limiting is a traffic cop, not a bouncer. It does not authenticate users, it does not validate input, and it does not stop an attacker who already has valid credentials from abusing their own account. Pair it with authentication, input validation, timeouts on expensive operations, and maximum payload sizes.
It also does not replace a CDN or WAF. Volumetric attacks hit your network before they hit your Express process. Rate limiting in Node handles application abuse; the edge handles the rest.
The setup above — a global limiter, stricter auth limits, a real client key, and a shared store when you scale past one instance — covers the small API and the growing one equally. Start with the memory store, add Redis when you add a second server, and always return 429 so clients know where they stand.
This is the stack I reach for on a new Express API. The first limiter goes in before the first real route, because adding it later means rewriting client code that already assumes unlimited access.