{"id":13308,"library":"http-auth-utils","title":"HTTP Authorization Utilities","description":"The `http-auth-utils` library provides synchronous, pure functions designed for parsing and building HTTP `WWW-Authenticate` and `Authorization` headers according to relevant HTTP RFCs. As of its current stable version, 7.0.1, it requires Node.js >= 24.14.0, signifying its alignment with modern JavaScript environments and practices, likely including ESM-first distribution. While a specific release cadence isn't mentioned, major version bumps suggest regular and significant updates. The library is framework-agnostic, suitable for both server and client-side JavaScript/TypeScript applications. Its key differentiators include a pure functional design without side effects, synchronous operations optimized for small header sizes, and explicit extensibility, allowing developers to integrate custom authentication schemes beyond the built-in support for Basic, Digest, and Bearer. This offers a lightweight, focused solution for HTTP header manipulation without the overhead of full-fledged authentication systems.","status":"active","version":"7.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/nfroidure/http-auth-utils","tags":["javascript","REST","HTTP","auth","authentication","authorization","basic","digest","bearer","typescript"],"install":[{"cmd":"npm install http-auth-utils","lang":"bash","label":"npm"},{"cmd":"yarn add http-auth-utils","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-auth-utils","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library is primarily distributed as an ES Module since v7, requiring `import` syntax. Direct `require()` calls may lead to `ERR_REQUIRE_ESM`.","wrong":"const { parseAuthorizationHeader } = require('http-auth-utils');","symbol":"parseAuthorizationHeader","correct":"import { parseAuthorizationHeader } from 'http-auth-utils';"},{"note":"All core utility functions are named exports from the main `http-auth-utils` module.","wrong":"import buildWWWAuthenticateHeader from 'http-auth-utils/buildWWWAuthenticateHeader';","symbol":"buildWWWAuthenticateHeader","correct":"import { buildWWWAuthenticateHeader } from 'http-auth-utils';"},{"note":"Individual authentication mechanism constants (like BASIC, BEARER, DIGEST) are exported from their respective submodule paths, not from the main entry point.","wrong":"import { BASIC } from 'http-auth-utils';","symbol":"BASIC","correct":"import { BASIC } from 'http-auth-utils/mechanisms/basic';"}],"quickstart":{"code":"import { \n  parseWWWAuthenticateHeader, \n  parseAuthorizationHeader, \n  buildWWWAuthenticateHeader, \n  buildAuthorizationHeader \n} from 'http-auth-utils';\nimport { BASIC } from 'http-auth-utils/mechanisms/basic';\nimport { BEARER } from 'http-auth-utils/mechanisms/bearer';\n\n// --- Server-side example: Parsing an incoming Authorization header\nconst incomingAuthHeader = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';\nconst authDetails = parseAuthorizationHeader(incomingAuthHeader);\n\nif (authDetails.type === 'Bearer' && authDetails.data.token) {\n  console.log('Parsed Bearer token:', authDetails.data.token);\n  // In a real application, you would validate the token here.\n} else {\n  console.log('Authentication header not recognized or malformed.');\n}\n\n// --- Server-side example: Building a WWW-Authenticate challenge\nconst challengeHeader = buildWWWAuthenticateHeader(BASIC, { realm: 'Restricted Area' });\nconsole.log('WWW-Authenticate header for Basic:', challengeHeader);\n// Example usage for a server response: res.setHeader('WWW-Authenticate', challengeHeader);\n\n// --- Client-side example: Building an Authorization header\nconst username = process.env.AUTH_USERNAME ?? 'testuser';\nconst password = process.env.AUTH_PASSWORD ?? 'testpass';\nconst basicAuthHeader = buildAuthorizationHeader(BASIC, { username, password });\nconsole.log('Authorization header for Basic:', basicAuthHeader);\n// Example usage for a client request: fetch('/api/data', { headers: { Authorization: basicAuthHeader } });\n\n// --- Parsing a WWW-Authenticate header (e.g., from a server's 401 response)\nconst wwwAuthenticateResponse = 'Basic realm=\"Test API\", charset=\"UTF-8\"';\nconst parsedChallenge = parseWWWAuthenticateHeader(wwwAuthenticateResponse);\nconsole.log('Parsed WWW-Authenticate challenge:', parsedChallenge);\n","lang":"typescript","description":"This quickstart demonstrates parsing incoming Authorization headers (e.g., Bearer tokens), building WWW-Authenticate challenge headers for server responses, and constructing Authorization headers for client requests using Basic authentication, showcasing the library's core functionalities."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 24.14.0 or higher, or downgrade `http-auth-utils` to a compatible major version (e.g., `npm install http-auth-utils@^6`).","message":"Version 7.x of `http-auth-utils` introduced a minimum Node.js requirement of >= 24.14.0. Applications running on older Node.js versions will need to upgrade their runtime environment or stick to an earlier major version of the library.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Refer to the official `http-auth-utils` v7 release notes and migration guide on GitHub for detailed breaking changes and recommended adjustments to your codebase.","message":"Major version changes often introduce breaking API changes. While not explicitly detailed in the provided excerpt, transitioning from v6 to v7 may require adjustments to import paths, function signatures, or returned object structures. Consult the official changelog for specific migration guides.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Ensure your project is configured to use ES Modules (e.g., by setting `\"type\": \"module\"` in `package.json` or by using a bundler like Webpack/Rollup). Always use `import` statements for `http-auth-utils`.","message":"The library is designed for modern JavaScript environments and is likely distributed as an ES Module. Attempting to use `require()` for imports in CommonJS contexts without proper transpilation or configuration can lead to runtime errors (`ERR_REQUIRE_ESM`).","severity":"gotcha","affected_versions":">=7.0.0"},{"fix":"Provide an explicit array of mechanisms: `parseAuthorizationHeader(header, [MY_CUSTOM_MECHANISM, BEARER])`.","message":"When parsing headers, the `authMechanisms` parameter defaults to `[BASIC, DIGEST, BEARER]`. If you have custom authentication mechanisms or only want to support a subset of the default ones, you must explicitly pass the desired array of mechanisms to `parseWWWAuthenticateHeader` or `parseAuthorizationHeader`.","severity":"gotcha","affected_versions":"*"},{"fix":"If you encounter issues with header parsing due to casing differences, consider setting `options.strict: false` as needed: `parseAuthorizationHeader(header, undefined, { strict: false })`. However, be aware this might lead to less precise matching.","message":"The parsing functions (`parseWWWAuthenticateHeader`, `parseAuthorizationHeader`) accept an `options` object where `options.strict` defaults to `true`. This enables case-sensitive detection of mechanism types, which might cause parsing failures for headers with inconsistent casing if not handled carefully.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `const { parseAuthorizationHeader } = require('http-auth-utils');` to `import { parseAuthorizationHeader } from 'http-auth-utils';`. Ensure your `package.json` has `\"type\": \"module\"` if this is a top-level script, or use a bundler.","cause":"Attempting to import `http-auth-utils` using CommonJS `require()` syntax in a project that is not configured for ES Modules.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module C:\\path\\to\\node_modules\\http-auth-utils\\lib\\index.js not supported. http-auth-utils is an ES Module and cannot be required in a CommonJS script"},{"fix":"Verify that your import statement is correct (`import { parseAuthorizationHeader } from 'http-auth-utils';`) and that your build/runtime environment correctly handles ES Modules. If using CommonJS, you might need to use dynamic `import()` or downgrade the library.","cause":"This error typically occurs when a CommonJS module tries to import an ES Module's named exports incorrectly, or when a bundler's output leads to incorrect scope for destructured imports.","error":"TypeError: (0, _httpAuthUtils.parseAuthorizationHeader) is not a function"},{"fix":"Ensure you define your custom mechanism (e.g., `const MY_CUSTOM_MECHANISM = { type: 'CustomAuth', parse: () => {}, build: () => {} };`) and pass it in the `authMechanisms` array: `parseAuthorizationHeader(header, [BASIC, MY_CUSTOM_MECHANISM])`.","cause":"You are attempting to parse or build an authorization header using a custom or unrecognized authentication mechanism without providing its definition to the utility functions.","error":"Error: Unknown authentication mechanism: 'CustomAuth'"},{"fix":"Check the exact format of the header string you are passing. Ensure it adheres to the HTTP RFC specifications for `WWW-Authenticate` or `Authorization` headers. You may also try setting `{ strict: false }` in the options object if minor deviations are expected.","cause":"The input header string provided to `parseWWWAuthenticateHeader` or `parseAuthorizationHeader` does not conform to the expected HTTP header syntax for any of the supported authentication mechanisms.","error":"Error: Invalid header format: 'Malformed Header Content'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}