Registry / auth-security / koa-basic-auth

koa-basic-auth

JSON →
library4.0.0jsnpmunverified

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-auth
INSTALL
IMPORT
SIG · KOA-BASIC-AUTH
K
koa-basic-auth
auth-securityjavascriptv4.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

auth
const auth = require('koa-basic-auth');
import auth from 'koa-basic-auth'; // Incorrect for CommonJS-only packages in pure ESM context import { auth } from 'koa-basic-auth'; // Incorrect, it's a default export
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`.

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.

const auth = require('koa-basic-auth'); const Koa = require('koa'); const app = new Koa(); // custom 401 handling to present a Basic Auth challenge to the client app.use(async (ctx, next) => { try { await next(); } catch (err) { if (err.status === 401) { ctx.status = 401; ctx.set('WWW-Authenticate', 'Basic'); ctx.body = 'Authentication Required'; } else { throw err; } } }); // Apply basic authentication to all downstream middleware // Use environment variables for sensitive credentials in production app.use(auth({ name: 'tj', pass: process.env.BASIC_AUTH_PASS ?? 'tobi' })); // This middleware will only execute if authentication succeeds app.use(async (ctx) => { ctx.body = 'Welcome, authenticated user!'; }); const port = process.env.PORT || 3000; app.listen(port, function () { console.log(`Koa server listening on port ${port}`); }); // To test with curl: curl -H "Authorization: basic dGo6dG9iaQ==" http://localhost:3000/
Debug
Known issues
breakingStarting 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.
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.
affects: >=4.0.0
gotchakoa-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`.
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.
affects: >=1.0.0
gotchaFailing 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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported
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.
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');`
HTTP/1.1 500 Internal Server Error (when authentication fails)
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`.
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')`.
HTTP/1.1 401 Unauthorized (but no browser/client prompt)
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.
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.
Upgrade
Version history
4.0.0latest on npm
Audit
Dependencies
tsscmprequiredUsed for time-safe string comparison of credentials, improving security against timing attacks. Added in v4.0.0.
Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources
koa-basic-auth — npm install koa-basic-auth · libregistry