liveBook · Manning

Cache Storage API

As explained in Vanilla Web

The Cache Storage API is a browser API for storing and retrieving request–response pairs, commonly to support offline use and control of network responses.

Use the Cache Storage API when data naturally looks like a network response: a Request or URL identifies a complete Response, including its headers and body. It is useful for offline assets and cached API responses. It works in service workers and is also available from a window. section 12.4.6

Choose storage by the shape of the data:

  • Use Cache Storage for request/response pairs, such as app-shell assets, an offline page, or an API response identified by URL. section 12.4.6
  • Use IndexedDB instead for drafts, queues, and other domain records that are not naturally identified by a URL. section 12.4.2 section 14.8.4
const cache = await caches.open("api-v1");

await cache.put(
  "/api/products?page=1",
  new Response(JSON.stringify(products), {
    headers: {
      "Content-Type": "application/json",
    },
  })
);

const cachedResponse = await cache.match("/api/products?page=1");

Open a named cache, put a JSON Response under an API URL, then match that URL to retrieve the cached response. section 12.4.6

Saving a response is only the first decision. A changed server file does not automatically update every client's cache. Choose an explicit strategy, such as versioned cache names, hashed filenames, stale-while-revalidate, cache-first, or network-first. Different resources may need different freshness rules: HTML, long-lived hashed assets, and API responses need not be treated alike. section 12.4.6 section 14.8.4

Treat the cache as recoverable browser storage, not the only copy of critical data. Quotas and eviction can remove stored responses; plan for recovery or server-side copies where necessary. Browser developer tools can help inspect stored data. section 2.4.3

How Vanilla Web covers it

How deep it goes
Defines Request/Response storage and demonstrates open, put, and match, while deferring detailed service-worker and offline strategies.
Examples
Shows a named cache holding a JSON product response under an API URL and retrieving it with match.
What it assumes
Assumes familiarity with URLs and network responses; introduces the storage model without requiring a service worker.
What you can do after
Operate/configure it by opening a named cache and putting and matching URL-keyed responses.
How it connects
Relates Cache Storage to service workers, IndexedDB, HTTP caching, and offline behavior.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.