An express rate-limiting middleware using redis as its storage
- Express > v4
- Redis > v2.6.12
- ioredis > v4 or ioredis-mock > v4
npm i express-rate-limit-redis
const express = require('express');
const app = express();
const RateLimiter = require('express-rate-limit-redis');
const Redis = require('ioredis');
const client = new Redis();
const limiter = RateLimiter({
client,
id: 'verify-phone-number',
max: 3, // limit each IP to 3 requests per windowMs
windowMs: 60 * 1000, // 1 minute
});
app.use('/verify-phone-number', limiter);
app.get('/verify-phone-number', (req, res) => {
res.json({
msg: 'ok',
});
});
const limiter2 = RateLimiter({
client,
id: 'change-password',
max: 1, // limit each IP to 1 requests per windowMs
windowMs: 10 * 60 * 1000, // 10 minute
});
app.get('/change-password', limiter2, (req, res) => {
res.json({
msg: 'ok',
});
});
const { PORT = 8080 } = process.env;
app.listen(PORT);
console.log(`server running on https://localhost:${PORT}`);
- Start example server
# install dependency
npm i
# ts to js
npm run build
# start example server
node example/server.jss
- Navigate to
https://localhost:8080/verify-phone-number
- Refresh the page for 3 times, you will find you are rate limited
Identifier of a limiter, to support multiple rate-limiter
Max number of connections during windowMs milliseconds before sending a 429 response.
How long in milliseconds to keep records of requests in memory.
- rate limit based not only on
req.ip
, but on params ofreq
- skip/whitelist requests
- customize statusCode
- header denoting request limit (X-RateLimit-Limit) and current usage (X-RateLimit-Remaining)
- add test
- ts lint