← All posts

· 9 min read

Making an SSR React App a PWA Without Breaking the Server

PWAs and SSR are not natural allies

A Progressive Web App's service worker is a network proxy that lives in the browser. It intercepts fetch requests, can serve cached responses, and enables offline mode. This is enormously valuable for static apps. For a server-rendered app, the relationship is more complicated.

The core problem: SSR relies on every navigation request reaching the server. If the service worker intercepts a navigation request and returns a cached HTML shell, the server never runs — and the user gets stale content, or worse, a blank page where the server would have rendered a 404.

The navigateFallback trap

Many PWA guides recommend setting navigateFallback to your index.html shell. This is correct for client-side-only SPAs. For SSR, it is the wrong default — it turns every navigation into a cached app-shell response and bypasses the server entirely.

The fix for this project was to set navigateFallback to null in the Vite PWA plugin configuration. Navigation requests always reach the server; only static assets (JS, CSS, fonts, images) are cached by the service worker.

// vite.config.ts
VitePWA({
  injectRegister: false,
  registerType: 'autoUpdate',
  workbox: {
    navigateFallback: null,          // critical for SSR — never cache HTML
    globPatterns: ['**/*.{js,css,woff2,png,svg,ico,webmanifest}'],
    runtimeCaching: [
      {
        urlPattern: /\/assets\/.*/,
        handler: 'CacheFirst',
        options: {
          cacheName: 'assets-cache',
          expiration: { maxAgeSeconds: 60 * 60 * 24 * 365 },
        },
      },
      {
        urlPattern: /\.(woff2|woff|ttf)$/,
        handler: 'CacheFirst',
        options: {
          cacheName: 'fonts-cache',
          expiration: { maxAgeSeconds: 60 * 60 * 24 * 365 },
        },
      },
    ],
  },
  manifest: false,                   // manifest.json is managed by hand
  devOptions: { enabled: false },    // no service worker in dev
})

Caching strategy: cache-first, even for fonts

With navigation excluded from the service worker, the caching strategy for the remaining static assets becomes straightforward. Files with content-hash names — the output of Vite's production build — can be cached cache-first with a one-year expiry. Their hash changes whenever their content changes, so a stale cache is impossible by construction: a new build produces new filenames, which miss the cache and fetch fresh.

It is tempting to reach for stale-while-revalidate for fonts, but for hashed, immutable assets that is strictly worse — it triggers a needless background revalidation for a file that can never change. This project uses two explicit runtimeCaching rules, both cache-first with a one-year expiry: one for everything under /assets/, and one matching .woff2/.woff/.ttf. The globPatterns precache handles the rest at install time.

Owning the manifest

The Vite PWA plugin can generate a web app manifest for you, but here it is disabled with manifest: false and a hand-written public/manifest.json is served instead. The trade-off is deliberate: a hand-managed manifest gives full control over the icon set, theme_color, background_color, and display: standalone without fighting the plugin's generated defaults — and it keeps the manifest reviewable in version control like any other asset.

Updates: autoUpdate and the reload question

With registerType: 'autoUpdate', a newly deployed service worker installs in the background and takes control on the next navigation — no user prompt, no stale bundle lingering across sessions. The alternative, prompt, shows a "new version available — reload?" affordance and hands the timing to the user.

For a content site where every navigation already hits the server, autoUpdate is the right default: only the cached static assets are ever slightly behind, and they are content-hashed, so a mismatch cannot serve broken code. Apps with long-lived client sessions and in-flight state usually prefer the prompt so they never swap assets out from under a user mid-task — that is the case where skipWaiting/clientsClaim semantics matter most.

Registration in development

Service worker registration must be skipped in development mode. A service worker running locally will aggressively cache assets that the dev server is actively changing, leading to confusing situations where source edits seem to have no effect. Guard registration on the production flag (and gate the plugin's own devOptions.enabled to false):

if (!import.meta.env.DEV && 'serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js', { scope: '/' });
}

Install prompt and offline indicator

The browser fires a beforeinstallprompt event when the PWA is eligible for installation. Capturing this event and showing a custom install button — rather than relying on the browser's default prompt — gives more control over when and how the installation is surfaced.

An offline indicator (a simple banner that reacts to the online/offline window events) rounds out the user experience. Static assets will load from cache even offline; dynamic content (server-rendered pages) will show a network error, and the indicator makes clear why.

Verifying it actually works

A service worker never runs against the dev server, so you cannot test it with npm run dev. Build for production and serve the output, then open DevTools → Application → Service Workers to confirm the worker is activated and inspect the Cache Storage buckets (assets-cache, fonts-cache). Two checks matter most: throttle the Network tab to Offline and reload — static assets should still paint, while a server-rendered route shows a clean network error rather than a blank page; and confirm that navigating between pages still produces real server requests (proof that navigateFallback: null is doing its job).

iOS and Safari caveats

PWA support is not uniform. iOS Safari does not fire beforeinstallprompt at all — installation is a manual "Add to Home Screen" action, so a custom install button should be hidden or replaced with instructions on that platform. Add-to-home-screen apps on iOS also historically ran in a more constrained storage and lifecycle context than Android. Treat installability as a progressive enhancement: the site must work perfectly as a normal tab first, with the PWA layer adding value on top.

The bottom line

PWA and SSR coexist well as long as the service worker's scope is correctly bounded. Cache static, content-hashed assets aggressively; let navigations reach the server. The navigateFallback: null setting is the single most important configuration choice — everything else is tuning around it.