What is rate-limit-redis?
The rate-limit-redis npm package is a Redis-backed store for the express-rate-limit middleware. It allows you to implement rate limiting in your Express applications using Redis as the storage backend. This is particularly useful for distributed applications where you need to share rate limit data across multiple instances.
What are rate-limit-redis's main functionalities?
Basic Rate Limiting
This code demonstrates how to set up basic rate limiting in an Express application using Redis as the storage backend. The rate limiter is configured to allow 100 requests per 15 minutes per IP address.
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const redisClient = require('redis').createClient();
const limiter = rateLimit({
store: new RedisStore({
client: redisClient
}),
max: 100, // limit each IP to 100 requests per windowMs
windowMs: 15 * 60 * 1000 // 15 minutes
});
const express = require('express');
const app = express();
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Custom Redis Client
This example shows how to use a custom Redis client configuration with the rate-limit-redis package. This is useful if you need to connect to a Redis instance with specific connection settings.
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const redis = require('redis');
const customRedisClient = redis.createClient({
host: 'custom-redis-host',
port: 6379,
password: 'your-redis-password'
});
const limiter = rateLimit({
store: new RedisStore({
client: customRedisClient
}),
max: 50, // limit each IP to 50 requests per windowMs
windowMs: 10 * 60 * 1000 // 10 minutes
});
const express = require('express');
const app = express();
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Dynamic Rate Limiting
This code demonstrates how to implement dynamic rate limiting based on user properties. In this example, premium users are allowed more requests compared to regular users.
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const redisClient = require('redis').createClient();
const dynamicLimiter = rateLimit({
store: new RedisStore({
client: redisClient
}),
max: (req, res) => {
if (req.user && req.user.isPremium) {
return 200; // higher limit for premium users
}
return 100; // default limit
},
windowMs: 15 * 60 * 1000 // 15 minutes
});
const express = require('express');
const app = express();
app.use(dynamicLimiter);
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Other packages similar to rate-limit-redis
express-rate-limit
The express-rate-limit package is a middleware for rate limiting in Express applications. It does not include a built-in store for Redis, but it can be extended with custom stores like rate-limit-redis. It is a good choice if you need a simple rate limiting solution without a specific storage backend.
rate-limiter-flexible
The rate-limiter-flexible package is a highly flexible rate limiting library that supports various backends including Redis, MongoDB, and in-memory storage. It offers more advanced features and customization options compared to rate-limit-redis, making it suitable for complex rate limiting requirements.
redis-rate-limiter
The redis-rate-limiter package is a Redis-based rate limiter that can be used with any Node.js application. It provides a simple API for rate limiting and is not tied to Express, making it a versatile choice for different types of applications.
rate-limit-redis
Installation
From the npm registry:
> npm install rate-limit-redis
> yarn/pnpm add rate-limit-redis
From Github Releases:
> npm install https://github.com/express-rate-limit/rate-limit-redis/releases/download/v{version}/rate-limit-redis.tgz
> yarn/pnpm add https://github.com/express-rate-limit/rate-limit-redis/releases/download/v{version}/rate-limit-redis.tgz
Replace {version}
with the version of the package that you want to use, e.g.:
3.0.0
.
Usage
Importing
This library is provided in ESM as well as CJS forms, and works with both
Javascript and Typescript projects.
This package requires you to use Node 16 or above.
Import it in a CommonJS project (type: commonjs
or no type
field in
package.json
) as follows:
const { RedisStore } = require('rate-limit-redis')
Import it in a ESM project (type: module
in package.json
) as follows:
import { RedisStore } from 'rate-limit-redis'
Examples
To use it with a node-redis
client:
import { rateLimit } from 'express-rate-limit'
import { RedisStore } from 'rate-limit-redis'
import { createClient } from 'redis'
const client = createClient({
})
await client.connect()
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
store: new RedisStore({
sendCommand: (...args: string[]) => client.sendCommand(args),
}),
})
app.use(limiter)
To use it with a ioredis
client:
import { rateLimit } from 'express-rate-limit'
import { RedisStore } from 'rate-limit-redis'
import RedisClient from 'ioredis'
const client = new RedisClient()
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
store: new RedisStore({
sendCommand: (...args: string[]) => client.call(...args),
}),
})
app.use(limiter)
Configuration
sendCommand
The function used to send commands to Redis. The function signature is as
follows:
;(...args: string[]) => Promise<number> | number
The raw command sending function varies from library to library; some are given
below:
Library | Function |
---|
node-redis | async (...args: string[]) => client.sendCommand(args) |
ioredis | async (...args: string[]) => client.call(...args) |
handy-redis | async (...args: string[]) => client.nodeRedis.sendCommand(args) |
tedis | async (...args: string[]) => client.command(...args) |
redis-fast-driver | async (...args: string[]) => client.rawCallAsync(args) |
yoredis | async (...args: string[]) => (await client.callMany([args]))[0] |
noderis | async (...args: string[]) => client.callRedis(...args) |
prefix
The text to prepend to the key in Redis.
Defaults to rl:
.
resetExpiryOnChange
Whether to reset the expiry for a particular key whenever its hit count changes.
Defaults to false
.
License
MIT © Wyatt Johnson,
Nathan Friedly,
Vedant K