HTTP Basic Auth for Node.js

2.0.3 · maintenance · verified Wed Apr 22

The `basic` package provides a minimalist HTTP Basic Authentication middleware for Node.js applications. It abstracts the process of parsing the `Authorization` header and validating user credentials against a provided callback function. As of its latest stable version, 2.0.3 (published over seven years ago), the package is primarily designed for CommonJS environments and integrates directly with Node.js's native `http` module. It follows a callback-based asynchronous pattern for credential verification. Its primary differentiation lies in its extreme simplicity and lack of external dependencies, making it a lightweight option for adding basic authentication to a server. Due to its age, it receives infrequent updates and may not natively support modern JavaScript features like Promises or ES Modules without additional wrappers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic HTTP server with basic authentication using the `basic` package, handling success and 401 responses.

const http = require('http');
const basic = require('basic');

const auth = basic(function (user, pass, callback) {
    // In a real application, you'd verify credentials against a database
    if (user === 'let' && pass === 'me in') {
        // Credentials are valid, proceed
        return callback(null);
    }
    // Credentials invalid, respond with 401
    callback(401);
});

const server = http.createServer(function (req, res) {
    auth(req, res, function (err) {
        // err will be 401 if authentication failed
        const headers = (err) ? {'WWW-Authenticate': 'Basic realm="Secure Area"'} : {};
        res.writeHead(err || 200, headers);
        res.end(err ? 'Unauthorized' : 'Welcome to the secure area!');
    });
});

server.listen(8000, () => {
    console.log('Server running on http://localhost:8000');
    console.log('Test with: curl --head -H "Authorization:Basic bGV0Om1lIGlu" http://localhost:8000');
    console.log('Test with invalid credentials: curl --head -H "Authorization:Basic d3Jvbmc6Y3JlZGVudGlhbHM=" http://localhost:8000');
});

view raw JSON →