Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Caching Strategies

The Cache First Strategy

Learn the cache-first (cache falling back to network) caching strategy: how it works, ideal use cases, code, pitfalls with stale files and how to combine it with versioning.

A caching strategy is a rule for answering a request using the cache, the network or both. Choosing the right strategy per kind of resource is the difference between a PWA that feels instant and one that serves stale data. This lesson covers the simplest and fastest: cache first, also called "cache, falling back to network".

The idea: look in the cache. If the file is there, return it immediately and never touch the network. If not, fetch it from the network, store a copy for next time, and return it.

flowchart TD
  R["Request"] --> C{"In cache?"}
  C -->|Yes| H["Return cached response (no network)"]
  C -->|No| N["Fetch from network"]
  N --> S["Store a copy in the cache"]
  S --> O["Return response"]

Cache first is the fastest strategy for anything that rarely changes.

The code

JavaScript
async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;

  const response = await fetch(request);
  if (response.ok) {
    const cache = await caches.open('assets-v1');
    cache.put(request, response.clone());
  }
  return response;
}

self.addEventListener('fetch', (event) => {
  if (event.request.method === 'GET') {
    event.respondWith(cacheFirst(event.request));
  }
});

Let's read it line by line:

  1. caches.match(request) looks through all caches. On a hit, we return right away: this is why the strategy is fast, even offline.
  2. On a miss we call fetch. If it fails (offline), the promise rejects and the page gets a network error. You can catch it and return a fallback (below).
  3. We store a copy only if response.ok, so a 404 or 500 does not poison the cache.
  4. response.clone() is needed because the body can be read once.
  5. We do not await cache.put before returning: the page gets its answer sooner. In a real fetch handler, wrap that put in event.waitUntil so the worker is not stopped before it finishes.

When to use it

Cache first is right for resources that never change at a given URL:

  • Fingerprinted build files like app.3f9a1c.js or logo.a81b.svg.
  • Web fonts.
  • Icons and static images.
  • Versioned third-party libraries (/lib/chart-4.4.1.js).

In all these cases the URL itself changes when the content changes, so a cached copy is never wrong.

When NOT to use it

  • HTML pages, unless you accept showing yesterday's page. A cache-first navigation can trap users on old pages for as long as the cache lives.
  • API data that changes (a feed, a cart, prices).
  • Unversioned file names such as /app.js with changing content. You need cache-busting (a version in the cache name) or a different strategy.

If the cached copy is stale you have no automatic way to learn about it: nothing checks the network. That is the cost of speed.

Adding an offline fallback

When nothing is cached and the network fails, return something helpful instead of an error.

JavaScript
async function cacheFirstWithFallback(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  try {
    const response = await fetch(request);
    if (response.ok) {
      (await caches.open('assets-v1')).put(request, response.clone());
    }
    return response;
  } catch (error) {
    if (request.destination === 'image') {
      return caches.match('/img/placeholder.svg');
    }
    if (request.mode === 'navigate') {
      return caches.match('/offline.html');
    }
    return new Response('Offline', { status: 503, statusText: 'Offline' });
  }
}

Precache /img/placeholder.svg and /offline.html during install, so the fallbacks exist.

Running a cache-first strategy

Here is the strategy with fake network and cache objects, so you can run it and watch what happens: the first request goes to the network and fills the cache, the second is served from cache, and a failing network is handled.

JS Stand-in: cache first with a fake network

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

No output.

Count the network requests at the end: only three of the six lookups reached the network, and the repeated 404 was never cached so it was fetched again.

Cache first and stale files

The danger is a cached file that should have changed. There are three standard remedies.

  1. Change the URL. Fingerprint file names or add a version query (/app.js?v=42). The new URL misses the cache, gets fetched, and cached.
  2. Change the cache name. Put the version in the cache name (assets-v2) and delete older caches on activate. Precache the new files on install.
  3. Expire entries. Store a timestamp and ignore entries older than a limit (below).

A runnable example of option 3 with a maximum age shows the idea:

JS Stand-in: cache first with a maximum age

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

No output.

In a real worker, store the timestamp in a custom response header (x-saved-at) or in IndexedDB. Workbox's ExpirationPlugin does this for you.

Cache first for navigations: the trap

A common beginner setup is caches.match(request) || fetch(request) for everything, including HTML. It works great in testing and then you ship an update and users keep seeing the old page, because the cached HTML still points to old fingerprinted files, and nothing triggers a refresh. If you use cache first for pages, you must version the caches and have an update flow (see Service Worker Updates). Otherwise prefer network first or stale-while-revalidate for documents.

Combining with precaching

Cache first plus precaching is the foundation of the app shell: files named in the install step are already in the cache when the first fetch happens, so the strategy never needs the network for them. Runtime caching (the code above) covers files that were not precached, like images the user happens to view. See Precaching and Cache Versioning.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cache first do on a cache hit?

    A hit is answered from the cache immediately; the network is never used.
  2. 2. Which resource is best suited to cache first?

    Fingerprinted files never change at a given URL, so a cached copy is always correct.
  3. 3. Why check response.ok before caching?

    put does not validate status; storing an error would serve it again and again.
  4. 4. What is the main risk of cache first?

    Speed comes from skipping the network, so staleness must be handled with versioning or expiry.

Summary

  • Cache first returns the cached response if present and falls back to the network otherwise, storing the result.
  • Use it for immutable, fingerprinted or rarely changing assets: fonts, icons, build files.
  • Avoid it for HTML and live data unless you have versioning and an update flow.
  • Handle offline misses with a fallback response, store only OK responses, and clone before caching.
  • Fight staleness by changing URLs, cache names or by expiring entries.

Next: The Network First Strategy