-
-
Notifications
You must be signed in to change notification settings - Fork 162
Koa Middleware
Roman edited this page Nov 10, 2023
·
12 revisions
const redis = require('ioredis');
const {RateLimiterRedis} = require('rate-limiter-flexible');
const redisClient = new Redis({
host: 'redis',
port: 6379,
enableOfflineQueue: false,
});
const rateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: 'middleware',
points: 10, // 10 requests for ctx.ip
duration: 1, // per 1 second
});
app.use(async (ctx, next) => {
try {
await rateLimiter.consume(ctx.ip)
} catch (rejRes) {
ctx.status = 429
ctx.body = 'Too Many Requests'
// Or you can throw an exception
// ctx.throw(429, 'Too Many Requests')
return
}
await next()
})
Mongo, Memcached, MySQL, PostgreSQL, Cluster or any other limiter from this package can be used as well.
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