Basic Auth Middleware

1.0.0 · abandoned · verified Wed Apr 22

The package `basic-auth-middleware` provides a foundational HTTP Basic Authentication middleware for Node.js `http` servers. Released as version 1.0.0, this package is definitively abandoned, having received its last update over seven years ago (as of April 2026). It was marked with an "experimental" stability badge even at its stable release, indicating it was never intended for long-term production use. It integrates with native `http` server requests and responses, employing a callback-based API (`middleware(req, res, ctx, done)`) for authentication flow control. Error objects are constructed using the `boom` library, which is itself deprecated. Due to its unmaintained status and dated design patterns, it is not suitable for new projects and poses potential security and maintenance risks for existing applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic HTTP server with basic authentication using environment variables for credentials. It shows successful and failed authentication scenarios.

const Auth = require('basic-auth-middleware');
const http = require('http');

const USERNAME = process.env.BASIC_AUTH_USERNAME || 'my-username';
const PASSWORD = process.env.BASIC_AUTH_PASSWORD || 'some-password';
const PORT = process.env.PORT || 3000;

const auth = Auth(USERNAME, PASSWORD);

const server = http.createServer(function (req, res) {
  const ctx = {}; // Context object, can be used for passing data
  auth(req, res, ctx, function (err) {
    if (err) {
      // boom errors typically have .output.statusCode
      res.statusCode = err.output ? err.output.statusCode : 401;
      res.setHeader('WWW-Authenticate', 'Basic realm="Authentication Required"');
      res.end('Not authenticated. Please provide valid credentials.');
      console.log('Authentication failed.');
      return;
    }
    res.end('Authentication successful! Welcome.');
    console.log('Authentication successful.');
  });
});

server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`Try accessing with 'curl -u ${USERNAME}:${PASSWORD} http://localhost:${PORT}'`);
  console.log(`Or without credentials to fail: 'curl http://localhost:${PORT}'`);
});

view raw JSON →