{"id":16636,"library":"koa-basic-auth","title":"Koa Basic HTTP Authentication Middleware","description":"koa-basic-auth provides a straightforward middleware for implementing blanket HTTP Basic Authentication within Koa applications. It's designed for simple use cases where a single username and password (or just one of them since v4.0.0) protects all subsequent middleware in the stack. The current stable version is 4.0.0. Releases are tied to the Koa ecosystem, typically stable and less frequent, with major updates addressing underlying security practices or JavaScript module changes. Its key differentiator is its simplicity and explicit focus on 'blanket' authentication, contrasting with more complex authentication libraries that offer granular control, roles, or advanced strategies. It is not intended for fine-grained access control but rather for protecting entire sections of an application.","status":"active","version":"4.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/koajs/basic-auth","tags":["javascript","koa","auth","authentication","basicauth","basic auth"],"install":[{"cmd":"npm install koa-basic-auth","lang":"bash","label":"npm"},{"cmd":"yarn add koa-basic-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-basic-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for time-safe string comparison of credentials, improving security against timing attacks. Added in v4.0.0.","package":"tsscmp","optional":false}],"imports":[{"note":"koa-basic-auth is primarily a CommonJS module. While modern Koa applications can be ESM, importing this middleware typically requires `require()`. Direct ESM `import` statements may fail in pure ESM environments or necessitate specific build configurations/polyfills like `createRequire`.","wrong":"import auth from 'koa-basic-auth'; // Incorrect for CommonJS-only packages in pure ESM context\nimport { auth } from 'koa-basic-auth'; // Incorrect, it's a default export","symbol":"auth","correct":"const auth = require('koa-basic-auth');"}],"quickstart":{"code":"const auth = require('koa-basic-auth');\nconst Koa = require('koa');\nconst app = new Koa();\n\n// custom 401 handling to present a Basic Auth challenge to the client\napp.use(async (ctx, next) => {\n  try {\n    await next();\n  } catch (err) {\n    if (err.status === 401) {\n      ctx.status = 401;\n      ctx.set('WWW-Authenticate', 'Basic');\n      ctx.body = 'Authentication Required';\n    } else {\n      throw err;\n    }\n  }\n});\n\n// Apply basic authentication to all downstream middleware\n// Use environment variables for sensitive credentials in production\napp.use(auth({ name: 'tj', pass: process.env.BASIC_AUTH_PASS ?? 'tobi' }));\n\n// This middleware will only execute if authentication succeeds\napp.use(async (ctx) => {\n  ctx.body = 'Welcome, authenticated user!';\n});\n\nconst port = process.env.PORT || 3000;\napp.listen(port, function () {\n  console.log(`Koa server listening on port ${port}`);\n});\n\n// To test with curl: curl -H \"Authorization: basic dGo6dG9iaQ==\" http://localhost:3000/","lang":"javascript","description":"Demonstrates how to apply blanket basic authentication to a Koa application, including essential custom 401 error handling and setting the WWW-Authenticate header to prompt clients. Uses environment variable for password for security."},"warnings":[{"fix":"Review your authentication logic. If your application previously assumed both credentials were mandatory for validation, adjust your security expectations or enforce both explicitly if needed. The middleware will now authenticate successfully if only one credential (name or pass) matches.","message":"Starting with v4.0.0, koa-basic-auth no longer requires both a `name` (username) and a `pass` (password) to be provided in the options object. Either `name` or `pass` (or both) can now be used for authentication. This change aligns with updated behavior in the underlying `basic-auth` module.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"To protect a specific prefix, use `koa-mount`: `app.use(mount('/admin', auth({ name: 'user', pass: 'password' })));`. For more granular route protection, integrate it into your router's middleware stack for specific routes or groups of routes.","message":"koa-basic-auth provides 'blanket' authentication, meaning it applies to all downstream middleware from where it's mounted. For selective protection of specific paths or routes, it must be explicitly combined with routing middleware (e.g., `koa-router`) or `koa-mount`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always wrap your `app.use(auth(...))` call or the relevant middleware stack in a `try...catch` block that specifically handles errors where `err.status === 401`. Within this catch block, set `ctx.status = 401` and `ctx.set('WWW-Authenticate', 'Basic')` to correctly challenge the client.","message":"Failing to implement custom 401 error handling for the `Koa.prototype.context.throw(401)` call will result in a generic 500 'Internal Server Error' instead of a proper 401 'Unauthorized' response. This also means the `WWW-Authenticate` header won't be set, preventing browsers from prompting for credentials.","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 your project's module system is consistent. If `koa-basic-auth` is a CommonJS module (which it is), use `const auth = require('koa-basic-auth');`. If in an ESM-only context, you might need to use `const { createRequire } = require('module'); const require = createRequire(import.meta.url); const auth = require('koa-basic-auth');`","cause":"This error occurs when attempting to use `require()` to import an ES Module, or more commonly, trying to `import` a CommonJS module like `koa-basic-auth` in an ES Module context without proper interop mechanisms.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported"},{"fix":"Add a `try...catch` block around your middleware usage as demonstrated in the quickstart example. This block should explicitly check for `err.status === 401` and handle it by setting `ctx.status = 401` and `ctx.set('WWW-Authenticate', 'Basic')`.","cause":"The basic authentication failed, but the Koa application did not have a custom error handling middleware in place to catch the `ctx.throw(401)` error emitted by `koa-basic-auth`.","error":"HTTP/1.1 500 Internal Server Error (when authentication fails)"},{"fix":"Inside your 401 error handler, make sure `ctx.set('WWW-Authenticate', 'Basic');` is explicitly called. This header is crucial for initiating the client-side authentication challenge.","cause":"While a custom 401 error handler is present, it's not correctly setting the `WWW-Authenticate` header, which is essential for a client (like a web browser) to understand that Basic Auth credentials are required and to prompt the user.","error":"HTTP/1.1 401 Unauthorized (but no browser/client prompt)"}],"ecosystem":"npm"}