Skip to main content

2026-11-27 · 3 min read

Offline reading for a blog with a service worker: network-first, so stale caches never win

PerformanceNext.js

Translated from the Chinese original: read it in Chinese

The site has had a PWA manifest for a long time but never a service worker, so "Add to Home Screen" was only an icon, and with no network you got a blank page. A blog is the best kind of content for offline: read a post once, and when you want to look at it again on a commute with no signal, it should open.

Strategy: network-first, not cache-first

The classic disaster of offline caching is "I deployed a new version and fixed a post, but users keep seeing the old one". This site deploys many times a day and posts get edited, so I chose network-first:

  1. With a network: always ask the server for the latest, and on success save that copy;
  2. If there is no answer in 5 seconds or it cannot connect: use the copy saved last time;
  3. If it was never read and there is no network: show a static offline page.

That way an old cache never "beats" new content; it is only a fallback for when the network is down. The cost: only pages "read after the service worker took over" are saved, so the very first visit is not, and there is no proactive pre-download of all posts.

Only two kinds of things are saved:

  • Pages under /blog and /blog/* (up to 60 copies, only normal responses with status 200; the maintenance page returns 503 and is not saved, so that maintenance does not wipe out good posts)
  • /_next/static/*: JS, CSS and fonts whose file names carry a hash and whose content never changes, cache-first. A post page needs them for styling when offline

Which requests must never be touched

A service worker intercepts requests across the whole site scope, so I list what it does not handle: non-GET, other origins, /api, /admin, /login, /go (redirect stats), /cdn-cgi (Cloudflare's login flow), and sw.js itself. Admin pages, login state and click counting must never be cached or rewritten.

Trap 1: Cloudflare caches sw.js

Browsers check by themselves whether sw.js has changed, and that is fine. But the site sits behind Cloudflare, which by default caches .js files as static. If I change sw.js later, the browser may keep getting the old one from Cloudflare and the new strategy never goes out (I handled this preventively and have not actually hit it). The fix is to add a header just for /sw.js in next.config.ts:

{ source: "/sw.js", headers: [{ key: "Cache-Control", value: "private, no-cache, max-age=0, must-revalidate" }] }

The CSP did not need changing: the site already had worker-src 'self'.

Register only in production

In development mode, every save recompiles, and if a service worker caches that as well, debugging gets very painful. CI's E2E also runs in development mode. So the registering component acts only when NODE_ENV === "production", and it waits until the page has loaded and the browser is idle before registering, so it does not fight the home page's LCP for bandwidth.

How to verify offline: Playwright's setOffline

Playwright can switch the browser environment to offline, which is just what a test needs. One detail in the flow: the first time a page loads, the service worker has not taken over yet, so that request is not saved. The test therefore loads twice:

await page.goto("/blog/task-scheduler-72-hours");           // triggers registration
await page.evaluate(() => navigator.serviceWorker.ready);
await expect.poll(() => page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true);
await page.goto("/blog/task-scheduler-72-hours");           // this one goes through the SW and is saved
await context.setOffline(true);
await page.goto("/blog/task-scheduler-72-hours");           // offline, should still open

Offline, the title of the same post has to match the online one; opening a post never read before should show the offline page. I ran this on a production build and both passed. In CI this test skips automatically (CI runs in development mode, where the service worker is never registered), so it only runs when I verify a production build locally.

Summary

  • For a site whose content changes often, use network-first: the old cache is only a fallback for when the network is down
  • List what is not handled: admin, API, login, third parties; save only responses with status 200
  • Static files with a hash use cache-first, so the offline page has its styles
  • With a CDN in between, make sure sw.js is not cached
  • Do not register in dev; in tests, "load twice" before going offline

Type to search projects and posts too