← All Tools

Service Worker Cache Strategy Generator

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.

Global config

Runtime route strategies

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.

Generated files


  
Heads up: Service Workers only run over HTTPS (or 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.

Which strategy to use for what

StrategyBest forHow it behaves offline
cache-firstVersioned 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-firstHTML 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-revalidateAvatar 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-onlyAuth 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-onlyPre-cached resources you know are in cache and never change.Serves only from cache. Errors if not precached.