Cache-Control Header Parser

2.2.0 · active · verified Tue Apr 21

cache-control-parser is a JavaScript/TypeScript utility for parsing and stringifying HTTP `Cache-Control` header directives. Its current stable version is 2.2.0, with regular updates that enhance its functionality, such as the introduction of the `stringify` function in v2.0.0. The library is designed to be fault-tolerant and case-insensitive when parsing, handling common HTTP caching scenarios robustly. Key differentiators include its zero-dependency footprint, comprehensive built-in TypeScript definitions, and the capability to both convert `Cache-Control` strings into structured JavaScript objects and convert objects back into valid header strings, making it suitable for both consuming and generating HTTP responses in Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a Cache-Control header, accessing its directives, and then stringifying a new set of directives, including TypeScript type usage.

import { parse, stringify } from "cache-control-parser";
import type { CacheControl } from "cache-control-parser";

// 1. Parse a cache-control header string into an object
const headerString = "public, max-age=300, stale-while-revalidate=60, no-transform";
const parsedDirectives: CacheControl = parse(headerString);

console.log("Parsed directives:", parsedDirectives);
// Expected output: { public: true, 'max-age': 300, 'stale-while-revalidate': 60, 'no-transform': true }

// 2. Access specific directives and apply fallback logic
const { "max-age": maxAge, "stale-while-revalidate": swr = maxAge ?? 0 } = parsedDirectives;
console.log(`Max Age: ${maxAge || 'N/A'}s, SWR: ${swr}s`);

// 3. Create an object of directives and stringify it back into a header string
const newDirectives: CacheControl = {
  "max-age": 600,
  "s-maxage": 120,
  "public": true,
  "immutable": true,
  "no-cache": false // Directives with false values are omitted
};
const newHeaderString = stringify(newDirectives);

console.log("Stringified header:", newHeaderString);
// Expected output: max-age=600, s-maxage=120, public, immutable

// Example of usage in a web framework (e.g., Next.js response)
// import type { NextApiRequest, NextApiResponse } from "next";
// export default (req: NextApiRequest, res: NextApiResponse) => {
//   res.setHeader(
//     "Cache-Control",
//     stringify({
//       "max-age": 300,
//       "stale-if-error": 60
//     })
//   );
//   res.send("API response");
// };

view raw JSON →