Pretty Cache Header Utility
pretty-cache-header is a JavaScript/TypeScript utility designed to simplify the creation of `Cache-Control` HTTP headers by parsing human-readable time strings into seconds. It aims to reduce errors by leveraging TypeScript's Template Literal Types to provide strong type-safety for time string formats, ensuring developers pass valid patterns like '1week' or '30days'. The package is currently at version 1.0.0, indicating its initial stable release. As a lightweight utility with a focused purpose, its release cadence is expected to be driven by bug fixes or minor enhancements rather than frequent major updates. Its key differentiator is the combination of human-readable time strings with robust type-checking, making it particularly useful in TypeScript-heavy projects where maintainability and type safety are priorities, especially when configuring server responses or CDN caching policies.
Warnings
- gotcha The library enforces strict `TimeString` formats for `maxAge`, `staleWhileRevalidate`, etc., using TypeScript's Template Literal Types. For example, '1 week' (with a space) is invalid, while '1week' is valid. Non-TypeScript users might only discover format issues at runtime if the string parsing fails, or they might not get the expected cache duration.
- gotcha When migrating from older cache-control header implementations, be aware that `pretty-cache-header` automatically converts time strings to seconds. Ensure any existing hardcoded second values are correctly expressed as human-readable strings if desired, or passed as numbers directly for properties like `maxAge` (though the primary benefit is the string parsing).
Install
-
npm install pretty-cache-header -
yarn add pretty-cache-header -
pnpm add pretty-cache-header
Imports
- cacheHeader
const { cacheHeader } = require('pretty-cache-header');import { cacheHeader } from 'pretty-cache-header';
Quickstart
import { cacheHeader } from 'pretty-cache-header';
function createResponseWithCaching() {
const cacheControlHeader = cacheHeader({
public: true,
maxAge: '1week',
sMaxage: '1hour',
staleWhileRevalidate: '1year',
immutable: true
});
// In a real application, this would be part of an HTTP response.
// For demonstration, we'll just log the header value.
console.log('Generated Cache-Control Header:', cacheControlHeader);
// Example of how it might be used in a web framework (e.g., Express.js or a Web Fetch API response)
// return new Response('Content', {
// headers: {
// 'Content-Type': 'text/plain',
// 'Cache-Control': cacheControlHeader
// }
// });
return cacheControlHeader;
}
createResponseWithCaching();