Cache-Control Header Parser
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
-
TypeError: (0 , cache_control_parser_1.stringify) is not a function
cause Attempting to use the `stringify` function on a version of `cache-control-parser` older than 2.0.0.fixUpdate your package to `npm install cache-control-parser@latest` (or at least `^2.0.0`). -
TypeError: Cannot read properties of undefined (reading 'parse')
cause Incorrect CommonJS `require` syntax for a library that may be ESM-first or provides named exports primarily through ESM.fixUse ESM import: `import { parse } from 'cache-control-parser';` instead of `const parse = require('cache-control-parser').parse;`.
Warnings
- breaking The `stringify` function was introduced in version 2.0.0. Projects on older major versions (1.x) will not have this function available, leading to runtime errors if called.
- gotcha This package is primarily designed for ESM usage. While some bundlers or transpilers may handle CommonJS `require()` syntax, direct `require()` calls in pure Node.js CommonJS environments might lead to import errors for certain Node.js versions or configurations, particularly with named exports.
- gotcha Directives with a boolean value of `false` (e.g., `'no-cache': false`) will be omitted from the output when using the `stringify` function. Only `true` boolean directives are included, and `number` directives are included with their value.
Install
-
npm install cache-control-parser -
yarn add cache-control-parser -
pnpm add cache-control-parser
Imports
- parse
const parse = require('cache-control-parser').parse;import { parse } from 'cache-control-parser'; - stringify
const { stringify } = require('cache-control-parser');import { stringify } from 'cache-control-parser'; - CacheControl
import { CacheControl } from 'cache-control-parser';import type { CacheControl } from 'cache-control-parser';
Quickstart
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");
// };