Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: A News Reader with Caching Strategies

Build a news reader PWA that mixes network-first pages, stale-while-revalidate data, cache-first images, cache limits, saved articles and push alerts, with a runnable strategy router.

A news reader is the classic test of caching judgment, because each kind of content needs a different rule. Headlines must be fresh. Article text can be a few minutes old. Images never change. Fonts and scripts have hashed names and last forever. And the user wants to read saved stories on a plane. In this project you will assign a strategy to each request type, write a router that applies them, limit how much the cache can grow, and add "save for offline" and breaking-news alerts.

The earlier chapters introduced the strategies one by one; here you combine them. Because real service workers cannot run in the preview, the router is written so that its decisions can be tested with fake Cache and fetch objects, and the exact same logic goes into sw.js.

Choose a strategy per request

Request Strategy Why
HTML pages (navigations) Network first, fall back to cache, then offline page Fresh when online, readable when not
/api/headlines Stale-while-revalidate Show instantly, update in the background
/api/articles/{id} Cache first for saved articles, otherwise network first Saved means available offline
Images Cache first, max 60 entries Large and immutable
/assets/*.hash.js, fonts Cache first (precached) Names change when content changes
Everything else Network only Unknown requests are not worth guessing
flowchart TD
  R["fetch event"] --> A{"Request type"}
  A -->|"navigate"| N["Network first"]
  A -->|"/api/headlines"| S["Stale while revalidate"]
  A -->|"image"| C["Cache first + trim"]
  A -->|"hashed asset"| P["Cache first"]
  A -->|"other"| O["Network only"]

The strategies as small functions

Each strategy takes a request, a cache and a network function. Passing them in makes them easy to test.

JS Strategies and a router, with fakes

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

No output.

Read the trace column carefully: it is the evidence that each strategy does what the table promises. The same trick (a trace of where each response came from) is invaluable when debugging a real worker; add a custom X-Served-From header in development.

Keep the cache bounded

Image caches can grow without limit. Trim them after each addition so the oldest entries go first:

JavaScript
async function trimCache(name, maxEntries) {
  const cache = await caches.open(name);
  const keys = await cache.keys();                       // insertion order
  for (const request of keys.slice(0, Math.max(0, keys.length - maxEntries))) {
    await cache.delete(request);
  }
}
JS Trimming a cache to its limit

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

No output.

For real LRU behavior, move an entry to the end whenever it is read. Workbox's ExpirationPlugin implements maxEntries and maxAgeSeconds for you, and the CacheableResponsePlugin makes sure only good responses (status 200, or 0 for opaque) are stored.

Save for offline

The most important feature is the user's own choice. A "Save" button copies the article and its images into a dedicated cache that the trimming code never touches:

JavaScript
// page code
async function saveArticle(id, imageUrls) {
  const cache = await caches.open("saved-v1");
  await cache.addAll([`/articles/${id}`, `/api/articles/${id}`, ...imageUrls]);
  await db.saved.put({ id, savedAt: Date.now() });      // list shown on the "Saved" screen
}

The router checks saved-v1 first for article requests (caches.match(request, { cacheName: "saved-v1" })), so saved stories open instantly offline. Show a "Saved" badge so users trust it, and an easy way to remove items. Ask the browser for persistent storage the first time the user saves something, so saved stories are not evicted.

Breaking news push

A reader has a natural reason for notifications: a story the user follows changed. Use a push subscription per topic, send a short payload (title, summary, article ID), and use the notification tag so a developing story updates one notification instead of adding five. The click handler opens the article; if the page is already open, it focuses it. See notification design.

Quality bar

  1. Lighthouse performance 90 or more on a mobile profile, LCP under 2.5 s (see Lighthouse audits).
  2. Offline test: every saved article opens in airplane mode, unsaved ones show a clear offline message.
  3. Stale data labeled: when the headlines come from the cache, show "Updated 12 min ago".
  4. The cache total stays under about 50 MB in a one-hour browsing test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which strategy fits a headlines API that should show instantly but stay fresh?

    It returns the cached copy at once and updates the cache from the network in the background.
  2. 2. Why cache hashed assets with cache-first?

    A changed file gets a new hashed name, so a cached URL is always correct.
  3. 3. Why put saved articles in a separate cache?

    Separate caches have separate policies. User-saved content must be protected from automatic eviction rules.
  4. 4. What does a trace of 'where it came from' help with?

    It makes the effect of each strategy visible during development.

Summary

  • Map each request type to the right strategy; keep the mapping in one small router.
  • Write strategies as plain functions that take a cache and a network function so they can be tested.
  • Bound growth with trimming or Workbox expiration plugins.
  • Protect user-saved content in its own cache and ask for persistent storage.
  • Label stale data, and use tagged notifications for updates.

Next: PWA Checklist and Practice