1# Can I cache this? [![Build Status](https://travis-ci.org/pornel/http-cache-semantics.svg?branch=master)](https://travis-ci.org/pornel/http-cache-semantics) 2 3`CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. 4 5## Usage 6 7Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. 8 9```js 10const policy = new CachePolicy(request, response, options); 11 12if (!policy.storable()) { 13 // throw the response away, it's not usable at all 14 return; 15} 16 17// Cache the data AND the policy object in your cache 18// (this is pseudocode, roll your own cache (lru-cache package works)) 19letsPretendThisIsSomeCache.set(request.url, {policy, response}, policy.timeToLive()); 20``` 21 22```js 23// And later, when you receive a new request: 24const {policy, response} = letsPretendThisIsSomeCache.get(newRequest.url); 25 26// It's not enough that it exists in the cache, it has to match the new request, too: 27if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { 28 // OK, the previous response can be used to respond to the `newRequest`. 29 // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. 30 response.headers = policy.responseHeaders(); 31 return response; 32} 33``` 34 35It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc. 36 37The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. 38 39### Constructor options 40 41Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method). 42 43```js 44const request = { 45 url: '/', 46 method: 'GET', 47 headers: { 48 accept: '*/*', 49 }, 50}; 51 52const response = { 53 status: 200, 54 headers: { 55 'cache-control': 'public, max-age=7234', 56 }, 57}; 58 59const options = { 60 shared: true, 61 cacheHeuristic: 0.1, 62 immutableMinTimeToLive: 24*3600*1000, // 24h 63 ignoreCargoCult: false, 64}; 65``` 66 67If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). 68 69`options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. 70 71`options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default. 72 73If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults. 74 75### `storable()` 76 77Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response. 78 79### `satisfiesWithoutRevalidation(newRequest)` 80 81This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request. 82 83If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`. 84 85If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`). 86 87### `responseHeaders()` 88 89Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time. 90 91```js 92cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); 93``` 94 95### `timeToLive()` 96 97Returns approximate time in *milliseconds* until the response becomes stale (i.e. not fresh). 98 99After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`. 100 101### `toObject()`/`fromObject(json)` 102 103Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it. 104 105### Refreshing stale cache (revalidation) 106 107When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth. 108 109The following methods help perform the update efficiently and correctly. 110 111#### `revalidationHeaders(newRequest)` 112 113Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is. 114 115Use this method when updating cache from the origin server. 116 117```js 118updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); 119``` 120 121#### `revalidatedPolicy(revalidationRequest, revalidationResponse)` 122 123Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: 124 125* `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. 126* `modified` — Boolean indicating whether the response body has changed. 127 * If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. 128 * If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource. 129 130```js 131// When serving requests from cache: 132const {oldPolicy, oldResponse} = letsPretendThisIsSomeCache.get(newRequest.url); 133 134if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) { 135 // Change the request to ask the origin server if the cached response can be used 136 newRequest.headers = oldPolicy.revalidationHeaders(newRequest); 137 138 // Send request to the origin server. The server may respond with status 304 139 const newResponse = await makeRequest(newResponse); 140 141 // Create updated policy and combined response from the old and new data 142 const {policy, modified} = oldPolicy.revalidatedPolicy(newRequest, newResponse); 143 const response = modified ? newResponse : oldResponse; 144 145 // Update the cache with the newer/fresher response 146 letsPretendThisIsSomeCache.set(newRequest.url, {policy, response}, policy.timeToLive()); 147 148 // And proceed returning cached response as usual 149 response.headers = policy.responseHeaders(); 150 return response; 151} 152``` 153 154# Yo, FRESH 155 156![satisfiesWithoutRevalidation](fresh.jpg) 157 158## Used by 159 160* [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/pornel/http-cache-semantics/network/dependents) 161 162## Implemented 163 164* `Cache-Control` response header with all the quirks. 165* `Expires` with check for bad clocks. 166* `Pragma` response header. 167* `Age` response header. 168* `Vary` response header. 169* Default cacheability of statuses and methods. 170* Requests for stale data. 171* Filtering of hop-by-hop headers. 172* Basic revalidation request 173 174## Unimplemented 175 176* Merging of range requests, If-Range (but correctly supports them as non-cacheable) 177* Revalidation of multiple representations 178