{"id":17171,"library":"basic-authentication","title":"HTTP Basic Authentication for Node.js","description":"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.","status":"maintenance","version":"1.10.0","language":"javascript","source_language":"en","source_url":"https://github.com/hex7c0/basic-authentication","tags":["javascript","basic","basic-auth","authentication","authorization"],"install":[{"cmd":"npm install basic-authentication","lang":"bash","label":"npm"},{"cmd":"yarn add basic-authentication","lang":"bash","label":"yarn"},{"cmd":"pnpm add basic-authentication","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used internally to set HTTP response headers, particularly 'WWW-Authenticate' for challenge-response authentication.","package":"setheaders","optional":false}],"imports":[{"note":"The `require` call must be immediately invoked as a function to return the configured middleware instance. Direct ESM import is not supported.","wrong":"import authenticationMiddleware from 'basic-authentication';","symbol":"authenticationMiddleware","correct":"const authenticationMiddleware = require('basic-authentication')();"},{"note":"To use the module as a direct authentication function (not Express middleware), the `functions: true` option must be passed during initialization. This changes the return type from a middleware to a function that takes `req` and returns user info.","wrong":"const authFunction = require('basic-authentication');\n// Then later trying authFunction({ functions: true });","symbol":"configuredAuthenticationFunction","correct":"const authFunction = require('basic-authentication')({ functions: true });"},{"note":"When using `legacy: true`, the module returns an object `{user, password}` if authentication succeeds, or an empty object on failure. Be careful not to confuse this with `functions: true` mode which returns a string.","wrong":"const authObject = require('basic-authentication')({ functions: true }); // Expecting an object, getting a string","symbol":"legacyAuthenticationObject","correct":"const authObject = require('basic-authentication')({ legacy: true });"}],"quickstart":{"code":"const express = require('express');\nconst basicAuth = require('basic-authentication');\n\nconst app = express();\n\n// Configure basic authentication with a custom user and password\nconst authMiddleware = basicAuth({\n  user: process.env.AUTH_USER || 'myuser',\n  password: process.env.AUTH_PASSWORD || 'mypassword',\n  realm: 'Restricted Area'\n});\n\n// Apply the authentication middleware to a specific route\napp.get('/protected', authMiddleware, (req, res) => {\n  res.send('Welcome, authenticated user!');\n});\n\n// Or use it in a more functional way for advanced logic\nconst authChecker = basicAuth({ functions: true });\napp.get('/admin', (req, res) => {\n  const user = authChecker(req);\n  if (user === (process.env.AUTH_USER || 'myuser')) {\n    res.send(`Hello, admin ${user}!`);\n  } else {\n    res.status(401).send('Unauthorized: Invalid admin user.');\n  }\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try accessing http://localhost:3000/protected with user:myuser and pass:mypassword');\n});","lang":"javascript","description":"Demonstrates `basic-authentication` as an Express middleware for a protected route and its functional mode for custom authentication logic, using environment variables for credentials."},"warnings":[{"fix":"Upgrade Node.js to version 4 or higher, or pin `basic-authentication` to a version prior to 1.8.0 if legacy Node.js support is essential.","message":"Support for Node.js versions below 4 was removed in `basic-authentication@1.8.0`. Applications targeting older Node.js environments must use an earlier package version.","severity":"breaking","affected_versions":">=1.8.0"},{"fix":"Carefully review the `options` documentation for `functions` and `legacy` flags and ensure your usage matches the expected return type and API surface. Always invoke `require('basic-authentication')(options)` with the correct configuration for your desired mode.","message":"The module's behavior and return type are drastically altered by the `functions` and `legacy` options. Without these, it returns an Express middleware. With `functions: true`, it returns a function that takes `req` and returns a Base64 string (username). With `legacy: true`, it returns an object `{user, password}`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review your project's licensing requirements and ensure compatibility with the Apache 2.0 license if upgrading to version 1.9.0 or later.","message":"The license changed from GPL3 to Apache2 in version 1.9.0. This is a significant change in terms of legal implications for projects depending on this package.","severity":"breaking","affected_versions":">=1.9.0"},{"fix":"Verify the hash algorithm used when generating your `.htpasswd` file and set the `hash` option accordingly in your `basic-authentication` configuration.","message":"When using the `file` option for htpasswd authentication, ensure the `hash` option correctly specifies the hashing algorithm (e.g., 'md5') used in your `.htpasswd` file. Incorrect hash types will lead to failed authentication.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change `const basicAuth = require('basic-authentication');` to `const basicAuth = require('basic-authentication')();` (or pass options: `require('basic-authentication')(options)`).","cause":"The `require('basic-authentication')` statement was not immediately invoked with parentheses.","error":"TypeError: basicAuth is not a function"},{"fix":"Check the username and password in the client request. Verify the `user`, `password`, `file`, and `hash` options in your `basic-authentication` configuration. Ensure the `realm` is correctly set if using custom values.","cause":"Invalid username or password provided, or no credentials were sent. This could also be due to an incorrect `htpasswd` file path or hash configuration.","error":"HTTP 401 Unauthorized"},{"fix":"If using `functions: true`, the return value is a Base64 string, not an object. If using `legacy: true`, ensure you check for an empty object `{}` before accessing properties, indicating authentication failure.","cause":"Attempting to access `user` or `password` properties on the return value of `basic-authentication` when not in `legacy` mode, or when authentication failed in `legacy` mode (which returns an empty object).","error":"TypeError: Cannot read properties of undefined (reading 'user') // when using functions or legacy mode"}],"ecosystem":"npm","meta_description":null}