HTTP Basic Auth for Node.js
The `basic` package provides a minimalist HTTP Basic Authentication middleware for Node.js applications. It abstracts the process of parsing the `Authorization` header and validating user credentials against a provided callback function. As of its latest stable version, 2.0.3 (published over seven years ago), the package is primarily designed for CommonJS environments and integrates directly with Node.js's native `http` module. It follows a callback-based asynchronous pattern for credential verification. Its primary differentiation lies in its extreme simplicity and lack of external dependencies, making it a lightweight option for adding basic authentication to a server. Due to its age, it receives infrequent updates and may not natively support modern JavaScript features like Promises or ES Modules without additional wrappers.
Common errors
-
TypeError: basic is not a function
cause Attempting to use ES Module `import basic from 'basic';` syntax, or incorrect `require` usage.fixChange your import to `const basic = require('basic');` as the package is CommonJS-only. -
401 Unauthorized (but no login prompt in browser)
cause The `WWW-Authenticate` header was not correctly set in the HTTP response when authentication failed.fixOn authentication failure, ensure you set the `WWW-Authenticate` header: `res.writeHead(401, {'WWW-Authenticate': 'Basic realm="Secure Area"'});` -
Authentication always fails / user and pass are always incorrect
cause The callback function provided to `basic()` is not correctly invoking `callback(null)` on success or `callback(401)` on failure, or the credential verification logic is flawed.fixDouble-check your `user` and `pass` comparison logic and ensure `callback(null)` is called when credentials are valid, and `callback(401)` (or another error code) when invalid.
Warnings
- gotcha The `basic` package is CJS-only and does not support ES Modules natively. Attempting to use `import` statements will result in runtime errors.
- gotcha This package requires manual handling of the `WWW-Authenticate` header for 401 Unauthorized responses. Failing to set this header will prevent browsers and clients from prompting for credentials.
- gotcha The package uses an older callback-based asynchronous pattern. It does not natively support Promises or async/await syntax, which might require wrapping the authentication function for use in modern async codebases.
Install
-
npm install basic -
yarn add basic -
pnpm add basic
Imports
- basic
import basic from 'basic'; // Does not support ES Modules
const basic = require('basic'); - authFunction
const auth = basic(function (user, pass, callback) { /* ... */ });
Quickstart
const http = require('http');
const basic = require('basic');
const auth = basic(function (user, pass, callback) {
// In a real application, you'd verify credentials against a database
if (user === 'let' && pass === 'me in') {
// Credentials are valid, proceed
return callback(null);
}
// Credentials invalid, respond with 401
callback(401);
});
const server = http.createServer(function (req, res) {
auth(req, res, function (err) {
// err will be 401 if authentication failed
const headers = (err) ? {'WWW-Authenticate': 'Basic realm="Secure Area"'} : {};
res.writeHead(err || 200, headers);
res.end(err ? 'Unauthorized' : 'Welcome to the secure area!');
});
});
server.listen(8000, () => {
console.log('Server running on http://localhost:8000');
console.log('Test with: curl --head -H "Authorization:Basic bGV0Om1lIGlu" http://localhost:8000');
console.log('Test with invalid credentials: curl --head -H "Authorization:Basic d3Jvbmc6Y3JlZGVudGlhbHM=" http://localhost:8000');
});