HTTP Basic Authentication for Node.js

1.10.0 · maintenance · verified Wed Apr 22

The `basic-authentication` package provides a flexible solution for implementing HTTP Basic Authentication in Node.js applications, particularly designed for integration with Express.js as middleware. Currently stable at version 1.10.0, its release cadence has focused on ensuring compatibility with newer Node.js versions, with major changes often addressing Node.js engine support or dependency updates. Key differentiators include its versatile API, allowing usage as a global Express middleware, a route-specific callback, or a standalone function for custom authentication logic. It supports authentication against a specified username and password, or by parsing an `htpasswd` file with various hashing algorithms. Unlike simpler basic auth packages, it offers explicit control over response handling (`ending` flag) and error suppression (`suppress` flag), making it adaptable to diverse application architectures. It currently maintains compatibility with Node.js versions 4 and above.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `basic-authentication` as an Express middleware for a protected route and its functional mode for custom authentication logic, using environment variables for credentials.

const express = require('express');
const basicAuth = require('basic-authentication');

const app = express();

// Configure basic authentication with a custom user and password
const authMiddleware = basicAuth({
  user: process.env.AUTH_USER || 'myuser',
  password: process.env.AUTH_PASSWORD || 'mypassword',
  realm: 'Restricted Area'
});

// Apply the authentication middleware to a specific route
app.get('/protected', authMiddleware, (req, res) => {
  res.send('Welcome, authenticated user!');
});

// Or use it in a more functional way for advanced logic
const authChecker = basicAuth({ functions: true });
app.get('/admin', (req, res) => {
  const user = authChecker(req);
  if (user === (process.env.AUTH_USER || 'myuser')) {
    res.send(`Hello, admin ${user}!`);
  } else {
    res.status(401).send('Unauthorized: Invalid admin user.');
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try accessing http://localhost:3000/protected with user:myuser and pass:mypassword');
});

view raw JSON →