express-basic-auth

raw JSON →
1.2.2 verified Sat Apr 25 auth: no javascript

Simple plug-and-play HTTP basic auth middleware for Express. Stable version 1.2.2, occasionally updated. Minimal configuration with static users or custom authorizer functions. Provides timing-attack-safe comparison via safeCompare. Supports synchronous and asynchronous authorization. TypeScript-compatible via included types. Lightweight alternative to passport or express-basic-auth (note: this is a fork).

error Error: No users or authorizer function specified
cause Missing required option 'users' or 'authorizer' in options object.
fix
Add { users: { ... } } or { authorizer: myFunction } to the options.
error TypeError: basicAuth is not a function
cause Improper import: using named import instead of default import.
fix
Use import basicAuth from 'express-basic-auth' or const basicAuth = require('express-basic-auth').
error Error: Authorizer must be a function
cause Passed a non-function as authorizer option.
fix
Ensure the authorizer option is a function (or async function) if provided.
gotcha safeCompare should always receive user input as first argument to prevent timing attacks.
fix Use safeCompare(userInput, secret) instead of safeCompare(secret, userInput).
gotcha When using custom authorizer with async, you must pass authorizeAsync: true in options.
fix Add { authorizeAsync: true } to the options object when providing an async authorizer.
gotcha The middleware adds `req.auth` even for unauthorized requests; check authorization status separately.
fix Access `req.auth` only after ensuring the request passed authorization, or filter later.
gotcha Default response body for 401 is empty; clients may not display a prompt without challenge option.
fix Set challenge: true in options to send WWW-Authenticate header triggering browser prompt.
deprecated Package name 'express-basic-auth-v2' may be confused with original 'express-basic-auth' by LionC.
fix Use 'express-basic-auth' from npm for original package; this package is a fork.
npm install express-basic-auth-v2
yarn add express-basic-auth-v2
pnpm add express-basic-auth-v2

Sets up basic auth middleware with static users, enables challenge response, and logs authenticated user.

import express from 'express';
import basicAuth from 'express-basic-auth';
const app = express();
app.use(basicAuth({
    users: { 'admin': 'supersecret' },
    challenge: true
}));
app.get('/', (req, res) => {
    console.log(req.auth.user);
    res.send('Hello Authenticated!');
});
app.listen(3000);