|
1 | | -<h1 align="center">cdn-cache-control</h1> |
2 | | -<p align="center"> |
3 | | - <img alt="cdn-cache-control" src="https://github.com/user-attachments/assets/62464d67-cbd5-48b5-a36d-800678ae22bb" /> |
4 | | -</p> |
| 1 | +# cache-primitives |
5 | 2 |
|
6 | | -Easy, opinionated CDN cache header handling. |
| 3 | +This repository is a monorepo containing several packages related to CDN cache control. |
7 | 4 |
|
8 | | -Modern CDNs allow very fine-grained control over the cache. This is particularly useful for server-side rendering of web content, as it allows you to manually handle the invalidation of content, ensuring it stays fast and fresh. This package provides a subclass of the `Headers` class that makes it easier to set cache control headers for content served through a modern CDN. It provides a simple, chainable API with sensible defaults for common use cases. It works by setting the `Cache-Control` and `CDN-Cache-Control` headers to the appropriate values. If run on a supported platform it will use the more specific header for that CDN. e.g. on Netlify it will use the `Netlify-CDN-Cache-Control` header. |
| 5 | +## Packages |
9 | 6 |
|
10 | | -e.g. |
| 7 | +- `cdn-cache-control`: Easy, opinionated CDN cache header handling. |
| 8 | +- `cache-handlers`: Modern CDN cache primitives using web-standard middleware. |
11 | 9 |
|
12 | | -```javascript |
13 | | -// Expires in 1 minute, but use stale-while-revalidate to serve stale content after that |
14 | | -const headers = new CacheHeaders().ttl(ONE_MINUTE).swr(); |
15 | | -``` |
16 | | - |
17 | | -## Installation |
18 | | - |
19 | | -```bash |
20 | | -npm install cdn-cache-control |
21 | | -``` |
22 | | - |
23 | | -It is also available in [jsr](https://jsr.io) as `@ascorbic/cdn-cache-control`. If using Deno, you can import it directly without installing: |
24 | | - |
25 | | -```javascript |
26 | | -import { CacheHeaders } from "jsr:@ascorbic/cdn-cache-control"; |
27 | | -``` |
28 | | - |
29 | | -## Usage |
30 | | - |
31 | | -The module exports a single class, `CacheHeaders`, which is a subclass of the fetch [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) class. It provides a chainable API for setting cache headers. By default it sets the `Cache-Control` and `CDN-Cache-Control` headers to sensible defaults for content that should be cached by the CDN and revalidated by the browser. |
32 | | - |
33 | | -It can be instantiated with a `HeadersInit` value, which lets you base it on an existing `Headers` object, or an object or array with existing header values. In that case it will default to using existing `s-maxage` directives if present. |
34 | | - |
35 | | -You can pass a `cdn` value as the second argument to set the CDN cache control header. In some cases this will enable targeted cache header names. e.g. for Netlify it will use the `Netlify-CDN-Cache-Control` header. Currently supported values are `netlify`, `vercel`, `cloudflare` and `akamai`. If you don't pass a value, or pass an unsupported one it will use the generic `CDN-Cache-Control` header. It will also attempt to detect the platform automatically on Vercel and Netlify. |
36 | | - |
37 | | -### Use cases |
38 | | - |
39 | | -If you have content that you want to have the CDN cache until it is manually revalidated or purged with a new deploy, you can use the default values: |
40 | | - |
41 | | -```javascript |
42 | | -import { CacheHeaders } from "cdn-cache-control"; |
43 | | - |
44 | | -const headers = new CacheHeaders(); |
45 | | -``` |
46 | | - |
47 | | -This sets the `CDN-Cache-Control` header to `public,s-maxage=31536000,must-revalidate`, which tells the CDN to cache the content for a year. It sets `Cache-Control` to `public,max-age=0,must-revalidate`, which tells the browser to always check with the CDN for a fresh version. You should combine this with an `ETag` or `Last-Modified` header to allow the CDN to serve a `304 Not Modified` response when the content hasn't changed. |
48 | | - |
49 | | -#### stale-while-revalidate |
50 | | - |
51 | | -You can enable `stale-while-revalidate` with the `swr` method, optionally passing a value for the time to serve stale content (defaults to one week): |
52 | | - |
53 | | -```javascript |
54 | | -import { CacheHeaders } from "cdn-cache-control"; |
55 | | - |
56 | | -const headers = new CacheHeaders().swr(); |
57 | | -``` |
58 | | - |
59 | | -This tells the CDN to serve stale content while revalidating the content in the background. Combine with the `ttl` method to set the time for which the content will be considered fresh (default is zero, meaning the CDN will always revalidate): |
60 | | - |
61 | | -```javascript |
62 | | -import { CacheHeaders, ONE_HOUR } from "cdn-cache-control"; |
63 | | - |
64 | | -const headers = new CacheHeaders().swr().ttl(ONE_HOUR); |
65 | | -``` |
66 | | - |
67 | | -#### Immutable content |
68 | | - |
69 | | -If you are serving content that is guaranteed to never change then you can set it as immutable. You should only do this for responses with unique URLs, because there will be no way to invalidate it from the browser cache if it ever changes. |
70 | | - |
71 | | -```javascript |
72 | | -import { CacheHeaders } from "cdn-cache-control"; |
73 | | -const headers = new CacheHeaders().immutable(); |
74 | | -``` |
75 | | - |
76 | | -This will set the CDN and browser caches to expire in 1 year, and add the immutable directive. |
77 | | - |
78 | | -#### Cache tags |
79 | | - |
80 | | -Some CDNs support the use of cache tags, which allow you to purge content from the cache in bulk. The `tag()` function makes it simple to add tags. You can call it with a string or array of strings. |
81 | | - |
82 | | -```javascript |
83 | | -import { CacheHeaders } from "cdn-cache-control"; |
84 | | -const headers = new CacheHeaders().tag(["blog", "blog:1"]); |
85 | | -``` |
86 | | - |
87 | | -You can then purge the tagged items from the cache using the CDN API. e.g. for Netlify the API is: |
88 | | - |
89 | | -```typescript |
90 | | -import { purgeCache } from "@netlify/functions"; |
91 | | - |
92 | | -export default async function handler(req: Request) => { |
93 | | - await purgeCache({ |
94 | | - tags: ["blog", "blog:1", "blog:2"], |
95 | | - }); |
96 | | - return new Response("Purged!", { status: 202 }) |
97 | | -}; |
98 | | - |
99 | | -``` |
100 | | - |
101 | | -#### Using the generated headers |
102 | | - |
103 | | -The headers object can be used anywhere that accepts a `fetch` `Headers` object. This includes most serverless hosts. It can also be used directly in many framework SSR functions. Some APIs need a plain object rather than a `Headers` object. For these you can use the `toObject()` method, which returns a plain object with the header names and values. |
104 | | - |
105 | | -```typescript |
106 | | -import { CacheHeaders } from "cdn-cache-control"; |
107 | | - |
108 | | -export default async function handler(request: Request): Promise<Response> { |
109 | | - const headers = new CacheHeaders().swr(); |
110 | | - // The `Response` constructor accepts the object directly |
111 | | - return new Response("Hello", { headers }); |
112 | | -} |
113 | | -``` |
114 | | - |
115 | | -Some frameworks use a readonly `Response` object, so you need to use an existing `headers` object. In this case you can use the `copyTo` method to copy the headers to the response: |
116 | | - |
117 | | -```astro |
118 | | ---- |
119 | | -import { CacheHeaders, ONE_HOUR } from "cdn-cache-control"; |
120 | | -
|
121 | | -new CacheHeaders().swr(ONE_HOUR).copyTo(Astro.response.headers); |
122 | | ---- |
123 | | -
|
124 | | -``` |
125 | | - |
126 | | -## API |
127 | | - |
128 | | -<!-- TSDOC_START --> |
129 | | - |
130 | | -## :wrench: Constants |
131 | | - |
132 | | -- [ONE_MINUTE](#gear-one_minute) |
133 | | -- [ONE_HOUR](#gear-one_hour) |
134 | | -- [ONE_DAY](#gear-one_day) |
135 | | -- [ONE_WEEK](#gear-one_week) |
136 | | -- [ONE_YEAR](#gear-one_year) |
137 | | - |
138 | | -### :gear: ONE_MINUTE |
139 | | - |
140 | | -Number of seconds in one minute |
141 | | - |
142 | | -| Constant | Type | |
143 | | -| ------------ | ---- | |
144 | | -| `ONE_MINUTE` | `60` | |
145 | | - |
146 | | -### :gear: ONE_HOUR |
147 | | - |
148 | | -Number of seconds in one hour |
149 | | - |
150 | | -| Constant | Type | |
151 | | -| ---------- | ------ | |
152 | | -| `ONE_HOUR` | `3600` | |
153 | | - |
154 | | -### :gear: ONE_DAY |
155 | | - |
156 | | -Number of seconds in one day |
157 | | - |
158 | | -| Constant | Type | |
159 | | -| --------- | ------- | |
160 | | -| `ONE_DAY` | `86400` | |
161 | | - |
162 | | -### :gear: ONE_WEEK |
163 | | - |
164 | | -Number of seconds in one week |
165 | | - |
166 | | -| Constant | Type | |
167 | | -| ---------- | -------- | |
168 | | -| `ONE_WEEK` | `604800` | |
169 | | - |
170 | | -### :gear: ONE_YEAR |
171 | | - |
172 | | -Number of seconds in one year |
173 | | - |
174 | | -| Constant | Type | |
175 | | -| ---------- | ---------- | |
176 | | -| `ONE_YEAR` | `31536000` | |
177 | | - |
178 | | -## :factory: CacheHeaders |
179 | | - |
180 | | -### Methods |
181 | | - |
182 | | -- [Installation](#installation) |
183 | | -- [Usage](#usage) |
184 | | - - [Use cases](#use-cases) |
185 | | - - [stale-while-revalidate](#stale-while-revalidate) |
186 | | - - [Immutable content](#immutable-content) |
187 | | - - [Cache tags](#cache-tags) |
188 | | - - [Using the generated headers](#using-the-generated-headers) |
189 | | -- [API](#api) |
190 | | -- [:wrench: Constants](#wrench-constants) |
191 | | - - [:gear: ONE\_MINUTE](#gear-one_minute) |
192 | | - - [:gear: ONE\_HOUR](#gear-one_hour) |
193 | | - - [:gear: ONE\_DAY](#gear-one_day) |
194 | | - - [:gear: ONE\_WEEK](#gear-one_week) |
195 | | - - [:gear: ONE\_YEAR](#gear-one_year) |
196 | | -- [:factory: CacheHeaders](#factory-cacheheaders) |
197 | | - - [Methods](#methods) |
198 | | - - [:gear: tag](#gear-tag) |
199 | | - - [:gear: swr](#gear-swr) |
200 | | - - [:gear: immutable](#gear-immutable) |
201 | | - - [:gear: ttl](#gear-ttl) |
202 | | - - [:gear: toObject](#gear-toobject) |
203 | | - - [:gear: copyTo](#gear-copyto) |
204 | | - - [:gear: getCdnCacheControl](#gear-getcdncachecontrol) |
205 | | - - [:gear: setCdnCacheControl](#gear-setcdncachecontrol) |
206 | | - - [:gear: getCacheControl](#gear-getcachecontrol) |
207 | | - - [:gear: setCacheControl](#gear-setcachecontrol) |
208 | | - - [:gear: getCacheTags](#gear-getcachetags) |
209 | | - - [:gear: setCacheTags](#gear-setcachetags) |
210 | | - |
211 | | -#### :gear: tag |
212 | | - |
213 | | -Adds a cache tag to the cache tags header. Cache tags are used to invalidate the cache for a URL. |
214 | | - |
215 | | -| Method | Type | |
216 | | -| ------ | ------------------------------------------------------ | |
217 | | -| `tag` | `(tag: string or string[], ...tags: string[]) => this` | |
218 | | - |
219 | | -Parameters: |
220 | | - |
221 | | -- `tag`: The cache tag to add. Can be a string or an array of strings. |
222 | | - |
223 | | -#### :gear: swr |
224 | | - |
225 | | -Sets stale-while-revalidate directive for the CDN cache. By default the browser is sent a must-revalidate |
226 | | -directive to ensure that the browser always revalidates the cache with the server. |
227 | | - |
228 | | -| Method | Type | |
229 | | -| ------ | -------------------------- | |
230 | | -| `swr` | `(value?: number) => this` | |
231 | | - |
232 | | -Parameters: |
233 | | - |
234 | | -- `value`: The number of seconds to set the stale-while-revalidate directive to. Defaults to 1 week. |
235 | | - |
236 | | -#### :gear: immutable |
237 | | - |
238 | | -Sets cache headers for content that should be cached for a long time and never revalidated. |
239 | | -The CDN cache will cache the content for the specified time, and the browser will cache the content |
240 | | -indefinitely without revalidating. Do not use this unless the URL is fingerprinted or otherwise unique. |
241 | | -Otherwise, the browser will cache the content indefinitely and never check for updates, including for new deploys. |
242 | | - |
243 | | -| Method | Type | |
244 | | -| ----------- | -------------------------- | |
245 | | -| `immutable` | `(value?: number) => this` | |
246 | | - |
247 | | -Parameters: |
248 | | - |
249 | | -- `value`: The number of seconds to set the CDN cache-control s-maxage directive to. Defaults to 1 year. |
250 | | - |
251 | | -#### :gear: ttl |
252 | | - |
253 | | -Sets the s-maxage for items in the CDN cache. This is the maximum amount of time that the CDN will cache the content. |
254 | | -If used with swr, the content will revalidate in the background after the max age has passed. Otherwise, the content will be |
255 | | -removed from the cache after the max age has passed. |
256 | | - |
257 | | -| Method | Type | |
258 | | -| ------ | ------------------------- | |
259 | | -| `ttl` | `(value: number) => this` | |
260 | | - |
261 | | -#### :gear: toObject |
262 | | - |
263 | | -Returns the headers as a plain object. |
264 | | - |
265 | | -| Method | Type | |
266 | | -| ---------- | ------------------------------ | |
267 | | -| `toObject` | `() => Record<string, string>` | |
268 | | - |
269 | | -#### :gear: copyTo |
270 | | - |
271 | | -Copy the headers from this instance to another Headers instance. |
272 | | - |
273 | | -| Method | Type | |
274 | | -| -------- | -------------------------------------- | |
275 | | -| `copyTo` | `<T extends Headers>(headers: T) => T` | |
276 | | - |
277 | | -#### :gear: getCdnCacheControl |
278 | | - |
279 | | -The parsed cache-control header for the CDN cache. |
280 | | - |
281 | | -| Method | Type | |
282 | | -| -------------------- | ------------------------------ | |
283 | | -| `getCdnCacheControl` | `() => Record<string, string>` | |
284 | | - |
285 | | -#### :gear: setCdnCacheControl |
286 | | - |
287 | | -| Method | Type | |
288 | | -| -------------------- | ---------------------------------------------- | |
289 | | -| `setCdnCacheControl` | `(directives: Record<string, string>) => void` | |
290 | | - |
291 | | -#### :gear: getCacheControl |
292 | | - |
293 | | -The parsed cache-control header for the browser cache. |
294 | | - |
295 | | -| Method | Type | |
296 | | -| ----------------- | ------------------------------ | |
297 | | -| `getCacheControl` | `() => Record<string, string>` | |
298 | | - |
299 | | -#### :gear: setCacheControl |
300 | | - |
301 | | -| Method | Type | |
302 | | -| ----------------- | ---------------------------------------------- | |
303 | | -| `setCacheControl` | `(directives: Record<string, string>) => void` | |
304 | | - |
305 | | -#### :gear: getCacheTags |
306 | | - |
307 | | -The parsed content of the cache tags header. |
308 | | - |
309 | | -| Method | Type | |
310 | | -| -------------- | ---------------- | |
311 | | -| `getCacheTags` | `() => string[]` | |
312 | | - |
313 | | -#### :gear: setCacheTags |
314 | | - |
315 | | -| Method | Type | |
316 | | -| -------------- | -------------------------- | |
317 | | -| `setCacheTags` | `(tags: string[]) => void` | |
318 | | - |
319 | | -<!-- TSDOC_END --> |
0 commit comments