HTTP Prefer Header Parser

1.0.0 · maintenance · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing various HTTP Prefer header string formats, including single strings, arrays, values with parameters, and quoted values, and shows how the output is structured as a JavaScript object.

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)

view raw JSON →