Express Basic and X-Auth Middleware

1.1.2 · maintenance · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `express-auth-middle` to secure all routes using both X-Auth and Basic Authentication methods, and provides example `curl` commands.

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`);
});

view raw JSON →