Simple in-memory rate limiting middleware
Quick Answer
This in-memory rate limiter middleware counts requests per IP address within a sliding window and returns `429 Too Many Requests` once the limit is exceeded.
1import { Request, Response, NextFunction } from 'express';
2
3interface RateLimitStore {
4 [key: string]: { count: number; resetTime: number };
5}
6
7const store: RateLimitStore = {};
8
9const rateLimit = (maxRequests: number, windowMs: number) => {
10 return (req: Request, res: Response, next: NextFunction) => {
11 const key = req.ip;
12 const now = Date.now();
13
14 if (!store[key] || now > store[key].resetTime) {
15 store[key] = { count: 1, resetTime: now + windowMs };
16 return next();
17 }
18
19 if (store[key].count < maxRequests) {
20 store[key].count++;
21 return next();
22 }
23
24 res.status(429).json({ error: 'Too many requests' });
25 };
26};
27
28export default rateLimit;Rate limiting prevents abuse, brute-force attacks, and accidental DDoS by capping how many requests a client can make in a time window. This in-memory implementation is suitable for single-process servers. For multi-process or distributed environments, use Redis-backed rate limiting with the same middleware interface.
Replace the in-memory `store` object with Redis INCR and EXPIRE commands. The `express-rate-limit` package with a Redis store adapter is the standard production approach.
This free typescript code snippet for rate limiter is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement rate limiter quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.