Back to KB
Difficulty
Intermediate
Read Time
8 min

Service Worker Caching Strategies: Cache-First, Network-First, and SWR

By Codcompass Team··8 min read

Related: Network Optimization for SPAs and React Apps covers the broader network optimization picture including HTTP caching and API request optimization.

A service worker is a JavaScript file that runs in a background thread, separate from your main application. It intercepts every network request your page makes and can respond from cache, modify the request, or let it pass through to the network unchanged. For a returning visitor, a well-configured service worker means many requests never touch the network at all. The page loads from cache at local disk speed.

What this covers: What service workers can and cannot do, the three core caching strategies (cache-first, network-first, stale-while-revalidate), when each strategy is correct for which resource type, and how Workbox makes implementing these strategies practical without writing the interception logic by hand.

Diagram showing three caching strategies: cache-first serving from cache immediately, network-first checking network before cache, and stale-while-revalidate serving cache then updating in background.


What a service worker actually does

A service worker is registered by your application JavaScript and installed by the browser. Once installed, it intercepts all network requests made from pages on its origin. This includes requests for HTML, CSS, JavaScript, images, fonts, and API calls.

// Register the service worker from your main application
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}

Enter fullscreen mode Exit fullscreen mode

The service worker file (sw.js) runs in a separate worker thread. It has access to the Cache Storage API, which is separate from the HTTP cache the browser manages automatically. The Cache Storage API is under your complete control: you decide what to cache, when to cache it, how long to keep it, and when to delete it.

// Inside sw.js: intercept a fetch event and respond from cache
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(cachedResponse => {
      if (cachedResponse) {
        return cachedResponse; // Serve from cache
      }
      return fetch(event.request); // Fall through to network
    })
  );
});

Enter fullscreen mode Exit fullscreen mode

This is the basic cache-first pattern in raw form. Every real application needs more nuance: what if the cache is stale? What if certain resources should never be served from cache? What if the network is unavailable? Writing and maintaining all of this logic by hand is error-prone, which is why Workbox exists.


Strategy 1: Cache-First

Cache-first means: check the cache first. If a response is in cache, return it immediately without hitting the network. Only go to the network if the resource is not in cache.

Use this for: Versioned static assets. JavaScript bundles, CSS files, images, and fonts that have content hashes in their filenames (main-a1b2c3.js).

🎉 Mid-Year Sale — Unlock Full Article

Base plan from just $4.99/mo or $49/yr

Sign in to read the full article and unlock all 635+ tutorials.

Sign In / Register — Start Free Trial

7-day free trial · Cancel anytime · 30-day money-back