Registry / web-framework / basic-authentication

basic-authentication

JSON →
library1.10.0jsnpmunverified

The `basic-authentication` package provides a flexible solution for implementing HTTP Basic Authentication in Node.js applications, particularly designed for integration with Express.js as middleware. Currently stable at version 1.10.0, its release cadence has focused on ensuring compatibility with newer Node.js versions, with major changes often addressing Node.js engine support or dependency updates. Key differentiators include its versatile API, allowing usage as a global Express middleware, a route-specific callback, or a standalone function for custom authentication logic. It supports authentication against a specified username and password, or by parsing an `htpasswd` file with various hashing algorithms. Unlike simpler basic auth packages, it offers explicit control over response handling (`ending` flag) and error suppression (`suppress` flag), making it adaptable to diverse application architectures. It currently maintains compatibility with Node.js versions 4 and above.

npm install basic-authentication
INSTALL
IMPORT
SIG · BASIC-AUTHENTICATI
B
basic-authentication
web-frameworkjavascriptv1.10.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.

authenticationMiddleware
const authenticationMiddleware = require('basic-authentication')();
import authenticationMiddleware from 'basic-authentication';
The `require` call must be immediately invoked as a function to return the configured middleware instance. Direct ESM import is not supported.
configuredAuthenticationFunction
const authFunction = require('basic-authentication')({ functions: true });
const authFunction = require('basic-authentication'); // Then later trying authFunction({ functions: true });
To use the module as a direct authentication function (not Express middleware), the `functions: true` option must be passed during initialization. This changes the return type from a middleware to a function that takes `req` and returns user info.
legacyAuthenticationObject
const authObject = require('basic-authentication')({ legacy: true });
const authObject = require('basic-authentication')({ functions: true }); // Expecting an object, getting a string
When using `legacy: true`, the module returns an object `{user, password}` if authentication succeeds, or an empty object on failure. Be careful not to confuse this with `functions: true` mode which returns a string.

Demonstrates `basic-authentication` as an Express middleware for a protected route and its functional mode for custom authentication logic, using environment variables for credentials.

const express = require('express'); const basicAuth = require('basic-authentication'); const app = express(); // Configure basic authentication with a custom user and password const authMiddleware = basicAuth({ user: process.env.AUTH_USER || 'myuser', password: process.env.AUTH_PASSWORD || 'mypassword', realm: 'Restricted Area' }); // Apply the authentication middleware to a specific route app.get('/protected', authMiddleware, (req, res) => { res.send('Welcome, authenticated user!'); }); // Or use it in a more functional way for advanced logic const authChecker = basicAuth({ functions: true }); app.get('/admin', (req, res) => { const user = authChecker(req); if (user === (process.env.AUTH_USER || 'myuser')) { res.send(`Hello, admin ${user}!`); } else { res.status(401).send('Unauthorized: Invalid admin user.'); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Try accessing http://localhost:3000/protected with user:myuser and pass:mypassword'); });
Debug
Known issues
breakingSupport for Node.js versions below 4 was removed in `basic-authentication@1.8.0`. Applications targeting older Node.js environments must use an earlier package version.
fix
Upgrade Node.js to version 4 or higher, or pin `basic-authentication` to a version prior to 1.8.0 if legacy Node.js support is essential.
affects: >=1.8.0
gotchaThe module's behavior and return type are drastically altered by the `functions` and `legacy` options. Without these, it returns an Express middleware. With `functions: true`, it returns a function that takes `req` and returns a Base64 string (username). With `legacy: true`, it returns an object `{user, password}`.
fix
Carefully review the `options` documentation for `functions` and `legacy` flags and ensure your usage matches the expected return type and API surface. Always invoke `require('basic-authentication')(options)` with the correct configuration for your desired mode.
affects: >=1.0.0
breakingThe license changed from GPL3 to Apache2 in version 1.9.0. This is a significant change in terms of legal implications for projects depending on this package.
fix
Review your project's licensing requirements and ensure compatibility with the Apache 2.0 license if upgrading to version 1.9.0 or later.
affects: >=1.9.0
gotchaWhen using the `file` option for htpasswd authentication, ensure the `hash` option correctly specifies the hashing algorithm (e.g., 'md5') used in your `.htpasswd` file. Incorrect hash types will lead to failed authentication.
fix
Verify the hash algorithm used when generating your `.htpasswd` file and set the `hash` option accordingly in your `basic-authentication` configuration.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: basicAuth is not a function
The `require('basic-authentication')` statement was not immediately invoked with parentheses.
fix
Change `const basicAuth = require('basic-authentication');` to `const basicAuth = require('basic-authentication')();` (or pass options: `require('basic-authentication')(options)`).
HTTP 401 Unauthorized
Invalid username or password provided, or no credentials were sent. This could also be due to an incorrect `htpasswd` file path or hash configuration.
fix
Check the username and password in the client request. Verify the `user`, `password`, `file`, and `hash` options in your `basic-authentication` configuration. Ensure the `realm` is correctly set if using custom values.
TypeError: Cannot read properties of undefined (reading 'user') // when using functions or legacy mode
Attempting to access `user` or `password` properties on the return value of `basic-authentication` when not in `legacy` mode, or when authentication failed in `legacy` mode (which returns an empty object).
fix
If using `functions: true`, the return value is a Base64 string, not an object. If using `legacy: true`, ensure you check for an empty object `{}` before accessing properties, indicating authentication failure.
Upgrade
Version history
1.10.0latest on npm
Audit
Dependencies
setheadersrequiredUsed internally to set HTTP response headers, particularly 'WWW-Authenticate' for challenge-response authentication.
Agent activity
25 hits · last 30 days
node
22
OpenAI (training)
1
Resources
basic-authentication — npm install basic-authentication · libregistry