HTTP Vary Header Parser and Utility

1.0.3 · active · verified Sun Apr 19

http-vary is a lightweight, RFC 9110 compliant utility designed for parsing and comparing HTTP Vary headers, which are crucial for ensuring correct HTTP caching behavior. It provides two primary functions: `parse()`, which normalizes a Vary header string into an array of lowercase header names (or a wildcard `'*'`), and `compare()`, used to determine if two sets of request headers are cache-equivalent based on a specified Vary header. The package is currently at version 1.0.3 and is part of the 'tinylibs' monorepo, suggesting a consistent, albeit independent, patch release cadence. Its core strength lies in its minimal footprint and strict adherence to RFC 9110, focusing exclusively on the Vary header without extraneous caching logic. This makes it ideal for environments demanding precise control over HTTP caching mechanisms. It also ships with comprehensive TypeScript types, enhancing developer experience and type safety.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a Vary header string and use the `compare` function to check if two sets of request headers are cache-equivalent according to the Vary header, including handling the wildcard ('*') case.

import { parse, compare, VaryHeader } from 'http-vary';

// Parse a Vary header string into a normalized array of header names.
const rawHeader: string = 'Accept-Encoding, User-Agent';
const vary: VaryHeader = parse(rawHeader);
console.log('Parsed Vary header:', vary); // => ['accept-encoding', 'user-agent']

// Handle the wildcard Vary header, which means the response varies by everything.
const wildcardVary: VaryHeader = parse('*');
console.log('Parsed wildcard Vary header:', wildcardVary); // => '*'

// Define two sets of request headers to compare for cache equivalence.
const headers1 = {
  'Accept-Encoding': 'gzip',
  'User-Agent': 'Chrome/120.0'
};

const headers2 = {
  'Accept-Encoding': 'gzip',
  'User-Agent': 'Chrome/120.0',
  'Cookie': 'session=abc' // This header should be ignored if not in the Vary list
};

// Compare headers for cache equivalence based on the parsed Vary header.
const isEquivalent1: boolean = compare(vary, headers1, headers2);
console.log('Headers 1 and 2 are equivalent (Accept-Encoding, User-Agent):', isEquivalent1); // true

const headers3 = {
  'Accept-Encoding': 'br',
  'User-Agent': 'Firefox/120.0'
};

const isEquivalent2: boolean = compare(vary, headers1, headers3);
console.log('Headers 1 and 3 are equivalent (Accept-Encoding, User-Agent):', isEquivalent2); // false (different values)

const headers4 = {
  'Accept-Encoding': 'gzip',
  'User-Agent': 'Chrome/121.0'
};

const isEquivalent3: boolean = compare(wildcardVary, headers1, headers4);
console.log('Headers 1 and 4 are equivalent (*):', isEquivalent3); // false (wildcard makes even minor changes relevant)

view raw JSON →