typescriptExpressexpert
Express Typed Rate Limit Middleware
In-memory token bucket rate limiter middleware in Express/TypeScript
By ApeType Staff·27 lines·712 characters·1,420 total attempts
import { Request, Response, NextFunction } from "express";
interface ClientBucket {
tokens: number;
lastRefill: number;
}
const clients = new Map<string, ClientBucket>();
export function rateLimiter(limit: number, intervalMs: number) {
return (req: Request, res: Response, next: NextFunction): void => {
const ip = req.ip || "unknown";
const now = Date.now();
let bucket = clients.get(ip);
if (!bucket || now - bucket.lastRefill > intervalMs) {
bucket = { tokens: limit, lastRefill: now };
clients.set(ip, bucket);
}
if (bucket.tokens > 0) {
bucket.tokens--;
return next();
}
res.status(429).json({ error: "Too many requests, try again later." });
};
}
TRANSCRIBE
Ready when you are.
Test your muscle memory and transcription speed against this exact snippet.
Start Typing
Tip: Press Esc anytime to restart
Best runs on this snippet
No recorded runs yet. Be the first to type this snippet!