Proposal: Add a Service Worker to the Workshop frontend #158
samkelleher
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Add production Service Worker support to
packages/workshop-frontendusingvite-plugin-pwa(generateSW). Static assets are precached and served Cache-First. WithregisterType: 'autoUpdate', new builds activate viaskipWaiting/clientsClaimand open clients reload onto the new revision without an in-app update prompt.Motivation
Workshop is a long-lived SPA. Without a Service Worker, every navigation and cold load re-fetches hashed assets, and there is no structured way to roll a new deploy under an already-open tab. Precaching improves repeat-load performance;
autoUpdateplusvirtual:pwa-registeravoids leaving clients stuck on an old in-memory build when/sw.jschanges.After implementing this change, Cloudflare OS, can be installed as an desktop windowed app (in most browsers) and it starts instantly with no load time. It really makes this a first class experience.
Approach
Use the default
generateSWstrategy. Registration goes throughvirtual:pwa-registerwithimmediate: trueso:window.load).injectRegisteralone registers but does not reload open clients).The web app manifest is declared in the Vite PWA plugin config so install metadata and the Service Worker ship from one place.
Dependencies
In
packages/workshop-frontend:workbox-windowis a peer ofvite-plugin-pwaand must be declared on the package that importsvirtual:pwa-register(pnpm will not hoist it otherwise).vite.config.ts(drop-in)Replace the package Vite config with:
Place
pwa-192x192.pngandpwa-512x512.pngunderpublic/(or adjust theiconspaths). The plugin emits the web manifest and injects the corresponding<link rel="manifest">at build time.Entry point registration
At the top of
src/main.tsx:For TypeScript, either add
"vite-plugin-pwa/client"tocompilerOptions.types, or declare the virtual module insrc/vite-env.d.ts.Static asset headers
/sw.jsmust revalidate so clients discover new precache manifests promptly. Hashedworkbox-*.jsfiles sit next tosw.js(Workbox does not emit them underassets/) and are content-addressed, so they may use long-lived immutable caching—same policy as other hashed build outputs.Example (Workers static-assets
_headersstyle):Behaviour notes
/api,/gatekeeper,/blueprint-screenshotoff the SPA fallback/sw.js→ install →skipWaiting/clientsClaim→ client reload viavirtual:pwa-registerdevOptions.enabledunset/false; SW is a production build concernOut of scope / follow-ups
registerType: 'prompt') if forced reload is undesirable for long sessions.injectRegister: 'script' | 'inline'as a lighter alternative that registers without reloading open clients.All reactions