@moksh05/tiny-rate-limiter
v1.0.2
Published
A lightweight and extensible multi-algorithm rate limiter for Node.js and Express.
Downloads
21
Maintainers
Readme
Tiny Rate Limiter
A powerful, highly structured, and extensible rate limiting package for Node.js and Express.
Features
- 5 Rate Limiting Algorithms:
fixed-window: Simple and efficient.sliding-window-log: Most accurate, prevents bursts.sliding-window-counter: Smooth transitions between windows.token-bucket: Supports bursts with a steady refill rate.leaky-bucket: Smooths out request processing.
- 2 Storage Strategies:
memory: Local in-memory storage (Map-based).redis: Distributed storage using Redis (powered byioredis).
- Flexible Key Generation:
- Limit by IP Address, UserID, API Key, or a custom function.
- Customizable:
- Custom error messages and status codes.
- Full TypeScript support.
Installation
npm install tiny-rate-limiterUsage
Simple Example (Fixed Window, IP-based)
const express = require('express');
const { createRateLimiter } = require('tiny-rate-limiter');
const app = express();
const limiter = createRateLimiter({
windowMs: 60 * 1000, // 1 minute
limit: 100, // 100 requests per minute
algorithm: 'fixed-window',
storage: 'memory',
keyGenerator: 'ip'
});
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000);Redis (Distributed) Example
const limiter = createRateLimiter({
windowMs: 15 * 60 * 1000,
limit: 50,
algorithm: 'token-bucket',
storage: 'redis',
redisUrl: 'redis://localhost:6379',
keyGenerator: 'apikey'
});Custom Key Generator
const limiter = createRateLimiter({
windowMs: 60 * 1000,
limit: 10,
algorithm: 'sliding-window-counter',
storage: 'memory',
keyGenerator: (req) => req.headers['x-client-id']
});Configuration Options
| Option | Type | Description |
| --- | --- | --- |
| windowMs | number | Time window in milliseconds. |
| limit | number | Maximum number of requests within the window. |
| algorithm | string | fixed-window, sliding-window-log, sliding-window-counter, token-bucket, leaky-bucket. |
| storage | string | memory or redis. |
| redisUrl | string | Required if storage is redis. |
| keyGenerator | string \| function | ip, userid, apikey, or a custom function (req) => string. |
| message | string | Custom error message (optional). |
| statusCode | number | Custom status code (default 429). |
License
MIT
