Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Caching Strategies

Cache API Basics

Learn the Cache API for PWAs: caches.open, add, addAll, put, match, delete and keys, how requests are matched, storage limits and quota, with runnable examples.

The Cache API is a storage system for Request and Response pairs. It was designed for service workers but is also available in normal pages in secure contexts. Think of it as a dictionary where the key is a request (essentially its URL) and the value is a full HTTP response with headers and body. This is what lets a service worker hand back "the file" with no network at all.

The Cache API is not an HTTP cache: nothing is added or removed automatically, nothing expires, and there are no freshness rules. You decide what goes in, when it is replaced and when it is deleted. That freedom is why caching strategies (the rest of this chapter) exist.

Two levels: CacheStorage and Cache

  • caches (a CacheStorage) holds many named caches: caches.open, caches.has, caches.keys, caches.delete and caches.match (search all caches).
  • A Cache is one named bucket: add, addAll, put, match, matchAll, delete, keys.
JavaScript
const cache = await caches.open('app-v1');      // creates it if it doesn't exist

Use several caches with separate purposes and versions, such as app-v1 for the shell, images-v1 for pictures, api-v1 for data. Each can be deleted on its own.

Adding entries

cache.add(url) fetches a URL and stores the response. cache.addAll([urls]) does that for many, atomically (one failure rejects them all). cache.put(request, response) stores a response you already have, for example one you fetched yourself.

JavaScript
const cache = await caches.open('app-v1');

await cache.add('/offline.html');
await cache.addAll(['/', '/styles.css', '/app.js']);

const response = await fetch('/api/notes');
await cache.put('/api/notes', response.clone());

Notes:

  • add and addAll fail for non-OK responses (for example 404 or 500). put does not check: you can store an error response by mistake, so check response.ok yourself.
  • Only GET requests can be cached. A POST request key throws a TypeError.
  • A response with status 206 (partial content) cannot be cached.
  • put replaces an existing entry with the same key.

Reading entries

JavaScript
const cached = await cache.match('/styles.css');      // Response or undefined
if (cached) console.log(await cached.text());

const all = await caches.match('/styles.css');        // search every cache, oldest first
const entries = await cache.keys();                   // array of Request objects
console.log(entries.map((r) => r.url));

match returns undefined when nothing matches. It does not reject. Remember this: caches.match(request).then(r => r || fetch(request)) is the classic cache-first one-liner.

Deleting

JavaScript
await cache.delete('/old.js');          // true if an entry was removed
await caches.delete('app-v0');          // drop a whole cache
console.log(await caches.keys());       // names of all caches

There is no automatic eviction by age. The browser may evict whole origins' storage when the device runs low on space, but only under pressure, and unless you request persistent storage (navigator.storage.persist()), you cannot control it.

How requests are matched

match compares the request URL, the HTTP method (GET), and the response's Vary header with the request headers. Query strings count by default: /api?page=1 and /api?page=2 are different entries. Options relax this:

Option Meaning
ignoreSearch: true Ignore the query string
ignoreMethod: true Match even if the method is not GET
ignoreVary: true Ignore the Vary header
cacheName Only in caches.match: search just one cache
JavaScript
await cache.match('/index.html?source=pwa', { ignoreSearch: true });

This matters for start_url: "/?source=pwa": you need ignoreSearch or the cached / does not match.

A tiny Cache API you can run

The real API is not available in this page's sandbox, so here is a small faithful stand-in built on a Map, with real Request and Response objects. It follows the semantics above: GET only, query strings matter unless ignored, match resolves to undefined on a miss.

JS Stand-in: a mini Cache and CacheStorage

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Inspecting the real thing

In Chrome DevTools open Application > Cache storage. Each cache is listed; clicking one shows its entries with URL, status, content type and size. Right-click to delete entries. The preview pane displays the body. Use it constantly while building caching logic: it shows exactly what your worker stored.

Storage limits and persistence

Browsers give each origin a quota, usually a sizeable percentage of free disk (often hundreds of MB or more, but varies widely, and is much smaller in some private modes). The Cache API, IndexedDB and other storage share that quota. You can ask:

JavaScript
const { usage, quota } = await navigator.storage.estimate();
console.log(`${(usage / 1e6).toFixed(1)} MB of ${(quota / 1e6).toFixed(0)} MB`);

const persisted = await navigator.storage.persist();   // ask the browser not to evict

If a write exceeds the quota you get a QuotaExceededError. Handle it in production by trimming the cache (see below).

Opaque cross-origin responses count for much more than their real size in some browsers, which is one reason to avoid caching them.

Trimming a cache

There is no built-in size limit per cache, so apps with image or API caches keep their own limits: delete the oldest entries when the count exceeds a maximum. cache.keys() returns entries in insertion order, so the first ones are the oldest.

JS Trim a cache to N entries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For a smarter eviction (least recently used) you would store timestamps in IndexedDB. Tools like Workbox do this with an ExpirationPlugin (covered in the precaching lesson).

Common mistakes

  • Treating match as if it rejects on a miss: always check for undefined.
  • Caching error responses with put.
  • Forgetting clone() when you both put and return a response.
  • Keeping unbounded caches: images and API data grow forever.
  • Using a single cache name for everything, making cleanup hard.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does cache.match(url) return when nothing is found?

    match resolves to undefined on a miss, so the cache-first one-liner uses || to fall back to the network.
  2. 2. Which requests can be stored in the Cache API?

    Only GET requests can be cache keys; others throw a TypeError.
  3. 3. What does ignoreSearch: true do?

    It lets /page?x=1 match a cached /page.
  4. 4. How can you remove an old cache named app-v1 entirely?

    caches.delete removes a whole named cache; cache.delete removes one entry.
  5. 5. Does the Cache API expire entries automatically?

    It is a plain store: entries stay until you delete them or the browser evicts the origin's storage.

Summary

  • caches manages named Cache objects; a cache stores Request/Response pairs.
  • Use add, addAll and put to store; match and keys to read; delete to remove.
  • Only GET requests are cacheable; match resolves to undefined on a miss; query strings matter unless you set ignoreSearch.
  • There is no automatic expiry, so you trim and version caches yourself.
  • Check storage with navigator.storage.estimate().

Next: The Cache First Strategy