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
