Skip to content

Koa Middleware

Roman edited this page Nov 13, 2021 · 12 revisions

Koa Middleware

const redis = require('redis');
const {RateLimiterRedis} = require('rate-limiter-flexible');

const redisClient = redis.createClient({
  host: 'redis',
  port: 6379,
  enable_offline_queue: 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.

See all options here