-
-
Notifications
You must be signed in to change notification settings - Fork 162
Express Middleware
Create middleware/rateLimiterRedis.js
.
You can use any limiter from this package the same way.
Note, be careful with express trust proxy
set to true
. You should always expect x-forwarded-for
headers can be spoofed. You can limit it to specific IPs or number of hops from your server. Read more on express behind proxies docs.
const Redis = require('ioredis');
const {RateLimiterRedis} = require('rate-limiter-flexible');
const redisClient = new Redis({ enableOfflineQueue: false });
const rateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'middleware',
points: 10, // 10 requests
duration: 1, // per 1 second by IP
// Use this flag for the `redis` package
useRedisPackage: true,
});
const rateLimiterMiddleware = (req, res, next) => {
rateLimiter.consume(req.ip)
.then(() => {
next();
})
.catch(() => {
res.status(429).send('Too Many Requests');
});
};
module.exports = rateLimiterMiddleware;
Import created middleware and use it
const express = require('express');
const rateLimiterRedisMiddleware = require('./middleware/rateLimiterRedis');
const app = express();
app.use(rateLimiterRedisMiddleware);
Middleware with different logic and limiters can be applied to exact route or application part as well.
Mongo, Memcache, MySQL or any other limiter from this package can be used with the same approach.
Alternatively, you can try express-rate-limit package, which may be more appropriate for your case.
Get started
Middlewares and plugins
Migration from other packages
Limiters:
- Redis
- Memory
- DynamoDB
- Prisma
- MongoDB (with sharding support)
- PostgreSQL
- MySQL
- BurstyRateLimiter
- Cluster
- PM2 Cluster
- Memcached
- RateLimiterUnion
- RateLimiterQueue
Wrappers:
- RLWrapperBlackAndWhite Black and White lists
Knowledge base:
- Block Strategy in memory
- Insurance Strategy
- Comparative benchmarks
- Smooth out traffic peaks
-
Usage example
- Minimal protection against password brute-force
- Login endpoint protection
- Websocket connection prevent flooding
- Dynamic block duration
- Different limits for authorized users
- Different limits for different parts of application
- Block Strategy in memory
- Insurance Strategy
- Third-party API, crawler, bot rate limiting