Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Caching Strategies

The Network First Strategy

Learn the network-first (network falling back to cache) strategy: fresh content when online, saved copies when offline, with timeouts, code and use cases for HTML and APIs.

Some content must be fresh whenever possible: a news feed, an account page, an inventory count, the HTML of your pages. Yet you still want the app to work offline. Network first (also called "network falling back to cache") does exactly that: always try the network, store the successful response, and only if the network fails return the last saved copy.

flowchart TD
  R["Request"] --> N["Try the network"]
  N -->|"OK"| S["Update the cache copy"]
  S --> O["Return network response"]
  N -->|"Failed or slow"| C{"In cache?"}
  C -->|Yes| H["Return cached response"]
  C -->|No| E["Offline page or error"]

The user gets fresh data when the connection works and the last known data when it does not.

The basic code

JavaScript
async function networkFirst(request) {
  const cache = await caches.open('pages-v1');
  try {
    const response = await fetch(request);
    if (response.ok) cache.put(request, response.clone());
    return response;
  } catch (error) {
    const cached = await cache.match(request);
    if (cached) return cached;
    throw error;            // nothing to fall back to
  }
}

The only difference from cache first is the order of the two steps, but the consequences are very different:

Cache first Network first
Speed when online Instant As slow as the network
Freshness Possibly stale Always fresh if online
Offline Works Works, with last copy
Best for Immutable assets Pages and changing data

The slow network problem

Network first has one weakness: a connection that is not off but terrible (the "lie-fi" case on trains or in elevators). fetch may hang for 30 seconds or more before failing, and the user stares at a blank page even though a cached copy is right there.

The cure is a timeout: if the network does not answer within a short limit (say 3 seconds), return the cached copy instead.

JavaScript
function timeout(ms) {
  return new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms));
}

async function networkFirstWithTimeout(request, ms = 3000) {
  const cache = await caches.open('pages-v1');
  try {
    const response = await Promise.race([fetch(request), timeout(ms)]);
    if (response.ok) cache.put(request, response.clone());
    return response;
  } catch (error) {
    return (await cache.match(request)) || Response.error();
  }
}

A refinement: abort the slow fetch with an AbortController so it does not keep consuming bandwidth, or let it finish in the background and update the cache for next time (which is basically stale-while-revalidate, the next lesson).

Try it: network first with a timeout

This stand-in simulates three conditions: a fast network, a slow one and a dead one. You can change the latency numbers and the timeout.

JS Stand-in: network first with timeout

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note how the slow case returns after about 300 ms with the cached copy, while the fast case updates the saved copy. After the first line, the saved news is fresh.

Network first for navigations and the offline page

The most common use is for HTML documents: users always get the newest page when connected, and the last visited pages when not. Add the offline page as the final fallback.

JavaScript
async function pageStrategy(request) {
  try {
    const response = await fetch(request);
    const cache = await caches.open('pages-v1');
    cache.put(request, response.clone());
    return response;
  } catch (error) {
    return (
      (await caches.match(request)) ||
      (await caches.match('/offline.html'))
    );
  }
}

self.addEventListener('fetch', (event) => {
  if (event.request.mode === 'navigate') {
    event.respondWith(pageStrategy(event.request));
  }
});

Only pages the user already visited are available offline. If you want specific pages (a reading list, last viewed articles) to be available, store them explicitly, for example from the page with postMessage to the worker, or with a "Save for offline" button that calls cache.add(url).

A subtle cost: when a service worker is not yet running, starting it takes time (tens to hundreds of milliseconds). For a network-first navigation that delays the request itself. Navigation preload fixes this: the browser starts the request in parallel with the worker's startup and hands you the result as event.preloadResponse.

JavaScript
self.addEventListener('activate', (event) => {
  event.waitUntil(self.registration.navigationPreload?.enable());
});

self.addEventListener('fetch', (event) => {
  if (event.request.mode !== 'navigate') return;
  event.respondWith((async () => {
    try {
      const preloaded = await event.preloadResponse;
      if (preloaded) return preloaded;
      return await fetch(event.request);
    } catch {
      return (await caches.match(event.request)) || caches.match('/offline.html');
    }
  })());
});

Use this for network-first pages; it makes your PWA's navigations as fast as a site without a service worker.

Network first for API data

For JSON APIs the same idea applies, but be explicit about what fallback data means to the user. A stale list of orders is useful; a stale account balance can be misleading. Common practice:

  • Return the cached response but add a header or message so the UI shows "Showing saved data from 10:42".
  • Keep a timestamp with each cached API response.
  • Cache only GET requests; mutations (POST, PUT, DELETE) need the background sync approach of chapter 5.

You can stamp the cached response with the time it was stored by building a new response with an extra header:

JavaScript
function stamp(response) {
  const headers = new Headers(response.headers);
  headers.set('x-cached-at', new Date().toISOString());
  return response.blob().then((body) => new Response(body, {
    status: response.status, statusText: response.statusText, headers,
  }));
}

The page then reads response.headers.get('x-cached-at') and shows a message.

JS Stamp a response with a cache time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pitfalls

  • Slow connections without a timeout make the app feel broken. Always add one for pages.
  • Caching private data (account pages) is a privacy risk on shared devices. Clear user-specific caches on logout, and never cache responses that should not be stored.
  • Caching redirects or error pages: check response.ok and response.redirected where relevant.
  • Unbounded caches: every page visited stays in the cache; trim it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In network first, when is the cached copy used?

    The network is tried first; the cache is the fallback.
  2. 2. What problem does a timeout solve in network first?

    Slow but not failing connections can hang for a long time; a timeout switches to the cache.
  3. 3. Which resource is a good fit for network first?

    Pages and live data benefit from freshness with an offline fallback.
  4. 4. What is navigation preload for?

    It removes the worker startup delay from network-first navigations.

Summary

  • Network first tries the network, updates the cache on success and falls back to the cache on failure.
  • Add a timeout so slow connections do not block the user.
  • Ideal for HTML documents and API data; combine with an offline page as the last fallback.
  • Enable navigation preload to avoid the worker startup penalty.
  • Mind privacy and cache growth for stored pages and responses.

Next: Stale-While-Revalidate