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.
npm install koa-basic-authVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.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.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');`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')`.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.