{"id":17449,"library":"koa-ratelimit","title":"Koa Rate Limit Middleware","description":"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.","status":"active","version":"6.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/koajs/ratelimit","tags":["javascript","koa","middleware","rate","ratelimit","ratelimiter"],"install":[{"cmd":"npm install koa-ratelimit","lang":"bash","label":"npm"},{"cmd":"yarn add koa-ratelimit","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-ratelimit","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for the 'redis' driver option, providing the Redis client connection.","package":"ioredis","optional":true},{"reason":"The core web framework that this middleware integrates with.","package":"koa","optional":false}],"imports":[{"note":"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()`.","wrong":"import ratelimit from 'koa-ratelimit';","symbol":"ratelimit","correct":"const ratelimit = require('koa-ratelimit');"},{"note":"Koa itself is typically imported via `require()` in most Koa middleware examples, maintaining consistency with CommonJS module loading.","wrong":"import Koa from 'koa';","symbol":"Koa","correct":"const Koa = require('koa');"},{"note":"The `ioredis` client, used for the Redis driver, is usually imported as a default export via `require()`.","wrong":"import { Redis } from 'ioredis';","symbol":"Redis","correct":"const Redis = require('ioredis');"}],"quickstart":{"code":"const Koa = require('koa');\nconst ratelimit = require('koa-ratelimit');\nconst Redis = require('ioredis');\nconst app = new Koa();\n\n// Initialize Redis client for rate limiting storage\nconst redisClient = new Redis();\n\n// Apply rate limit middleware\napp.use(ratelimit({\n  driver: 'redis',\n  db: redisClient, // Pass the ioredis client instance\n  duration: 60000, // 1 minute\n  errorMessage: 'You have sent too many requests. Please try again later.',\n  id: (ctx) => ctx.ip, // Identify clients by their IP address\n  headers: {\n    remaining: 'X-Rate-Limit-Remaining',\n    reset: 'X-Rate-Limit-Reset',\n    total: 'X-Rate-Limit-Total'\n  },\n  max: 100, // Max 100 requests per minute\n  disableHeader: false,\n  whitelist: (ctx) => {\n    // Example: allow localhost to bypass rate limiting\n    return ctx.ip === '127.0.0.1';\n  },\n  onLimited: (ctx) => {\n    console.log(`Rate limited IP: ${ctx.ip} for path ${ctx.path}`);\n  }\n}));\n\n// Response middleware for successful requests\napp.use(async (ctx) => {\n  ctx.body = 'Hello, Koa! This is an un-rate-limited response.';\n});\n\n// Start the server\napp.listen(3000,\n  () => console.log('Koa server listening on http://localhost:3000')\n);","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 18 or a later compatible version before upgrading to `koa-ratelimit@6`.","message":"Version 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.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Clients consuming your API should read the `Retry-After` header from 429 responses and respect the specified delay before making subsequent requests.","message":"The `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.","severity":"gotcha","affected_versions":">=5.1.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=5.x <6.0.0"},{"fix":"Always initialize `db` correctly, e.g., `db: new Map()` for memory or `db: new Redis()` (assuming `ioredis`) for Redis.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `db` is an instance of `Map` when `driver: 'memory'` or an `ioredis` client instance when `driver: 'redis'`.","cause":"The `db` option was either omitted or provided an invalid type for the configured `driver`.","error":"TypeError: db is not a Map instance or Redis client"},{"fix":"Install `ioredis` explicitly: `npm install ioredis`.","cause":"The `ioredis` package is required for the Redis driver but was not installed in the project's dependencies.","error":"Error: Cannot find module 'ioredis'"},{"fix":"Install `koa` and import it using `const Koa = require('koa');` at the top of your application file.","cause":"The Koa framework itself was not imported or installed, which is necessary for the middleware to function within a Koa application.","error":"ReferenceError: Koa is not defined"}],"ecosystem":"npm","meta_description":null}