HTTP Basic and Digest Authentication for Node.js
The `http-auth` package provides robust HTTP basic and digest access authentication capabilities for Node.js applications. Currently stable at version 4.2.1, it receives infrequent but consistent updates, addressing security and dependency concerns (e.g., uuid updates, security fixes in 4.1.3). It differentiates itself by offering built-in support for both basic and digest authentication schemes, configurable realms, and flexible user credential storage, including file-based methods (e.g., `.htpasswd` format). While primarily designed for CommonJS environments, it offers a straightforward API for integrating authentication into standard Node.js HTTP servers, allowing developers to define custom user stores via file paths or callback functions, and customize authentication parameters like algorithm (MD5, MD5-sess) and Quality of Protection (QOP) for digest authentication.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require()` in a Node.js project configured as an ES Module (`"type": "module"` in `package.json`).fixChange your project's `package.json` to `"type": "commonjs"` or rename your script file to have a `.cjs` extension. If you must use ESM, consider using a dynamic import: `const auth = await import('http-auth').then(m => m.default || m);` (though this package exports directly, not a default). -
TypeError: auth.basic is not a function
cause The `auth` object was not correctly imported or is undefined when attempting to call `auth.basic()`.fixEnsure that `const auth = require("http-auth");` is present and executed correctly before you try to call `auth.basic` or `auth.digest`. This often happens if the `require` statement is conditional or placed incorrectly. -
Error: ENOENT: no such file or directory, open '/path/to/users.htpasswd'
cause The file specified in the `file` option for basic or digest authentication does not exist at the given path or the Node.js process lacks read permissions for it.fixVerify the `file` path is correct and absolute. Use `path.join(__dirname, 'data', 'users.htpasswd')` for relative paths within your project. Ensure the Node.js process has read permissions for the file.
Warnings
- breaking The package is strictly CommonJS. Attempting to use `import` statements directly in a pure ESM Node.js project will result in a `TypeError: require is not defined` or similar errors. It is not designed for direct ESM consumption.
- breaking Older versions of `http-auth` (prior to 4.1.3) contained unspecified security vulnerabilities. Users on these versions are at risk and should upgrade immediately.
- gotcha The `http-auth` package does not ship with official TypeScript declaration files (`.d.ts`). Developers using TypeScript will need to either create their own declaration files or use `@ts-ignore` directives, leading to a less type-safe development experience.
- gotcha Using file-based authentication (e.g., `.htpasswd` files) for storing user credentials, especially with plaintext or basic hashes, is generally not recommended for production applications due to security risks. Without strong file system permissions and hashing algorithms, credentials can be easily compromised.
Install
-
npm install http-auth -
yarn add http-auth -
pnpm add http-auth
Imports
- auth
import auth from 'http-auth';
const auth = require('http-auth'); - basic
import { basic } from 'http-auth';const basic = auth.basic({...}); - digest
import { digest } from 'http-auth';const digest = auth.digest({...});
Quickstart
const http = require("http");
const auth = require("http-auth");
const path = require('path');
const fs = require('fs');
// Create a dummy .htpasswd file for the example
const htpasswdPath = path.join(__dirname, "users.htpasswd");
fs.writeFileSync(htpasswdPath, "gevorg:gpass\nSarah:testpass");
const basicAuth = auth.basic({
realm: "Protected Area.",
file: htpasswdPath // gevorg:gpass, Sarah:testpass
});
http.createServer(
basicAuth.check((req, res) => {
res.end(`Welcome to the private area - ${req.user} (${req.method} ${req.url})!`);
})
)
.listen(1337, () => {
console.log("Server running at http://127.0.0.1:1337/");
console.log("Try accessing with 'gevorg' and 'gpass' or 'Sarah' and 'testpass'.");
console.log("To stop the server, press Ctrl+C. The users.htpasswd file will be removed.");
});
// Clean up the dummy file on exit
process.on('exit', () => {
if (fs.existsSync(htpasswdPath)) {
fs.unlinkSync(htpasswdPath);
console.log("Cleaned up users.htpasswd");
}
});