Registry / web-framework / koa-ratelimit

koa-ratelimit

JSON →
library6.0.0jsnpmunverified

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-ratelimit
INSTALL
IMPORT
SIG · KOA-RATELIMIT
K
koa-ratelimit
web-frameworkjavascriptv6.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ratelimit
const ratelimit = require('koa-ratelimit');
import ratelimit from 'koa-ratelimit';
As of v6.0.0, the package's primary export for common usage remains a CommonJS default export. While Node.js v18+ supports ESM, the provided examples and typical usage patterns still rely on `require()`.
Koa
const Koa = require('koa');
import Koa from 'koa';
Koa itself is typically imported via `require()` in most Koa middleware examples, maintaining consistency with CommonJS module loading.
Redis
const Redis = require('ioredis');
import { Redis } from 'ioredis';
The `ioredis` client, used for the Redis driver, is usually imported as a default export via `require()`.

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') );
Debug
Known issues
breakingVersion 6.0.0 and above of `koa-ratelimit` explicitly require Node.js v18 or newer. Deployments on older Node.js environments will fail with engine incompatibility errors.
fix
Upgrade your Node.js runtime to version 18 or a later compatible version before upgrading to `koa-ratelimit@6`.
affects: >=6.0.0
gotchaThe `Retry-After` HTTP header is automatically set in 429 'Too Many Requests' responses since `v5.1.0` when a limit is exceeded and an error is thrown. This provides clients with a standardized time (in seconds) to wait before retrying. Ensure your client-side error handling is prepared to interpret this header.
fix
Clients consuming your API should read the `Retry-After` header from 429 responses and respect the specified delay before making subsequent requests.
affects: >=5.1.0
gotchaThe `onLimited` callback function, which allows custom logic to execute when a request is rate-limited, was fixed in `v6.0.0` to ensure correct functionality. If you were using this callback in earlier `v5.x` versions, its behavior might have been inconsistent or broken.
fix
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.
affects: >=5.x <6.0.0
gotchaThe `db` option is mandatory and must be an appropriate instance for the chosen `driver` (`Map` for 'memory', `ioredis` client for 'redis'). Providing an incorrect or uninitialized `db` will lead to runtime errors when the middleware attempts to store or retrieve rate limit data.
fix
Always initialize `db` correctly, e.g., `db: new Map()` for memory or `db: new Redis()` (assuming `ioredis`) for Redis.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: db is not a Map instance or Redis client
The `db` option was either omitted or provided an invalid type for the configured `driver`.
fix
Ensure `db` is an instance of `Map` when `driver: 'memory'` or an `ioredis` client instance when `driver: 'redis'`.
Error: Cannot find module 'ioredis'
The `ioredis` package is required for the Redis driver but was not installed in the project's dependencies.
fix
Install `ioredis` explicitly: `npm install ioredis`.
ReferenceError: Koa is not defined
The Koa framework itself was not imported or installed, which is necessary for the middleware to function within a Koa application.
fix
Install `koa` and import it using `const Koa = require('koa');` at the top of your application file.
Upgrade
Version history
6.0.0latest on npm
Audit
Dependencies
ioredisoptionalRequired for the 'redis' driver option, providing the Redis client connection.
koarequiredThe core web framework that this middleware integrates with.
Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources
koa-ratelimit — npm install koa-ratelimit · libregistry