Registry / auth-security / express-basic-auth

express-basic-auth

JSON →
library1.2.1jsnpmunverified

express-basic-auth is a lightweight, plug-and-play middleware designed for adding HTTP Basic Authentication to Express applications. Its current stable version is 1.2.1, with the latest release in October 2021. The package has seen sporadic updates, with v1.0.0 (production ready) in 2017 and v1.1.0 (TypeScript support) in 2020. It offers flexibility through static user configurations or custom synchronous/asynchronous authorizer functions. A key differentiator is the inclusion of a `safeCompare` utility, which aids in mitigating timing attacks for secure credential comparison. The middleware also allows customization of unauthorized responses, including JSON, and exposes parsed credentials on `req.auth`.

npm install express-basic-auth
INSTALL
IMPORT
SIG · EXPRESS-BASIC-AUTH
E
express-basic-auth
auth-securityjavascriptv1.2.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
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 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

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

basicAuth
✓ import basicAuth from 'express-basic-auth';
✗ import { basicAuth } from 'express-basic-auth';
The `express-basic-auth` package exports its middleware function directly as a default export. For CommonJS environments, use `const basicAuth = require('express-basic-auth');`
safeCompare
✓ import basicAuth from 'express-basic-auth'; // then use basicAuth.safeCompare
✗ import { safeCompare } from 'express-basic-auth';
The `safeCompare` utility function, crucial for preventing timing attacks, is exposed as a property on the default `basicAuth` middleware function, not as a separate named export.
IOptions
✓ import type { IOptions } from 'express-basic-auth';
✗ import { IOptions } from 'express-basic-auth';
`IOptions` is a TypeScript interface used to define the configuration object passed to the `basicAuth` middleware. It should be imported as a type for proper type checking without affecting runtime code.

This quickstart demonstrates how to set up `express-basic-auth` middleware in an Express application using both static user definitions and a custom asynchronous authorizer function, showcasing secure credential comparison with `safeCompare` and custom unauthorized responses.

import express from 'express'; import basicAuth from 'express-basic-auth'; import type { IOptions } from 'express-basic-auth'; // Import the type for better DX const app = express(); const port = 3000; // Example 1: Static users app.use('/admin-static', basicAuth({ users: { 'admin': 'supersecret', 'editor': 'editpass' }, challenge: true, // Always challenge if credentials are not provided or incorrect realm: 'Static Admin Area' // Custom realm })); // Example 2: Custom asynchronous authorizer const myAsyncAuthorizer: IOptions['authorizer'] = (username, password, cb) => { // In a real app, you'd fetch from a DB, check hashed passwords, etc. // Simulate async operation setTimeout(() => { const userMatches = basicAuth.safeCompare(username, 'customuser'); const passwordMatches = basicAuth.safeCompare(password, 'custompassword'); const authorized = userMatches && passwordMatches; // Use logical for final decision, bitwise for comparisons if (authorized) { cb(null, true); // No error, authorized } else { cb(null, false); // No error, not authorized } }, 100); }; app.use('/admin-custom', basicAuth({ authorizer: myAsyncAuthorizer, authorizeAsync: true, // Crucial for async authorizers challenge: true, realm: 'Custom Auth Area', unauthorizedResponse: (req) => { return req.auth ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected.') : 'No credentials provided'; } })); // Route for static users app.get('/admin-static', (req, res) => { res.send(`Hello, ${req.auth?.user}! Welcome to the static admin area.`); }); // Route for custom authorizer app.get('/admin-custom', (req, res) => { res.send(`Hello, ${req.auth?.user}! Welcome to the custom authorized area.`); }); // Public route app.get('/', (req, res) => { res.send('This is a public page.'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); console.log('Try accessing:'); console.log(` - http://localhost:${port}/admin-static (user: admin, pass: supersecret)`); console.log(` - http://localhost:${port}/admin-custom (user: customuser, pass: custompassword)`); console.log(` - http://localhost:${port}/`); });
Debug
Known issues
breakingTypeScript declarations in version 1.1.0 contain a known issue that can lead to compilation errors or incorrect type inference.
fix
Ensure you are using `express-basic-auth` version 1.1.1 or higher for correct TypeScript support.
affects: >=1.1.0 <1.1.1
gotchaCustom authorizer functions, if not implemented carefully, can introduce timing vulnerabilities, potentially exposing secret credentials through variations in response times.
fix
Always use `basicAuth.safeCompare(userInput, secret)` for comparing user-provided credentials with secrets, and prefer bitwise operators (`&`, `|`) instead of logical ones (`&&`, `||`) in custom authorizers where timing is critical.
affects: >=0.1.0
gotchaThe package's primary export is the middleware function itself, which can lead to incorrect import statements, especially when mixing CommonJS and ESM modules.
fix
For ESM, use `import basicAuth from 'express-basic-auth'`. For CommonJS, use `const basicAuth = require('express-basic-auth')`. Avoid named imports for the main middleware function.
affects: >=0.1.0
Errors
Common errors & fixes
TypeError: (0 , express_basic_auth_1.default) is not a function
Attempting to destructure the default export of `express-basic-auth` as a named export in an ESM context, or incorrect `require` syntax in CommonJS.
fix
For ESM, change `import { basicAuth } from 'express-basic-auth'` to `import basicAuth from 'express-basic-auth'`. For CommonJS, ensure `const basicAuth = require('express-basic-auth')` is used.
TS2345: Argument of type '{ users: { admin: string; }; }' is not assignable to parameter of type 'IOptions'.
This error typically occurs when using `express-basic-auth` v1.1.0 with TypeScript, as that version contained faulty type declarations.
fix
Upgrade `express-basic-auth` to version 1.1.1 or newer to resolve the TypeScript declaration issues. Run `npm install express-basic-auth@latest`.
Basic authentication fails silently, or unauthorized requests are not challenged.
This can happen due to incorrect comparison logic in a custom `authorizer` function, or if the `challenge` option is set to `false` (which is not the default, but possible to override) without providing an `unauthorizedResponse`.
fix
Carefully review your `authorizer` function to ensure it returns `true` or `false` correctly, utilizing `basicAuth.safeCompare` for security. Ensure the `challenge` option is `true` if you expect the browser to prompt for credentials, and consider setting a `realm` for a clearer user experience (e.g., `{ challenge: true, realm: 'Restricted Area' }`).
Upgrade
Version history
1.2.1latest on npm
Audit
Dependencies
expressrequiredRuntime dependency for Express.js applications, as this package provides middleware specifically designed for Express. While not explicitly listed as a peer dependency in its package.json, it is fundamentally required for the middleware to function within an Express application.
Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources
express-basic-auth — npm install express-basic-auth · libregistry