Koa Rate Limit Middleware

6.0.0 · active · verified Wed Apr 22

koa-ratelimit is a robust rate limiting middleware designed for Koa web applications. The current stable version is 6.0.0. It provides essential functionality to control and restrict the frequency of client requests to prevent abuse, enhance security, and ensure fair resource usage. Developers can choose between an in-memory driver (using a JavaScript Map) for simple, single-instance deployments or a Redis driver (requiring an ioredis client) for scalable, distributed environments. Key configurable options include the duration of the rate limit window, the maximum number of requests allowed within that duration, custom error messages, and flexible request identification (e.g., by IP address). It also supports advanced features like whitelisting, blacklisting, and custom HTTP headers for communicating rate limit status to clients. Releases follow an evolutionary path, with recent major versions focusing on updated Node.js engine support and feature refinements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `koa-ratelimit` with a Redis backend to limit requests by IP address, including custom error messages, headers, and a whitelist.

const Koa = require('koa');
const ratelimit = require('koa-ratelimit');
const Redis = require('ioredis');
const app = new Koa();

// Initialize Redis client for rate limiting storage
const redisClient = new Redis();

// Apply rate limit middleware
app.use(ratelimit({
  driver: 'redis',
  db: redisClient, // Pass the ioredis client instance
  duration: 60000, // 1 minute
  errorMessage: 'You have sent too many requests. Please try again later.',
  id: (ctx) => ctx.ip, // Identify clients by their IP address
  headers: {
    remaining: 'X-Rate-Limit-Remaining',
    reset: 'X-Rate-Limit-Reset',
    total: 'X-Rate-Limit-Total'
  },
  max: 100, // Max 100 requests per minute
  disableHeader: false,
  whitelist: (ctx) => {
    // Example: allow localhost to bypass rate limiting
    return ctx.ip === '127.0.0.1';
  },
  onLimited: (ctx) => {
    console.log(`Rate limited IP: ${ctx.ip} for path ${ctx.path}`);
  }
}));

// Response middleware for successful requests
app.use(async (ctx) => {
  ctx.body = 'Hello, Koa! This is an un-rate-limited response.';
});

// Start the server
app.listen(3000,
  () => console.log('Koa server listening on http://localhost:3000')
);

view raw JSON →