Service Worker strategies for working without network

Cache-first, network-first, stale-while-revalidate — each strategy fits different data. What to apply where.

Service Worker strategies for working without network

The Service Worker sits between the app and the network. Every request goes through it. A strategy is a rule: what to give the user — cache, network, or some combination.

Service Worker strategies for working without network
The four core strategies — each balances freshness against offline availability.

Cache-first

Look at the cache first. If a hit, serve it. Network only if there is no cache entry.

  • When: static assets (CSS, JS, fonts, icons) that change rarely
  • Pro: instant response, works offline
  • Con: user may see stale version for a while
  • Fix: cache-bust via `?v=` or version the cache name

Network-first

Try the network. If it fails, fall back to cache.

  • When: HTML pages, APIs with live data (account balance, order status)
  • Pro: always fresh when network is available
  • Con: on slow network you wait for the timeout before fallback
  • Fix: race against a 3-5 second timeout via Promise.race

Stale-while-revalidate

Serve cache immediately, refresh cache from network in the background.

  • When: lists, feeds, dashboards, avatars — anywhere yesterday's data is fine while fresh data loads
  • Pro: instant UI plus fresh data on next visit
  • Con: user sees old version until reload
  • Fix: notify the UI that an update arrived via postMessage from the SW

Network-only

No cache. Always network.

  • When: payments, auth, OAuth callbacks, analytics
  • Pro: safe, accurate
  • Con: offline does not work

Cache-only

Cache only. Pure offline mode.

  • When: precached static assets that must be present after install
  • Add the precache list at the SW `install` event

In practice

One PWA usually runs 3-4 strategies in parallel — different URL patterns get different rules. Workbox from Google handles this declaratively. Or write 100 lines of plain JS yourself.