Caching Strategies: How to Save Data

Caching Strategies: How to Save Data in JavaScript: Choosing a caching strategy is like packing for a trip. Cache-First: Great for icons and fonts.

Concept Explanation

Choosing a caching strategy is like packing for a trip.

  • Cache-First: Great for icons and fonts. They never change, so always take them from the cache to be fast.
  • Network-First: Great for news or weather. You want the freshest data, but you'll take the old data from the cache if the internet is down.
  • Stale-While-Revalidate: The "Speed Ninja" strategy. Give the user the old data immediately, but secretly fetch the new data in the background to update the cache for next time.

There is no single best answer, because every strategy is a bet on the same trade-off: speed versus freshness. The right bet depends entirely on what happens if the user sees data that is five minutes old. For a logo, nothing. For an account balance, a support ticket.

Two more worth knowing: Network-Only for anything you must never cache (payments, auth), and Cache-Only for content you deliberately shipped with the build and will replace on the next deploy.


Syntax or Core Structure

Cache-first, with a write-through

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

  const response = await fetch(request);
  const cache = await caches.open('assets-v1');
  cache.put(request, response.clone());   // clone: body is single-use
  return response;
}

Network-first, with an offline fallback

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

Stale-while-revalidate

async function swr(request) {
  const cache = await caches.open('feed-v1');
  const hit = await cache.match(request);
  const fresh = fetch(request).then((res) => {
    cache.put(request, res.clone());
    return res;
  });
  return hit || fresh;      // answer instantly if we can, refresh regardless
}

Choosing a Strategy

ContentStrategyWhy
Fonts, icons, hashed JS/CSSCache-firstThe filename changes when the content does
HTML documentsNetwork-firstNever pin users to an old build
Social feed, product listStale-while-revalidateInstant paint, fresh on next view
Account balance, checkoutNetwork-onlyWrong beats slow here
Offline fallback pageCache-onlyIt exists precisely for when the network does not

Real World Example

Instagram: When you open the app, it instantly shows you the last 5 posts from your cache. While you are looking at them, it's secretly downloading the newest ones. This makes the app feel "Instant."

That is stale-while-revalidate, and the reason it works socially as well as technically is that a feed being two minutes out of date costs the user nothing. Apply the same strategy to a bank balance and you have manufactured a support call.


Common Mistakes

  • Reusing a response body twice. cache.put(req, res) followed by return res fails; the body was already consumed. Always clone() first.
  • Cache-first on HTML. The classic PWA bug: the app updates on the server and users never see it.
  • Unbounded caches. Caching every image a user ever scrolls past will eventually get your whole origin evicted. Cap entries and age.
  • Caching error responses. Check response.ok before storing, or you will happily serve a cached 500 for a week.
  • Caching opaque cross-origin responses without thought. They have status 0 and you cannot inspect them, so failures become invisible.
  • Ignoring Vary. Cached responses can be served to requests that should have received a different variant.

Best Practices

  • Pick the strategy per request type inside one fetch handler, keyed off request.destination or the URL path.
  • Set an expiry and a maximum entry count for anything user-generated.
  • Store API data in IndexedDB rather than Cache Storage when you need to query or merge it.
  • Test with DevTools "Offline" and with throttling, not just on your office connection.
  • Let Workbox implement these strategies; it already handles the clone, the expiry and the edge cases.

Practice Exercises

  1. Strategy Comparison: Create a table comparing the "Cache-First" and "Network-First" strategies. Which is better for a "User Profile Settings" page?
  2. The Cache limit: Research how much space a PWA is allowed to use on a phone (it depends on the browser!).
  3. Workbox: Research "Workbox" by Google and explain why most people use it instead of writing raw Service Worker code.