Registry / auth-security / basicauth-middleware

basicauth-middleware

JSON →
library3.1.1jsnpmunverified

basicauth-middleware is an Express.js middleware designed for implementing HTTP Basic Authentication on web routes. Currently at version 3.1.1, the package is in a maintenance state, with the last major update (v3) occurring in 2021 which dropped support for Node.js versions below 10 and enhanced asynchronous credential checking. It allows for flexible authentication strategies, accepting plain username/password pairs, arrays of credentials, or custom synchronous/asynchronous callback functions, including Promise-based and async/await syntax. This middleware is suitable for protecting administrative interfaces, APIs, or internal tools where a simple, stateless authentication mechanism is sufficient. Key differentiators include its simplicity and versatility in defining authentication logic directly within the application.

npm install basicauth-middleware
INSTALL
IMPORT
SIG · BASICAUTH-MIDDLEWA
B
basicauth-middleware
auth-securityjavascriptv3.1.1
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.

basicauth
const basicauth = require('basicauth-middleware');
import basicauth from 'basicauth-middleware';
Primarily designed for CommonJS; direct ESM import may not work without a bundler or Node.js loader configuration for older packages. Version 3 dropped Node <10 support, but `require` is still the idiomatic import shown in documentation.
basicauth (with named export pattern, though not explicitly supported)
const basicauth = require('basicauth-middleware');
import { basicauth } from 'basicauth-middleware';
The package exports a single function as its module.exports. Attempting a named import in ESM or CJS will likely result in an undefined symbol or error. Always use the default import pattern shown in the `correct` example.
basicauth (as an Express middleware function)
app.use(basicauth('user', 'pass'));
app.use(basicauth); // Missing arguments for configuration
The `basicauth` import is a function that *returns* an Express middleware. It must be called with configuration (credentials or a callback) to produce a usable middleware function.

Demonstrates protecting an Express.js route with basicauth-middleware using an async callback for credential verification.

const express = require('express'); const basicauth = require('basicauth-middleware'); const app = express(); // Simulate an asynchronous user database check const verifyUser = async (username, password) => { console.log(`Attempting to authenticate user: ${username}`); return new Promise(resolve => { setTimeout(() => { // In a real app, you'd check a database or external service if (username === process.env.AUTH_USERNAME && password === process.env.AUTH_PASSWORD) { console.log(`User ${username} authenticated successfully.`); resolve(true); } else { console.log(`Authentication failed for user: ${username}.`); resolve(false); } }, 100); }); }; // Protect all routes under /admin with basic authentication app.use('/admin', basicauth(verifyUser, 'Admin Area')); // A protected route app.get('/admin/dashboard', (req, res) => { res.send('Welcome to the Admin Dashboard, authenticated user!'); }); // An unprotected route app.get('/', (req, res) => { res.send('Public homepage.'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Access http://localhost:3000/admin/dashboard (requires AUTH_USERNAME and AUTH_PASSWORD environment variables)'); }); // To run this, set environment variables: // AUTH_USERNAME=testuser // AUTH_PASSWORD=testpass
Debug
Known issues
breakingVersion 3.0.0 of `basicauth-middleware` dropped support for Node.js versions older than 10. Applications running on Node.js 6 or 8 (which were supported by v2) will break upon upgrading to v3.
fix
Ensure your project's Node.js version is 10 or higher before upgrading to `basicauth-middleware@3.x.x`. Consider using an NVM to manage Node.js versions, or update your deployment environment.
affects: >=3.0.0
breakingThe behavior of authentication callbacks changed significantly in v3. While older versions primarily relied on synchronous or Node-style async callbacks, v3 embraces Promises and async/await. Callback functions are now expected to return a boolean or a Promise resolving to a boolean, rather than using a `cb(err, result)` signature.
fix
Review and update custom authentication callback functions to return a boolean directly for synchronous checks, or a Promise (or be an `async` function) that resolves to `true` or `false` for asynchronous checks. The `cb(null, auth)` style is still shown in the README but the primary examples emphasize Promise returns.
affects: >=3.0.0
gotchaBasic Authentication transmits credentials Base64-encoded, not encrypted. If used over HTTP, credentials can be easily intercepted and decoded. This poses a significant security risk for sensitive applications.
fix
ALWAYS use `basicauth-middleware` exclusively over HTTPS (TLS/SSL). This ensures the entire communication, including the Basic Auth header, is encrypted in transit. Configure your server or reverse proxy (e.g., Nginx, Traefik) to enforce HTTPS for all requests to protected endpoints.
affects: >=1.0.0
gotchaWhen implementing custom authentication callbacks, standard string comparisons (e.g., `===`) for passwords can be vulnerable to timing attacks, where an attacker deduces parts of a password by measuring response times.
fix
Use a cryptographically secure, constant-time comparison function (e.g., Node.js `crypto.timingSafeEqual`) for comparing sensitive data like passwords within your custom authentication logic. This mitigates timing attack vulnerabilities.
affects: >=1.0.0
gotchaIf the `basicauth` middleware is not called with arguments (e.g., `app.use(basicauth);`), it will not function correctly and will likely throw an error or fail to protect routes, as it expects configuration arguments.
fix
Always invoke `basicauth` with appropriate credentials or a callback function, e.g., `app.use(basicauth('user', 'pass'))` or `app.use(basicauth(async (u,p) => { ... }))`. The function call returns the actual middleware.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: basicauth is not a function
Attempting to use `basicauth-middleware` with an incorrect import statement (e.g., `import basicauth from 'basicauth-middleware';` in a CJS context or without proper ESM configuration) or if the `require` statement returned `undefined`.
fix
Ensure you are using `const basicauth = require('basicauth-middleware');` for CommonJS projects. If using ESM, you might need a transpiler or a Node.js version with full ESM-CJS interop and potentially a custom loader if the package isn't dual-bundled.
Error: Not Authenticated
This is a common custom error message returned by the middleware when authentication fails. It indicates that the provided credentials (username/password) were incorrect or not provided in the `Authorization` header, based on the configured authentication logic.
fix
Double-check the username and password being sent by the client. Verify the middleware's configuration (plain credentials or custom callback logic) ensures it matches expected values. Inspect the network request to confirm the `Authorization` header is correctly formatted (`Basic <base64-encoded-credentials>`).
ERR_REQUIRE_ESM
This error occurs when a CommonJS `require()` call attempts to load an ES Module (ESM) that does not provide a CommonJS export, typically in a project where `type: module` is set in `package.json` or you're trying to mix module types incorrectly.
fix
As `basicauth-middleware` is primarily CJS, if your project is ESM-native, you might need to use dynamic `import()`: `const basicauth = await import('basicauth-middleware')`. Alternatively, ensure your build setup correctly handles CJS interop, or use an older Node.js version if still on `type: commonjs` and encountering issues.
Upgrade
Version history
3.1.1latest on npm
Audit
Dependencies
expressrequiredThis is an Express.js middleware and requires Express to function.
Agent activity
33 hits · last 30 days
node
30
OpenAI (training)
1
Resources