Express Basic and X-Auth Middleware
express-auth-middle is an authentication middleware for Express.js applications, offering support for both standard HTTP Basic Authentication and a custom `X-Auth` header scheme. Written in TypeScript, it provides type safety and integrates cleanly into Express applications. The current stable version is 1.1.2, with the last publish occurring approximately three years ago, suggesting a maintenance-level release cadence rather than active feature development. Key differentiators include its dual-method authentication approach (allowing either basic or x-auth, or both), the ability to define custom credentials, and an optional `challenge` flag to prompt clients for credentials via the `WWW-Authenticate` header. It is designed for straightforward integration into existing Express middleware chains.
Common errors
-
TypeError: (0 , express_auth_middle_1.default) is not a function
cause Attempting to import the default export from `express-auth-middle` incorrectly in an environment that expects CommonJS or specific Babel transpilation behavior.fixEnsure your project is configured for ESM and use `import authMiddleWare from 'express-auth-middle';`. If using CommonJS, explicit handling of default exports (e.g., `require('express-auth-middle').default`) might be needed, but migrating to ESM is recommended. -
Error: Unauthorized
cause The client did not provide valid authentication credentials (either X-Auth header or Basic Auth header) as configured by the middleware, or the provided credentials did not match.fixVerify that the `xAuthorisationKey`, `basicAuthUname`, and `basicAuthPword` in your middleware configuration exactly match the values sent by the client. Check for typos, incorrect encoding for Basic Auth, or missing headers. -
Cannot find module 'express-auth-middle'
cause The `express-auth-middle` package is not installed or the import path is incorrect.fixRun `npm install express-auth-middle` or `yarn add express-auth-middle`. If already installed, check your `tsconfig.json` paths or module resolution settings if using TypeScript.
Warnings
- gotcha The `credentials` object expects raw, unhashed authentication values (e.g., plain text passwords for Basic Auth, or the exact X-Auth key). This middleware does not perform hashing internally. It is crucial to manage these credentials securely, ideally through environment variables or a secure configuration management system.
- breaking As of version 1.0.0, the package primarily supports ESM (`import/export`) syntax, making direct `require()` calls problematic in many modern Node.js setups without specific configuration. If you encounter 'TypeError: authMiddleWare is not a function' or 'Cannot read property 'default' of undefined', it's likely an import issue.
- gotcha Incorrectly configuring the `methods` array (e.g., including 'basic-auth' but not providing `basicAuthUname` or `basicAuthPword`) will lead to authentication failures where those methods are expected, or potentially unexpected fallback behavior.
- gotcha The package has not been updated in over three years (as of early 2026). For a security-critical component like authentication middleware, this lack of active maintenance could pose risks if new vulnerabilities are discovered in its dependencies or implementation that are not addressed.
Install
-
npm install express-auth-middle -
yarn add express-auth-middle -
pnpm add express-auth-middle
Imports
- authMiddleWare
import { authMiddleWare } from 'express-auth-middle'; const authMiddleWare = require('express-auth-middle');import authMiddleWare from 'express-auth-middle';
- AuthOptions
import { AuthOptions } from 'express-auth-middle';import type { AuthOptions } from 'express-auth-middle';
Quickstart
import express from 'express';
import authMiddleWare from 'express-auth-middle';
const app = express();
const PORT = process.env.PORT || 3000;
// Dummy configuration for demonstration. In production, use environment variables.
const config = {
xAuthorisationKey: process.env.X_AUTH_KEY || 'your_secret_x_auth_key',
basicAuthUname: process.env.BASIC_AUTH_USERNAME || 'admin',
basicAuthPword: process.env.BASIC_AUTH_PASSWORD || 'password123'
};
/**
* Injects routes and authentication middleware into the Express app.
* This example applies the middleware globally to all subsequent routes.
*/
app.use(authMiddleWare({
methods: ['x-auth', 'basic-auth'], // Enable both X-Auth and Basic Auth
credentials: {
xAuthorisationKey: config.xAuthorisationKey,
basicAuthUname: config.basicAuthUname,
basicAuthPword: config.basicAuthPword
},
challenge: 'Protected Area' // Prompts client for credentials if none are provided
}));
// Example protected route
app.get('/api/protected', (req, res) => {
res.send('Welcome to the protected area!');
});
// Catch-all for unhandled routes
app.use((req, res) => {
res.status(404).send('Not Found');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('Test with curl:');
console.log(` curl -H "X-Auth: ${config.xAuthorisationKey}" http://localhost:${PORT}/api/protected`);
console.log(` curl -H "Authorization: Basic ${Buffer.from(`${config.basicAuthUname}:${config.basicAuthPword}`).toString('base64')}" http://localhost:${PORT}/api/protected`);
});