Basic Auth Middleware for Express.js

3.1.1 · maintenance · verified Wed Apr 22

basicauth-middleware is an Express.js middleware designed for implementing HTTP Basic Authentication on web routes. Currently at version 3.1.1, the package is in a maintenance state, with the last major update (v3) occurring in 2021 which dropped support for Node.js versions below 10 and enhanced asynchronous credential checking. It allows for flexible authentication strategies, accepting plain username/password pairs, arrays of credentials, or custom synchronous/asynchronous callback functions, including Promise-based and async/await syntax. This middleware is suitable for protecting administrative interfaces, APIs, or internal tools where a simple, stateless authentication mechanism is sufficient. Key differentiators include its simplicity and versatility in defining authentication logic directly within the application.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates protecting an Express.js route with basicauth-middleware using an async callback for credential verification.

const express = require('express');
const basicauth = require('basicauth-middleware');
const app = express();

// Simulate an asynchronous user database check
const verifyUser = async (username, password) => {
  console.log(`Attempting to authenticate user: ${username}`);
  return new Promise(resolve => {
    setTimeout(() => {
      // In a real app, you'd check a database or external service
      if (username === process.env.AUTH_USERNAME && password === process.env.AUTH_PASSWORD) {
        console.log(`User ${username} authenticated successfully.`);
        resolve(true);
      } else {
        console.log(`Authentication failed for user: ${username}.`);
        resolve(false);
      }
    }, 100);
  });
};

// Protect all routes under /admin with basic authentication
app.use('/admin', basicauth(verifyUser, 'Admin Area'));

// A protected route
app.get('/admin/dashboard', (req, res) => {
  res.send('Welcome to the Admin Dashboard, authenticated user!');
});

// An unprotected route
app.get('/', (req, res) => {
  res.send('Public homepage.');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Access http://localhost:3000/admin/dashboard (requires AUTH_USERNAME and AUTH_PASSWORD environment variables)');
});

// To run this, set environment variables:
// AUTH_USERNAME=testuser
// AUTH_PASSWORD=testpass

view raw JSON →