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.
npm install koa-ratelimitVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Node.js runtime to version 18 or a later compatible version before upgrading to `koa-ratelimit@6`.
Clients consuming your API should read the `Retry-After` header from 429 responses and respect the specified delay before making subsequent requests.
If upgrading from an earlier `v5.x` version, review and re-test any custom logic within your `onLimited` callback to ensure it behaves as expected after the `v6.0.0` update.
Always initialize `db` correctly, e.g., `db: new Map()` for memory or `db: new Redis()` (assuming `ioredis`) for Redis.
Ensure `db` is an instance of `Map` when `driver: 'memory'` or an `ioredis` client instance when `driver: 'redis'`.
Install `ioredis` explicitly: `npm install ioredis`.
Install `koa` and import it using `const Koa = require('koa');` at the top of your application file.