Build a complete sw.js with a different caching strategy per URL pattern — precache the shell, stale-while-revalidate for images, network-first for the API, and a clean offline fallback page. Bumping CACHE_VERSION blows away the old cache on the next activate.
Each route matches by URL substring, prefix, or regex. The first route that matches the request URL wins. Anything that matches no route falls through to network.
localhost). Browsers cache sw.js aggressively — most respect a 24-hour TTL maximum, but you should serve sw.js with Cache-Control: max-age=0, must-revalidate to be safe. Always bump CACHE_VERSION when you change the precache list, or users will keep seeing stale files until they close every tab.
| Strategy | Best for | How it behaves offline |
|---|---|---|
cache-first | Versioned static assets (hashed JS/CSS, fonts, images that never change). | Serves cached copy instantly; only hits network on cache miss. Fastest. Cache never auto-refreshes — relies on URL changing. |
network-first | HTML pages, JSON APIs where freshness matters more than speed. | Tries network; on failure (timeout or offline) falls back to cache. Slower when online; resilient when not. |
stale-while-revalidate | Avatar images, news feeds, comment counts — anything where slightly stale is fine but you want updates. | Serves cached copy instantly while fetching a fresh one in the background for next time. Best UX for non-critical content. |
network-only | Auth endpoints, analytics, anything that must never be cached. | Always fetches from network. Throws / fails offline — useful for endpoints where stale data is wrong data. |
cache-only | Pre-cached resources you know are in cache and never change. | Serves only from cache. Errors if not precached. |