OpenChat icon indicating copy to clipboard operation
OpenChat copied to clipboard

Service worker is built but never registered

Open ajanraj opened this issue 1 month ago • 0 comments

Problem

The build generates sw.js and registerSW.js, but no page loads registerSW.js or calls navigator.serviceWorker.register, so no service worker is ever installed. Precaching, registerType: "autoUpdate" and the Google Fonts runtime caching in vite.config.ts all do nothing.

Repro

NODE_ENV=production bun run build
NODE_ENV=production bunx vite preview
  • GET /sw.js and GET /registerSW.js return 200.
  • The HTML for / includes <link rel="manifest" href="/manifest.json"/>, but nothing mentions registerSW, serviceWorker or sw.js.
  • Nothing in src/ imports virtual:pwa-register, and nothing in git history ever did.

Checked on main (17ade4e). #87 (vite-plugin-pwa 2.0) uses the same injection logic.

Cause

VitePWA defaults to injectRegister: "auto". Without a virtual:pwa-register import, that resolves to "script", which adds <script src="/registerSW.js"> in Vite's transformIndexHtml hook. TanStack Start renders HTML on the server and has no index.html, so the hook never runs and the tag is never added.

Expected

Production pages register /sw.js.

Possible fixes

  • Register from the app: set injectRegister: false and call registerSW({ immediate: true }) from virtual:pwa-register in client-only code, such as an effect in the root component.
  • Or add { src: "/registerSW.js" } to the root route's head().scripts in src/routes/__root.tsx.

Before fixing:

  • Fix #89 first or in the same change. /sw.js isn't deployed on Vercel today, so registration there would fail.
  • Turning the service worker on means every first visit downloads the whole precache in the background: 681 entries (~24 MB) in CI's build of main. globPatterns may need trimming.

ajanraj avatar Oct 16 '26 21:10 ajanraj