Register and apply a service worker update
Follow one service worker release from generation to an accepted waiting update.
Table of contents
APIs used
- sw
- Provides the server build entry point for service worker assets.
- SwRuntimeManager
- Exposes installing, registration, waiting and updateAvailable state and manages service worker updates.
Run this recipe
- Starting project
- Start with a Valyrian.js browser project served from localhost or another origin where service workers are available.
- File
- Place the sw(...) call in the build entry and the SwRuntimeManager code in the browser entry.
- Run
- Run the project build, serve its public directory, open the served URL and call applyReadyUpdate after updateavailable is reported.
- Observable result
- The browser registers /sw.js, reports a waiting update and applies it when the application calls applyUpdate().
1. Generate the service worker
Generate public/sw.js during the application build. Update the version when a release changes cached assets.
jsimport { sw } from "valyrian.js/node";
import pkg from "./package.json" with { type: "json" };
sw("./public/sw.js", {
version: pkg.version,
name: "my-app-cache",
criticalUrls: ["/", "/index.html", "/assets/app.js"],
optionalUrls: ["/offline.html"],
offlinePage: "/offline.html",
});2. Observe the update lifecycle
Run this browser entry after generating and serving /sw.js. init registers the configured worker. The handlers expose registration, available update, completed update and failure states.
tsimport { SwRuntimeManager } from "valyrian.js/sw";
const runtime = new SwRuntimeManager({
swUrl: "/sw.js",
strategy: "prompt-user",
});
const reportState = (event) => console.log(event, runtime.state);
const reportError = (error) => console.error("service worker", error);
runtime.on("registered", () => reportState("registered"));
runtime.on("updateavailable", () => reportState("updateavailable"));
runtime.on("updated", () => reportState("updated"));
runtime.on("error", reportError);
await runtime.init();
await runtime.checkForUpdate();
export function applyReadyUpdate() {
if (runtime.state.updateAvailable) {
runtime.applyUpdate();
}
}3. Apply the update
Call applyReadyUpdate after the application accepts the update. With prompt-user, the application decides when to apply the waiting worker.