koa2-ratelimit
raw JSON → 1.1.3 verified Sat Apr 25 auth: no javascript
IP rate-limiting middleware for Koa2, inspired by express-rate-limit. Version 1.1.3 supports Redis, MongoDB (via Mongoose), and Sequelize stores. Release cadence is low; last significant update was in 2020. Differentiators: async/await, flexible interval config (ms or object), per-route keys, and delay-after behavior for throttling. Requires Node >=7.10 and peer deps for advanced stores.
Common errors
error Error: Cannot find module 'redis' ↓
cause Redis store used but 'redis' package not installed.
fix
Run
npm install redis@4 in your project. error TypeError: Invalid interval: must be a number or an object with time units ↓
cause Interval provided in unsupported format (e.g., string).
fix
Use number (milliseconds) or object like
{ hour: 1 }. See docs for supported units. error TypeError: Cannot read property 'middleware' of undefined ↓
cause Using `RateLimit.middleware.middleware()` (typo in README).
fix
Use
RateLimit.middleware(options) only once. error Error: prefixKey is required when using a store ↓
cause Using a database store without specifying `prefixKey`.
fix
Add
prefixKey: 'someKey' to middleware options. Warnings
breaking In v1.0.0, the `messageKey` option was removed; responses now use a standard JSON format. ↓
fix Update to v1.0.0+ and remove `messageKey` from options. Override `message` as a function to customize response.
breaking In v1.0.0, `prefixKey` is now required when using stores to differentiate endpoints. ↓
fix Add `prefixKey` to your middleware options, e.g., `prefixKey: 'my-route'`.
deprecated The `delayAfter` and `timeWait` options are deprecated in favor of simpler throttling mechanisms. ↓
fix Remove `delayAfter` and `timeWait`; use rate-only limiting.
gotcha Redis store requires `redis@4`; older `redis@2` or `redis@3` will cause connection errors. ↓
fix Install `npm install redis@4` and update client configuration to v4 style.
gotcha The package does not ship TypeScript definitions; you must create your own or use `@types/koa2-ratelimit` (community). ↓
fix Install `@types/koa2-ratelimit` or declare module manually.
Install
npm install koa2-ratelimit yarn add koa2-ratelimit pnpm add koa2-ratelimit Imports
- RateLimit wrong
import { RateLimit } from 'koa2-ratelimit';correctconst { RateLimit } = require('koa2-ratelimit'); - Stores wrong
const Stores = require('koa2-ratelimit').Stores;correctconst { Stores } = require('koa2-ratelimit'); - default wrong
import koa2Ratelimit from 'koa2-ratelimit';correctconst koa2Ratelimit = require('koa2-ratelimit');
Quickstart
const Koa = require('koa');
const { RateLimit } = require('koa2-ratelimit');
const app = new Koa();
const limiter = RateLimit.middleware({
interval: { min: 15 },
max: 100,
message: 'Too many requests, please try again later.'
});
app.use(limiter);
app.use(async (ctx) => {
ctx.body = 'Hello World';
});
app.listen(3000);