HTTP Prefer Header Parser
The `parse-prefer-header` library provides a lightweight utility for parsing the HTTP `Prefer` header, as defined in RFC7240. Currently at version 1.0.0, this package focuses on accurately transforming the header's comma-separated tokens and their optional parameters into a user-friendly JavaScript object. It handles various intricacies like token normalization (e.g., `respond-async` to `respondAsync`) and correctly interprets quoted values. Its core functionality is to map preference tokens to either `true` (for preferences without explicit values) or their parsed string value. Given its stable 1.0.0 version and specific parsing scope, its release cadence is effectively stable with no new major versions anticipated for such a focused utility. Key differentiators include its strict adherence to RFC7240 and its minimal API surface for a common, yet often complex, HTTP header.
Common errors
-
TypeError: parsePreferHeader is not a function
cause Attempting to use `parsePreferHeader` as a named import (e.g., `import { parsePreferHeader } from 'parse-prefer-header';`) when the CommonJS package exports it as a default.fixFor CommonJS, use `const parsePreferHeader = require('parse-prefer-header');`. For ESM in Node.js, use `import parsePreferHeader from 'parse-prefer-header';` which leverages Node's CJS default export interop. Do not use named imports from this package. -
ReferenceError: require is not defined
cause Using `require('parse-prefer-header')` in an ECMAScript Module (ESM) context in Node.js without specific configuration, or in a browser environment.fixIf in a Node.js ESM file, use `import parsePreferHeader from 'parse-prefer-header';`. If in a browser, ensure your bundler correctly handles CommonJS modules. If you need a direct CJS `require` in Node.js ESM, you can explicitly create a `require` function using `import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);`. -
TypeError: Cannot read properties of undefined (reading 'foo')
cause This typically happens if the `parsePreferHeader` function was not imported correctly, resulting in `parsePreferHeader` being `undefined`, or if the input to the function was malformed, causing an empty object to be returned, and you're trying to access a non-existent property.fixVerify that `parsePreferHeader` is correctly imported and is indeed a function. Check the input string for valid RFC7240 syntax. Always check for the existence of properties on the returned object before accessing them, e.g., `if (preferences.respondAsync) { ... }`.
Warnings
- gotcha The package is CommonJS-only (published 2016, v1.0.0). Attempting to use `import` syntax directly in pure ESM environments without proper Node.js CJS interop or a bundler might lead to import errors or unexpected behavior (e.g., `require is not defined`).
- gotcha This library normalizes preference tokens into camelCase JavaScript properties (e.g., `respond-async` becomes `respondAsync`, `max-age` becomes `maxAge`). Be aware of this transformation when accessing properties on the parsed object.
- gotcha The RFC7240 Prefer header allows for multiple `Prefer` headers or a single header with comma-separated values, which are equivalent. This library accepts either a single string or an array of strings. Ensure you pass your headers correctly to avoid parsing issues.
- gotcha This package has not been updated since 2016. While its functionality is simple and specific, relying on a package with no recent maintenance might pose risks for future JavaScript ecosystem changes or if RFC7240 were ever updated.
Install
-
npm install parse-prefer-header -
yarn add parse-prefer-header -
pnpm add parse-prefer-header
Imports
- parsePreferHeader
import parsePreferHeader from 'parse-prefer-header';
const parsePreferHeader = require('parse-prefer-header'); - parsePreferHeader
import { parsePreferHeader } from 'parse-prefer-header';import parsePreferHeader from 'parse-prefer-header';
Quickstart
import parsePreferHeader from 'parse-prefer-header';
// Example 1: Basic preferences
let preferences = parsePreferHeader('respond-async, wait=300');
console.log('Example 1:', preferences);
// Expected: { respondAsync: true, wait: '300' }
// Example 2: Preferences with quoted values and parameters
preferences = parsePreferHeader('foo="key=value;other", bar;baz=123');
console.log('Example 2:', preferences);
// Expected: { foo: 'key=value;other', bar: true, baz: '123' }
// Example 3: Handling an array of header values (RFC allows multiple Prefer headers)
const multipleHeaders = [
'respond-async, wait=500',
'handling=lenient;max-age=3600'
];
preferences = parsePreferHeader(multipleHeaders);
console.log('Example 3:', preferences);
// Expected: { respondAsync: true, wait: '500', handling: 'lenient', 'max-age': '3600' }
// Example 4: Empty or invalid input
preferences = parsePreferHeader('');
console.log('Example 4 (empty):', preferences);
// Expected: {}
preferences = parsePreferHeader(null);
console.log('Example 4 (null):', preferences);
// Expected: {} (or throws, depending on internal implementation for null/undefined - testing shows it handles it gracefully)