@santosh-ddev/rate-limiter
v1.0.1
Published
A high-performance, Redis-backed rate limiting middleware for Express.js, powered by Lua scripting for atomic operations. Easily plug into your Node.js/TypeScript projects to protect your APIs from abuse.
Downloads
10
Readme
@santosh-ddev/rate-limiter
A high-performance, Redis-backed rate limiting middleware for Express.js, powered by Lua scripting for atomic operations.
Easily plug into your Node.js/TypeScript projects to protect your APIs from abuse.
Features
- Fast & Atomic: Uses Redis and Lua for accurate, race-free request counting.
- Flexible: Customize rate limits, time windows, and key generation (per IP, user, route, etc).
- TypeScript Support: Ships with type declarations.
- Plug & Play: Simple Express middleware interface.
Installation
npm install @santosh-ddev/rate-limiterUsage
1. Set up Redis
Install and run Redis locally or use a managed Redis service.
2. Configure the Middleware
import express from 'express';
import { createClient } from 'redis';
import { rateLimiter, RateLimiterOptions } from '@santosh-ddev/rate-limiter';
const app = express();
const redisClient = createClient({
socket: {
host: 'localhost',
port: 6379,
},
});
await redisClient.connect();
app.use(
rateLimiter({
redisClient,
rateLimit: 10, // Max requests
timeWindow: 60, // Per 60 seconds
keyGenerator: (req) => req.ip, // Optional: customize key (e.g., req.user.id)
})
);
app.get('/api/hello', (req, res) => {
res.send('Welcome to the Rate Limited API!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});API
rateLimiter(options: RateLimiterOptions): express.RequestHandler
Options
| Option | Type | Required | Description |
|---------------|----------------------------|----------|--------------------------------------------------|
| redisClient | RedisClientType | Yes | An instance of a connected Redis client |
| rateLimit | number | Yes | Max requests allowed per window |
| timeWindow | number | Yes | Window size in seconds |
| keyGenerator| (req: Request) => string | No | Function to generate a unique key per user/route |
How It Works
- On each request, the middleware runs a Lua script in Redis to atomically increment and check the request count for the generated key.
- If the count exceeds
rateLimitwithintimeWindowseconds, a429 Too Many Requestsresponse is sent. - Otherwise, the request proceeds.
TypeScript
Type definitions are included.
You can import types as:
import { RateLimiterOptions } from '@santosh-ddev/rate-limiter';Customization
Key Generation:
By default, uses the request IP.
You can provide your own function to rate limit by user ID, API key, etc.Multiple Routes:
Apply different rate limits to different routes by using the middleware with different options.
