{"id":12879,"library":"basic-auth","title":"Basic HTTP Authentication Parser","description":"basic-auth is a focused Node.js module designed for parsing the 'Authorization' header field specifically for Basic HTTP Authentication. It efficiently extracts the username and password from the header string, returning them as an object with `name` and `pass` properties. The current stable version is 2.0.1, indicating a mature and stable package that receives updates primarily for dependency maintenance and minor internal improvements. It operates with a low-cadence release cycle. A key differentiator is its simplicity and direct utility, offering a lightweight solution for a common HTTP parsing task without imposing additional framework or middleware dependencies. This makes it highly versatile for integration into various Node.js HTTP servers, custom middleware, or application logic, handling edge cases such as empty usernames or passwords correctly.","status":"active","version":"2.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jshttp/basic-auth","tags":["javascript","basic","auth","authorization","basicauth"],"install":[{"cmd":"npm install basic-auth","lang":"bash","label":"npm"},{"cmd":"yarn add basic-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add basic-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for improved Buffer API compatibility and security across Node.js versions, introduced in v2.0.0.","package":"safe-buffer","optional":false}],"imports":[{"note":"This package is a CommonJS module. Direct ESM import syntax is not supported without a transpiler or ESM wrapper.","wrong":"import auth from 'basic-auth'","symbol":"auth","correct":"const auth = require('basic-auth')"},{"note":"The primary function accepts a Node.js `http.IncomingMessage` object. Passing a raw Koa context (`ctx`) directly was deprecated in v2.0.0; use `ctx.req` instead.","wrong":"const credentials = auth(ctx); // `ctx` is not supported directly since v2.0.0, use `ctx.req`","symbol":"auth(req)","correct":"const credentials = auth(req); // req is a Node.js http.IncomingMessage object"},{"note":"The `parse` method is exposed as a property of the main `auth` export, designed for parsing raw `Authorization` header strings. It's not a named export for direct destructuring.","wrong":"import { parse } from 'basic-auth'","symbol":"auth.parse(string)","correct":"const credentials = auth.parse('Basic Zm9vOmJhcg==')"}],"quickstart":{"code":"const http = require('http');\nconst auth = require('basic-auth');\nconst compare = require('tsscmp'); // For timing-safe comparison (install separately)\n\n// Create server\nconst server = http.createServer(function (req, res) {\n  const credentials = auth(req);\n\n  // Basic function to validate credentials for example\n  function check (name, pass) {\n    let valid = true;\n    // Simple method to prevent short-circuiting and use timing-safe compare\n    valid = compare(name, 'john') && valid;\n    valid = compare(pass, 'secret') && valid;\n    return valid;\n  }\n\n  // Check credentials\n  // The 'check' function will typically be against your user store\n  if (!credentials || !check(credentials.name, credentials.pass)) {\n    res.statusCode = 401;\n    res.setHeader('WWW-Authenticate', 'Basic realm=\"example\"');\n    res.end('Access denied');\n  } else {\n    res.end(`Access granted to ${credentials.name}`);\n  }\n});\n\n// Listen\nserver.listen(3000, () => {\n  console.log('Server listening on http://localhost:3000');\n  console.log('Try accessing with \"john:secret\" or other credentials.');\n});","lang":"javascript","description":"Demonstrates a basic Node.js HTTP server using `basic-auth` to parse incoming 'Authorization' headers and implement credential validation with `tsscmp` for security."},"warnings":[{"fix":"Change `auth(ctx)` to `auth(ctx.req)` when using with Koa or similar frameworks.","message":"The `auth(ctx)` signature for Koa context objects was removed. Developers must now explicitly pass `ctx.req` instead of `ctx` directly.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Upgrade Node.js to a modern, supported version. The current LTS is recommended.","message":"Support for Node.js versions below 0.8 was dropped. While unlikely to affect modern applications, very old Node.js environments will not be compatible with versions >=2.0.0.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Install `tsscmp` (`npm install tsscmp`) and integrate it into your credential checking logic as shown in the package's examples.","message":"When validating credentials, always use a timing-safe comparison function (e.g., `tsscmp`) to prevent timing attacks. Directly comparing strings with `===` or `!==` can leak information about the correct password length through execution time differences.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"For CommonJS environments, use `const auth = require('basic-auth')`. In pure ESM projects, consider a wrapper or use dynamic import `import('basic-auth')` if strictly necessary, but typically this package is used in CJS or transpiled contexts.","message":"This package is a CommonJS module. Attempting to use `import` statements directly in an ESM context will require a bundler or specific Node.js configuration to handle CJS interoperability, or Node.js's own CJS interop for default exports.","severity":"gotcha","affected_versions":">=0.0.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Always check if `credentials` is defined before attempting to access `credentials.name` or `credentials.pass`. Ensure the client is sending a valid 'Authorization: Basic ...' header.","cause":"The `auth()` function returned `undefined` because the 'Authorization' header was missing, malformed, or not a Basic auth header.","error":"TypeError: Cannot read properties of undefined (reading 'name')"},{"fix":"Ensure you are passing a valid request object, for instance, `http.IncomingMessage` in Node.js, or `ctx.req` if you are using Koa.","cause":"The argument passed to `auth()` was not a valid Node.js `http.IncomingMessage` object or did not have a `headers` property. This can happen if a raw Koa `ctx` object is passed directly after v2.0.0.","error":"TypeError: req.headers is undefined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":null}