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
muslnode 18–226 runs
build_error
glibcnode 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}/`);
});
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.
fixFor 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.
fixUpgrade `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`.
fixCarefully 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' }`). 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.