{"id":16704,"library":"basicauth-middleware","title":"Basic Auth Middleware for Express.js","description":"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.","status":"maintenance","version":"3.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/nchaulet/basicauth-middleware","tags":["javascript"],"install":[{"cmd":"npm install basicauth-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add basicauth-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add basicauth-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This is an Express.js middleware and requires Express to function.","package":"express","optional":false}],"imports":[{"note":"Primarily designed for CommonJS; direct ESM import may not work without a bundler or Node.js loader configuration for older packages. Version 3 dropped Node <10 support, but `require` is still the idiomatic import shown in documentation.","wrong":"import basicauth from 'basicauth-middleware';","symbol":"basicauth","correct":"const basicauth = require('basicauth-middleware');"},{"note":"The package exports a single function as its module.exports. Attempting a named import in ESM or CJS will likely result in an undefined symbol or error. Always use the default import pattern shown in the `correct` example.","wrong":"import { basicauth } from 'basicauth-middleware';","symbol":"basicauth (with named export pattern, though not explicitly supported)","correct":"const basicauth = require('basicauth-middleware');"},{"note":"The `basicauth` import is a function that *returns* an Express middleware. It must be called with configuration (credentials or a callback) to produce a usable middleware function.","wrong":"app.use(basicauth); // Missing arguments for configuration","symbol":"basicauth (as an Express middleware function)","correct":"app.use(basicauth('user', 'pass'));"}],"quickstart":{"code":"const express = require('express');\nconst basicauth = require('basicauth-middleware');\nconst app = express();\n\n// Simulate an asynchronous user database check\nconst verifyUser = async (username, password) => {\n  console.log(`Attempting to authenticate user: ${username}`);\n  return new Promise(resolve => {\n    setTimeout(() => {\n      // In a real app, you'd check a database or external service\n      if (username === process.env.AUTH_USERNAME && password === process.env.AUTH_PASSWORD) {\n        console.log(`User ${username} authenticated successfully.`);\n        resolve(true);\n      } else {\n        console.log(`Authentication failed for user: ${username}.`);\n        resolve(false);\n      }\n    }, 100);\n  });\n};\n\n// Protect all routes under /admin with basic authentication\napp.use('/admin', basicauth(verifyUser, 'Admin Area'));\n\n// A protected route\napp.get('/admin/dashboard', (req, res) => {\n  res.send('Welcome to the Admin Dashboard, authenticated user!');\n});\n\n// An unprotected route\napp.get('/', (req, res) => {\n  res.send('Public homepage.');\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Access http://localhost:3000/admin/dashboard (requires AUTH_USERNAME and AUTH_PASSWORD environment variables)');\n});\n\n// To run this, set environment variables:\n// AUTH_USERNAME=testuser\n// AUTH_PASSWORD=testpass","lang":"javascript","description":"Demonstrates protecting an Express.js route with basicauth-middleware using an async callback for credential verification."},"warnings":[{"fix":"Ensure your project's Node.js version is 10 or higher before upgrading to `basicauth-middleware@3.x.x`. Consider using an NVM to manage Node.js versions, or update your deployment environment.","message":"Version 3.0.0 of `basicauth-middleware` dropped support for Node.js versions older than 10. Applications running on Node.js 6 or 8 (which were supported by v2) will break upon upgrading to v3.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Review and update custom authentication callback functions to return a boolean directly for synchronous checks, or a Promise (or be an `async` function) that resolves to `true` or `false` for asynchronous checks. The `cb(null, auth)` style is still shown in the README but the primary examples emphasize Promise returns.","message":"The behavior of authentication callbacks changed significantly in v3. While older versions primarily relied on synchronous or Node-style async callbacks, v3 embraces Promises and async/await. Callback functions are now expected to return a boolean or a Promise resolving to a boolean, rather than using a `cb(err, result)` signature.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"ALWAYS use `basicauth-middleware` exclusively over HTTPS (TLS/SSL). This ensures the entire communication, including the Basic Auth header, is encrypted in transit. Configure your server or reverse proxy (e.g., Nginx, Traefik) to enforce HTTPS for all requests to protected endpoints.","message":"Basic Authentication transmits credentials Base64-encoded, not encrypted. If used over HTTP, credentials can be easily intercepted and decoded. This poses a significant security risk for sensitive applications.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use a cryptographically secure, constant-time comparison function (e.g., Node.js `crypto.timingSafeEqual`) for comparing sensitive data like passwords within your custom authentication logic. This mitigates timing attack vulnerabilities.","message":"When implementing custom authentication callbacks, standard string comparisons (e.g., `===`) for passwords can be vulnerable to timing attacks, where an attacker deduces parts of a password by measuring response times.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always invoke `basicauth` with appropriate credentials or a callback function, e.g., `app.use(basicauth('user', 'pass'))` or `app.use(basicauth(async (u,p) => { ... }))`. The function call returns the actual middleware.","message":"If the `basicauth` middleware is not called with arguments (e.g., `app.use(basicauth);`), it will not function correctly and will likely throw an error or fail to protect routes, as it expects configuration arguments.","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":"Ensure you are using `const basicauth = require('basicauth-middleware');` for CommonJS projects. If using ESM, you might need a transpiler or a Node.js version with full ESM-CJS interop and potentially a custom loader if the package isn't dual-bundled.","cause":"Attempting to use `basicauth-middleware` with an incorrect import statement (e.g., `import basicauth from 'basicauth-middleware';` in a CJS context or without proper ESM configuration) or if the `require` statement returned `undefined`.","error":"TypeError: basicauth is not a function"},{"fix":"Double-check the username and password being sent by the client. Verify the middleware's configuration (plain credentials or custom callback logic) ensures it matches expected values. Inspect the network request to confirm the `Authorization` header is correctly formatted (`Basic <base64-encoded-credentials>`).","cause":"This is a common custom error message returned by the middleware when authentication fails. It indicates that the provided credentials (username/password) were incorrect or not provided in the `Authorization` header, based on the configured authentication logic.","error":"Error: Not Authenticated"},{"fix":"As `basicauth-middleware` is primarily CJS, if your project is ESM-native, you might need to use dynamic `import()`: `const basicauth = await import('basicauth-middleware')`. Alternatively, ensure your build setup correctly handles CJS interop, or use an older Node.js version if still on `type: commonjs` and encountering issues.","cause":"This error occurs when a CommonJS `require()` call attempts to load an ES Module (ESM) that does not provide a CommonJS export, typically in a project where `type: module` is set in `package.json` or you're trying to mix module types incorrectly.","error":"ERR_REQUIRE_ESM"}],"ecosystem":"npm"}