Skip to content

Lesson 2 of 9 · 27m

Cache-First, Network-First, and Stale-While-Revalidate

Choose cache strategy by failure tolerance and data freshness instead of copying a generic service worker recipe.

Most offline implementations fail because the cache policy is a vibe. Someone copies cache.addAll(['/']), adds a catch-all fetch handler, and calls the app offline-ready. Six months later users see yesterday's account balance, a deleted document, or a shell that references files the server no longer hosts. Caching is a consistency design problem wearing a networking costume.

Classify resources before writing handlers

Every URL in your application should have a cache owner:

versioned static assets   cache-first, immutable
HTML navigations          network-first with offline fallback
GET API reads             stale-while-revalidate or network-first
non-GET API mutations     never cache as successful
media/uploads             cache-first with bounded storage
personalized pages        usually avoid full-document caching

Route explicitly. No request should fall into a default policy you cannot explain:

if (event.request.method !== 'GET') return;
if (url.pathname.startsWith('/assets/')) {
  event.respondWith(cacheFirst(event.request));
} else if (event.request.mode === 'navigate') {
  event.respondWith(networkFirstNavigation(event.request));
} else if (url.pathname.startsWith('/api/catalog/')) {
  event.respondWith(staleWhileRevalidate(event.request));
}

Cache-first belongs to immutable files

Fingerprinted assets are safe because the URL changes when the content changes:

async function cacheFirst(request) {
  const hit = await caches.match(request);
  if (hit) return hit;
  const response = await fetch(request);
  if (response.ok) {
    const cache = await caches.open('assets-v1');
    await cache.put(request, response.clone());
  }
  return response;
}

Do not cache-first /app.js if deployments reuse that URL. Either fingerprint the file or accept stale clients. Teams frequently forget CSS, wasm, nested workers, and manifest icons in the same rule.

Network-first is for truth with a fallback

HTML is the classic case: prefer the newest deployment online, but keep a useful shell when the network is absent. The minimal shape is fetch(request) first and caches.match('/offline.html') in the catch path. Production navigation caching must also respect authentication, personalization, redirects, and response headers. Never blindly cache an authenticated HTML page and serve it to another browser profile.

Stale-while-revalidate is a bargain, not magic

For catalog-style GET data, returning fast stale data and refreshing in the background feels native:

async function staleWhileRevalidate(request) {
  const cache = await caches.open('api-read-v1');
  const cached = await cache.match(request);
  const fresh = fetch(request).then((r) => {
    if (r.ok) cache.put(request, r.clone());
    return r;
  }).catch(() => cached);
  return cached || fresh;
}

If the user can act on data — pay, delete, submit, approve — stale-by-default is dangerous. Pair it with freshness timestamps and validation before irreversible operations.

Field notes

  • ignoreSearch can collapse ?v=1 and ?v=2 into one entry. Use it only when query parameters do not affect representation.
  • Cache only complete responses. Aborted responses can poison the cache if status and errors are not checked.
  • Authentication cookies still travel with cache misses. Caching is not authorization.
  • The Cache API has no useful built-in byte budget. Track size and obsolete versions yourself.
  • A high hit rate for stale critical data is not a success metric.

Was this lesson helpful?

Sign in to rate