{"id":17760,"library":"koa-unless","title":"Koa Unless","description":"Koa Unless is a utility for Koa.js applications that allows developers to conditionally skip middleware execution based on various criteria such as HTTP method, request path (string or regex), file extension, or a custom function. The current stable version, 1.0.7, was last published about 9 years ago (March 2017). Given its age, it relies on older Koa.js conventions (e.g., generator functions for middleware) and CommonJS modules. This package's primary differentiator is its simple, declarative API for conditional middleware, though modern Koa applications often achieve similar functionality with explicit `if` statements or newer conditional middleware libraries. The project appears to be abandoned, with the last commit also around 9 years ago, indicating no active development or compatibility updates for newer Koa versions or Node.js features like ESM.","status":"abandoned","version":"1.0.7","language":"javascript","source_language":"en","source_url":"https://github.com/Foxandxss/koa-unless","tags":["javascript","koa","middleware","unless"],"install":[{"cmd":"npm install koa-unless","lang":"bash","label":"npm"},{"cmd":"yarn add koa-unless","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-unless","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package is CommonJS-only and does not support ES modules. Attempting to `import` it will result in a runtime error.","wrong":"import unless from 'koa-unless';","symbol":"unless","correct":"const unless = require('koa-unless');"},{"note":"To integrate `koa-unless` with your own middleware, assign the `unless` function to a property named `unless` on your middleware function. This pattern relies on modifying the middleware function directly.","symbol":"mymid.unless","correct":"mymid.unless = require('koa-unless');"},{"note":"The `unless` function is called directly on the middleware you wish to make conditional, returning a new, wrapped middleware that Koa's `app.use` can then consume. Configuration options are passed as an object to `unless`.","symbol":"app.use(middleware.unless({ ... }))","correct":"app.use(static.unless({ path: ['/index.html', '/'] }));"}],"quickstart":{"code":"const Koa = require('koa');\nconst unless = require('koa-unless');\nconst serve = require('koa-static');\n\nconst app = new Koa();\n\n// A simple authentication middleware\nconst requiresAuth = async (ctx, next) => {\n  if (!ctx.headers.authorization || ctx.headers.authorization !== 'Bearer my-secret-token') {\n    ctx.status = 401;\n    ctx.body = 'Unauthorized';\n    return;\n  }\n  await next();\n};\n\n// Make the authentication middleware conditional\n// It will run for all paths EXCEPT '/public' and '/login'\nrequiresAuth.unless = unless;\napp.use(requiresAuth.unless({ path: ['/public', '/login'] }));\n\n// Serve static files from a 'public' directory, unless the method is OPTIONS\nconst staticMiddleware = serve(__dirname + '/public');\nstaticMiddleware.unless = unless;\napp.use(staticMiddleware.unless({ method: 'OPTIONS' }));\n\n// Example public route, accessible without auth\napp.use(async (ctx, next) => {\n  if (ctx.path === '/public') {\n    ctx.body = 'This is a public page!';\n  } else {\n    await next();\n  }\n});\n\n// Example login route, accessible without auth\napp.use(async (ctx) => {\n  if (ctx.path === '/login') {\n    ctx.body = 'Login page, no auth required here.';\n  } else if (!ctx.body) {\n    // If no middleware has set a body yet (meaning auth passed, or path was /public or /login)\n    ctx.body = 'Protected content! You are authorized.';\n  }\n});\n\n// Create a simple 'public' directory for the static middleware\nconst fs = require('fs');\nconst path = require('path');\nconst publicDirPath = path.join(__dirname, 'public');\nif (!fs.existsSync(publicDirPath)) {\n  fs.mkdirSync(publicDirPath);\n}\nfs.writeFileSync(path.join(publicDirPath, 'index.html'), '<h1>Hello from static!</h1>');\n\napp.listen(3000, () => {\n  console.log('Koa app listening on port 3000');\n  console.log('Try:');\n  console.log('  curl http://localhost:3000/public');\n  console.log('  curl http://localhost:3000/login');\n  console.log('  curl http://localhost:3000/ (will be unauthorized)');\n  console.log('  curl -H \"Authorization: Bearer my-secret-token\" http://localhost:3000/');\n});\n","lang":"javascript","description":"This quickstart demonstrates how to apply `koa-unless` to both custom and third-party Koa middleware, using path and method conditions to skip authentication and static file serving respectively. It also includes basic setup for a Koa application and a static directory."},"warnings":[{"fix":"For new applications, consider reimplementing conditional logic directly within your `async` middleware functions or using more modern conditional middleware solutions compatible with `async/await`. If migrating an existing Koa 1.x application, thoroughly test `koa-unless` integration or refactor conditional logic.","message":"Koa-unless was designed for Koa v1.x, which used generator functions for middleware (e.g., `function *(next)`). Modern Koa (v2.x and above) exclusively uses `async/await` functions. While it might still function for simple cases, full compatibility with the cascading `async/await` middleware pattern is not guaranteed, and unexpected behavior may occur.","severity":"breaking","affected_versions":">=2.0.0 (of Koa)"},{"fix":"Evaluate modern alternatives or implement conditional middleware logic natively within your application using standard `if` statements and `async/await`.","message":"This package is abandoned; its last publish was approximately 9 years ago. There will be no further updates for bug fixes, security patches, or compatibility with newer Node.js or Koa versions.","severity":"deprecated","affected_versions":">=1.0.0"},{"fix":"Create `koa-unless.d.ts` declaration files or consider alternatives that provide native TypeScript support.","message":"Koa-unless does not ship with TypeScript type definitions. Using it in a TypeScript project will require creating custom declaration files (`.d.ts`) or disabling type checks for its usage, which can reduce type safety and developer experience.","severity":"gotcha","affected_versions":"*"},{"fix":"Always use a regular `function` declaration for the `custom` option to ensure `this` correctly refers to the Koa context (e.g., `function () { return this.path === '/api'; }`).","message":"The `custom` option for conditional logic provides a `this` context that refers to Koa's `ctx` object. However, if the custom function is an arrow function, `this` will not be bound to `ctx`, leading to unexpected behavior.","severity":"gotcha","affected_versions":"*"},{"fix":"If your project is ESM-first, you will need to either configure your build system to handle CommonJS `require` statements or use dynamic `import()` for `koa-unless`. The recommended approach is to migrate to a modern, actively maintained conditional middleware solution.","message":"Due to its CommonJS nature, `koa-unless` cannot be directly `import`ed in an ES module environment without specific Node.js loader configurations or transpilation. Many modern Koa projects are now ESM-first.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `yourMiddleware.unless = require('koa-unless');` is called before applying the conditional logic to `app.use`.","cause":"Attempting to use `unless` on a middleware that hasn't had `unless` assigned to it, or assigning `unless` incorrectly.","error":"TypeError: app.use(...) is not a function"},{"fix":"If staying with `koa-unless`, ensure all integrated middleware (including `koa-unless` itself, if adapting it) are compatible with either generator functions or `async/await` consistently. For modern Koa, it's strongly recommended to avoid `koa-unless` and use native `async/await` middleware with explicit conditional logic.","cause":"Using `koa-unless` with Koa middleware written as generator functions (Koa v1.x style) while also trying to use `async/await` patterns within your application or in other middleware. This package was designed for Koa v1.x, which utilized generator-based middleware, leading to conflicts with modern `async/await` patterns in Koa v2+.","error":"SyntaxError: await is only valid in async function"},{"fix":"Change the `custom` condition to a regular function declaration (e.g., `function () { return this.url === '/some-path'; }`) to correctly bind `this` to the Koa context (`ctx`).","cause":"Within a `custom` function passed to `unless`, using an arrow function (`() => { ... }`) for the condition. Arrow functions do not bind their own `this` context, causing `this` to refer to the surrounding lexical scope instead of Koa's `ctx` object.","error":"this.url is not a function (or similar property access errors within custom condition)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}