The `koa-ip` package provides a robust IP filtering middleware specifically designed for Koa applications. It allows developers to manage network access by configuring either a `whitelist` to permit specific IP addresses or a `blacklist` to deny them. The package accommodates both literal IP strings and regular expressions for defining patterns, enabling flexible control over single IPs, IP ranges, or subnets. Currently stable at version 2.1.4, `koa-ip` exhibits a stable release cadence, typical for well-defined utility middleware, suggesting ongoing maintenance rather than rapid feature development. Its key differentiators include a minimalist API, seamless integration into the Koa middleware chain, and built-in TypeScript definitions, making it easy to adopt in modern Koa projects. By default, it returns a 403 Forbidden status for blacklisted IPs, a behavior that can be customized with an asynchronous handler function, offering fine-grained control over denied requests.
npm install koa-ipVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to set up `koa-ip` middleware with both whitelist and blacklist configurations, including a custom handler for blacklisted IPs. It also includes a simulated IP setter for easy local testing of different scenarios.
Ensure `app.use(ip(...))` is called before other route-handling or request-processing middlewares.
Provide a custom `handler` function in the `koa-ip` options object: `{ blacklist: [...], handler: async (ctx, next) => { ctx.status = 401; ctx.body = 'Unauthorized'; } }`If your Koa app is behind a proxy, set `app.proxy = true;` during Koa application initialization to correctly parse client IPs from `X-Forwarded-For`.
Thoroughly test all IP patterns (whitelist and blacklist) to confirm they match intended IP ranges. Use online regex testers for complex regular expressions. Refer to `koa-ip` documentation for supported wildcard syntax and CIDR interpretation.
Ensure you have `const Koa = require('koa');` (or `import Koa from 'koa';`) and `const app = new Koa();` at the start of your application file.Verify `koa-ip` is `app.use()`d early in your middleware stack. Double-check your `whitelist` and `blacklist` patterns. If behind a proxy, ensure `app.proxy = true;` is configured.
Either use the TypeScript-specific CommonJS import: `import ip = require('koa-ip');` or enable `"esModuleInterop": true` and `"allowSyntheticDefaultImports": true` in your `tsconfig.json`.