PWA and service workers
A service worker is a script the browser runs beside your pages. It can answer requests from a cache, so the app opens offline, and it can receive push messages. Hamur does not run your server inside it. A worker is a file of your app that Hamur builds, types and registers, and @hamur/pwa adds the web app manifest, the icons, the install and update prompts and web push on top.
| You want | You write | Hamur does |
|---|---|---|
| a worker with your own code | app/sw.ts | builds it to sw.js, types it, registers it |
| the app to open offline, and nothing else | serviceWorker: { generate: "precache" } | writes a worker that caches the build's files |
| to remove a worker you shipped earlier | serviceWorker: { generate: "unregister" } | writes a worker that deletes its caches and itself |
| an installable app with icons and prompts | modules: [pwa] (import pwa from "@hamur/pwa") | makes the manifest icons, usePwa |
| push notifications | app/sw.ts with a push listener, @hamur/pwa | subscribePush in the browser, sendPush on the server |
The references are @hamur/pwa and the serviceWorker row of Configuration. A new deploy while tabs are open is its own subject, see Deploys and version skew.
A service worker of your own: app/sw.ts
app/sw.ts (also .mts, .js and .mjs) is the service worker entry. Helper files go in app/sw/, which no scan reads: no routes. hamur build writes one file, .output/public/sw.js, served at <baseURL>sw.js. The name is fixed and has no hash, because a browser finds a new worker by fetching the same URL again. Hamur serves it with cache-control: no-cache; a routeRules entry for /sw.js of your own wins.
The smallest worker caches every file of the build and answers from the cache:
import { precache } from "#hamur/service-worker"
precache({ maxFileSize: 1_048_576 })
Facts about how the file is built and loaded:
- A classic script. The build bundles the entry and its imports into one file, so it is registered without
type: "module", which older Firefox versions refuse for a service worker. - Registration. After hydration, when
"serviceWorker" in navigatorandserviceWorker.registeris notfalse, the client callsnavigator.serviceWorker.register("<baseURL>sw.js", { scope: "<baseURL>" }). A failure is logged once as[hamur] the service worker did not register: <message>. Withregister: falseyou register it yourself. - Scope. The worker controls
<baseURL>and below, with noService-Worker-Allowedheader. It is never served fromapp.cdnURL: a worker must come from the page's origin. - What it may import.
#hamur/service-worker, files inapp/sw/andshared/(#shared/*), and packages other thanhamurand the adapters. A worker has no page and no server, sohamur,hamur/*,@hamur/adapter-*,#server, files belowserver/and files ofapp/outsidesw/fail the build, as doesimport()(a service worker cannot load code that way) and a CSS file. - Conflicts.
app/sw.tswithserviceWorker.generate, andpublic/sw.jswith either, fail the build. Without both,public/sw.jsis an ordinary public file that Hamur neither builds nor registers. hamur dev. The dev server answers<baseURL>sw.jsitself. WithserviceWorker.dev: trueit builds your worker and reloads the page when a file of it changes. With the defaultfalseit answers a worker that unregisters itself, so a production worker left on the same address and port does not answer dev pages from its cache.
The build errors name the file and the import:
| When | Message |
|---|---|
| a forbidden import | app/sw.ts may import only #hamur/service-worker, files in app/sw/ and shared/, and packages other than hamur and its adapters; app/sw/cache.ts imports "#app/utils/format.ts" |
import() | app/sw.ts: a service worker cannot load code with import(); app/sw/cache.ts imports "./strategies" dynamically |
| CSS | app/sw.ts imports app/sw/x.css; a service worker has no document to style |
#hamur/service-worker outside the worker | #hamur/service-worker can be imported only by the service worker (app/sw.ts and app/sw/); <importer> imports it |
| two workers | serviceWorker.generate and app/sw.ts both define the service worker; keep one, and public/sw.js and app/sw.ts both define the service worker; keep one |
#hamur/service-worker
A virtual module that only the worker build resolves. It holds what the build wrote, each file with its revision.
| Export | What |
|---|---|
buildId, baseURL | the build id of the client and the app's base URL |
revision | 16 hex characters that change when the build id or any listed file's URL or bytes change. precache() names its cache with it |
immutable | the files of the build below app.buildAssetsDir: JS, CSS, assets, worker chunks, route manifest and fixed-params files, and files modules emitted. Their URLs start with app.cdnURL when it is set |
publicFiles | the files of public/ and of module public assets, without dotfiles and .well-known/; never sw.js or the version file |
prerendered | each prerendered page by the URL a navigation requests, and on the static preset each payload file |
precache(options?) | adds the listeners of the generated worker, see below |
Each list entry is { url, revision, size }: revision is the SHA-256 of the file's bytes cut to 16 hex characters, size is in bytes. Kept builds of skewProtection.keep are in no list. Under hamur dev the lists are empty, buildId is "dev" and revision is "dev".
Types
When the app has app/sw.ts, hamur typegen writes .hamur/tsconfig.sw.json with the libraries ESNext and WebWorker and no DOM, and .hamur/types-sw/service-worker.d.ts, which declares the module above. The worker is left out of the other contexts, so document.title in app/sw.ts is an error. hamur typegen adds the file to the references of your tsconfig.json when that file has a references array without it, and says so once. Check the worker with tsc -p .hamur/tsconfig.sw.json.
lib.webworker types self as WorkerGlobalScope. A worker that listens for fetch, push or notificationclick shadows it at the top of its module with declare const self: ServiceWorkerGlobalScope;, as the samples below do. Hamur adds no export for that.
precache() and the generated worker
precache({ maxFileSize }) adds four listeners:
installopens the cachehamur-<revision>and adds every file ofimmutableandpublicFilesof at mostmaxFileSizebytes (default 2 MiB), and<baseURL>when it is prerendered, so an installed app starts offline. A fetch that fails fails the install, and the worker that already runs keeps the page.activatedeletes every cache whose name starts withhamur-other than its own, then claims the open pages.message:{ type: "SKIP_WAITING" }callsskipWaiting(). This is whatupdate()ofusePwaposts.fetch, forGETonly:- a precached URL is answered from the cache first;
- a navigation, a payload file and
GET <baseURL>_hamur/fn/<id>go to the network first and fall back to the cached copy when the network fails; - any other
GETof the page's origin (or the CDN's) goes to the network and is stored when the answer saysimmutableincache-control, and served from the cache next time; sw.js, the version file and the other paths below<baseURL>_hamur/without a file extension (islands, components, reports, devtools) are not answered.- Never stored: an answer other than 200, an opaque answer,
cache-control: no-store,text/event-stream, a redirected answer, and a request withrange.
A worker of your own that wants precaching calls precache() and adds its own listeners beside it. A fetch listener of yours that should win over precache()'s must be added before it and call event.stopImmediatePropagation(): precache() answers every other same-origin GET, and a second respondWith throws.
Caching strategies
Hamur does not ship a router with strategies by pattern; you write them. This worker keeps images stale-while-revalidate, answers API calls from the network and falls back to a cached copy, and precaches the rest:
import { baseURL, precache } from "#hamur/service-worker"
declare const self: ServiceWorkerGlobalScope
const IMAGES = "images-v1"
// Registered before precache(), which answers every other same-origin GET; stopping the event keeps a second respondWith from throwing.
self.addEventListener("fetch", (event) => {
const { request } = event
if (request.method !== "GET") return
const url = new URL(request.url)
if (url.origin !== location.origin) return
if (request.destination === "image") {
event.stopImmediatePropagation()
event.respondWith(staleWhileRevalidate(event, request))
} else if (url.pathname.startsWith(`${baseURL}api/`)) {
event.stopImmediatePropagation()
event.respondWith(networkFirst(request))
}
})
precache()
async function staleWhileRevalidate(event: FetchEvent, request: Request): Promise<Response> {
const cache = await caches.open(IMAGES)
const cached = await cache.match(request)
const fresh = fetch(request).then((response) => {
if (response.ok) void cache.put(request, response.clone())
return response
})
if (cached) {
event.waitUntil(fresh.catch(() => undefined))
return cached
}
return fresh
}
async function networkFirst(request: Request): Promise<Response> {
try {
return await fetch(request)
} catch (error) {
const cached = await caches.match(request)
if (cached) return cached
throw error
}
}
Save it as app/sw.ts. The cache images-v1 does not start with hamur-, so precache() leaves it alone when a new build activates; change its name when the shape of what it holds changes.
Generated workers: serviceWorker.generate
generate | What Hamur writes |
|---|---|
false (default) | nothing; app/sw.ts is the worker, or the app has none |
"precache" | sw.js from import { precache } from "#hamur/service-worker"; precache();, the same build as app/sw.ts |
"unregister" | sw.js that calls skipWaiting() on install, and on activate deletes every hamur-* cache and unregisters itself. It reloads no page. The client registers nothing and, after hydration, unregisters the registration of <baseURL> |
Use "unregister" when you drop a worker: browsers that ran it would otherwise keep answering from its old cache.
The keys
| Key | Default | |
|---|---|---|
serviceWorker.register | true | the client registers the worker after hydration |
serviceWorker.dev | false | hamur dev builds and registers the worker; false answers the unregistering worker |
serviceWorker.generate | false | false, "precache" or "unregister" |
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
serviceWorker: {
register: true,
dev: false,
generate: false,
},
})
A wrong value fails at load: serviceWorker.register must be a boolean (got "yes"), the same for dev, and serviceWorker.generate must be false, "precache" or "unregister" (got "workbox").
@hamur/pwa
bun add @hamur/pwa
Add it to modules. Its options are under the pwa key; the manifest stays the core's app.manifest.
import { defineConfig } from "hamur"
import pwa from "@hamur/pwa"
export default defineConfig({
framework: "react",
modules: [pwa],
app: {
manifest: { name: "Todo", short_name: "Todo", theme_color: "#102030", background_color: "#ffffff" },
},
pwa: {
registerType: "prompt",
icons: { source: "app/pwa-icon.png", maskable: "app/pwa-maskable.png", sizes: [192, 512], apple: true },
},
serviceWorker: { generate: "precache" },
})
| Key | Default | |
|---|---|---|
pwa.registerType | "prompt" | "prompt": a new worker waits until update(). "autoUpdate": the page posts SKIP_WAITING at once, and needRefresh stays false |
pwa.icons | false | false, or { source, maskable?, sizes?, apple? }: icons made from one source image |
pwa.icons.source | required | a square PNG, JPEG or WebP file, path from the root, at least as large as the largest size |
pwa.icons.maskable | none | a second source, drawn with the safe zone of a maskable icon |
pwa.icons.sizes | [192, 512] | integers from 48 to 1024 |
pwa.icons.apple | true | also make a 180 by 180 icon and link it as apple-touch-icon |
What the module does:
- The manifest. It sets
app.manifest.displayto"standalone"when the manifest is unset or has nodisplay, appends its icons toapp.manifest.iconsand keeps every member you set. Withapp.manifest: falseit adds no manifest. There is nopwa.manifestkey. Hamur serves the manifest at<baseURL>manifest.webmanifestand links it from every document. theme-color. When the manifest hastheme_colorandapp.headhas notheme-colormeta, the module adds one.- No worker. The module sets no
serviceWorkerkey. Without a worker the app can still be installed in Chrome, butneedRefreshandofflineReadystayfalse. - Icons. Each size is resized with
Bun.Imageand written aspwa-icon-<size>-<hash>.pngbelowapp.buildAssetsDir, so it is cached for a year.maskablegivespwa-maskable-<size>-<hash>.pngwithpurpose: "maskable". Hamur does not pad a plain image into a maskable one, because unpadded art is cropped by the platform: draw the maskable source yourself. Anapp/apple-icon.*file wins over the generated apple icon. - Bad sources fail the build with the key first:
pwa.icons.source: app/pwa-icon.png does not exist,... is not a PNG, JPEG or WebP file,... is 512x400; an app icon is squareand... is 256x256; the largest size, 512, needs a source at least that large.pwa.icons.maskablefails the same way under its own key. - Load errors:
pwa.registerType must be "prompt" or "autoUpdate" (got "auto"),pwa.icons must be an object or false (got "icon.png"),pwa.icons.sizes must be a non-empty array of integers from 48 to 1024 (got [0]), andpwa.icons.<key> is not an option; use source, maskable, sizes, apple. hamur devmakes the icons at start and restarts when a source file changes.
usePwa
usePwa() is in @hamur/pwa/<library>, with the same name in all six. It returns three flags and two actions.
offlineReady | a service worker is active and controls the page |
needRefresh | a new worker is installed and waiting while another controls the page |
installable | the browser offered to install the app and the offer is kept; false again after install() or appinstalled. Safari and Firefox fire no such event and leave it false |
update() | posts SKIP_WAITING to the waiting worker and reloads the page when the new one takes over, through reloadApp. With no waiting worker it resolves at once. A worker of your own must handle the message; precache() does |
install() | shows the browser's install prompt and resolves "accepted" or "dismissed"; "unavailable" when there is none |
On the server, and before hydration, every flag is false, so the first render matches the server's. Without the module in modules, usePwa() throws usePwa() needs the @hamur/pwa module in hamur.config.ts modules.
The value has the shape of the library's other composables:
| Library | Returns |
|---|---|
| React, Preact | the flags as values, re-rendering on change |
| Vue | the flags as readonly refs |
| Solid | the flags as accessors |
| Svelte | getters that track in templates and effects |
| html | getters, plus subscribe(listener): () => void; the page runs again when it hydrates |
import { useAppUpdate } from "@hamur/adapter-react"
import { usePwa } from "@hamur/pwa/react"
import { reloadApp } from "hamur/app"
export default function UpdatePrompt() {
const { needRefresh, offlineReady, installable, update, install } = usePwa()
const { available } = useAppUpdate()
if (needRefresh) {
return (
<p role="status">
A new version is ready. <button onClick={() => void update()}>Update</button>
</p>
)
}
if (available) {
return (
<p role="status">
The app changed on the server.{" "}
<button onClick={() => reloadApp({ force: true, persistState: true })}>Reload</button>
</p>
)
}
if (installable) return <button onClick={() => void install()}>Install the app</button>
return offlineReady ? <p role="status">Ready to work offline.</p> : null
}
The same prompt in Vue, Svelte and html. useAppUpdate is its own subject; the prompt reads it so one banner covers both a new worker and a new deploy.
<script setup lang="ts">
import { useAppUpdate } from "@hamur/adapter-vue"
import { usePwa } from "@hamur/pwa/vue"
const { needRefresh, installable, update, install } = usePwa()
const { available } = useAppUpdate()
</script>
<template>
<p v-if="needRefresh" role="status">A new version is ready. <button @click="update()">Update</button></p>
<p v-else-if="available" role="status">The app changed on the server. The next link you click loads it.</p>
<button v-else-if="installable" @click="install()">Install the app</button>
</template>
<script lang="ts">
import { useAppUpdate } from "@hamur/adapter-svelte"
import { usePwa } from "@hamur/pwa/svelte"
const pwa = usePwa()
const appUpdate = useAppUpdate()
</script>
{#if pwa.needRefresh}
<p role="status">A new version is ready. <button onclick={() => pwa.update()}>Update</button></p>
{:else if appUpdate.available}
<p role="status">The app changed on the server. The next link you click loads it.</p>
{:else if pwa.installable}
<button onclick={() => pwa.install()}>Install the app</button>
{/if}
An html page returns markup, so a click needs a listener of its own. This client plugin talks to the store that the module already started:
import { useAppUpdate } from "@hamur/adapter-html"
import { usePwa } from "@hamur/pwa/html"
export default function UpdatePrompt(): string {
const { needRefresh, installable } = usePwa()
const { available } = useAppUpdate()
if (needRefresh) return `<p role="status">A new version is ready. <button data-pwa="update">Update</button></p>`
if (available) return `<p role="status">The app changed on the server. The next link you click loads it.</p>`
return installable ? `<button data-pwa="install">Install the app</button>` : ""
}
import { pwaStore } from "@hamur/pwa/client"
document.addEventListener("click", (event) => {
const action = (event.target as Element).closest("[data-pwa]")?.getAttribute("data-pwa")
if (action === "update") void pwaStore().update()
if (action === "install") void pwaStore().install()
})
Preact and Solid read the same: usePwa from @hamur/pwa/preact and @hamur/pwa/solid.
Web push
Push needs four things: a VAPID key pair, a worker that shows the notification, a page that subscribes, and a server that keeps the subscriptions and sends. @hamur/pwa has no dependency for this: the message is encrypted with crypto.subtle (RFC 8291 and RFC 8188 aes128gcm) and signed with a VAPID token (RFC 8292), so it runs on the bun, node and cloudflare presets.
1. Make the keys once. A new pair invalidates every subscription made with the old public key, so keep both.
import { generateVapidKeys } from "@hamur/pwa/server"
const { publicKey, privateKey } = await generateVapidKeys()
console.log(`VAPID_PUBLIC_KEY=${publicKey}`)
console.log(`VAPID_PRIVATE_KEY=${privateKey}`)
Run it with bun and it prints two lines. Put them in the environment of the build and of the server.
2. Declare the keys and a store that survives. app/env.ts declares both keys. The public key is static, read at build by import.meta.env.VAPID_PUBLIC_KEY, so the browser gets the public key only; the private key stays on the server:
import { defineEnv } from "hamur"
export default defineEnv({
VAPID_PUBLIC_KEY: { public: true, static: true },
VAPID_PRIVATE_KEY: {},
})
The config reads both into runtimeConfig.vapid with env("NAME") when the server starts. The default useStorage mount is memory, which is empty after a restart, so mount a driver for the subscriptions:
import { defineConfig, env } from "hamur"
import { fs } from "hamur/storage"
import pwa from "@hamur/pwa"
export default defineConfig({
framework: "react",
modules: [pwa],
storage: {
push: fs({ base: ".data/push" }),
},
runtimeConfig: {
vapid: {
subject: "mailto:you@example.com",
publicKey: env("VAPID_PUBLIC_KEY"),
privateKey: env("VAPID_PRIVATE_KEY"),
},
},
})
3. Show the notification in the worker. The generated worker has no push listener, so push needs an app/sw.ts:
import { precache } from "#hamur/service-worker"
declare const self: ServiceWorkerGlobalScope
precache()
self.addEventListener("push", (event) => {
const { title, body, url } = event.data?.json() ?? { title: "Todo" }
event.waitUntil(self.registration.showNotification(title, { body, data: { url: url ?? "/" } }))
})
self.addEventListener("notificationclick", (event) => {
event.notification.close()
event.waitUntil(self.clients.openWindow(event.notification.data.url))
})
4. Subscribe in the page. subscribePush(publicKey) waits for the registered worker, asks the browser for permission and resolves the subscription as JSON, which sendPush takes. Without a worker registered within 10 seconds it rejects with subscribePush needs a service worker (app/sw.ts or serviceWorker.generate). A permission the user refuses rejects with the browser's NotAllowedError. Call it from a click, not on load: browsers refuse a permission prompt nobody asked for.
import { subscribePush } from "@hamur/pwa/client"
import { $fetch } from "hamur/app"
import { useState } from "react"
export default function EnablePush() {
const [state, setState] = useState<"idle" | "on" | "refused">("idle")
async function enable() {
try {
const subscription = await subscribePush(import.meta.env.VAPID_PUBLIC_KEY!)
await $fetch("/api/push", { method: "POST", body: subscription })
setState("on")
} catch {
setState("refused")
}
}
if (state === "on") return <p role="status">Notifications are on.</p>
return (
<button onClick={() => void enable()}>
{state === "refused" ? "Notifications are blocked" : "Turn on notifications"}
</button>
)
}
5. Keep the subscriptions and send. The handlers key each subscription by a hash of its endpoint in useStorage("push"), and remove one when the push service says it is gone:
import { sendPush } from "@hamur/pwa/server"
import { createError, defineHandler, useRuntimeConfig, useStorage } from "hamur/server"
type PushSubscription = Parameters<typeof sendPush>[0]
type Vapid = Parameters<typeof sendPush>[2]["vapid"]
async function keyOf(endpoint: string): Promise<string> {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint))
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")
}
export const subscribe = defineHandler({
route: "/api/push",
method: "POST",
async handler(input: PushSubscriptionJSON) {
const { endpoint, keys } = input
if (!endpoint || !keys?.p256dh || !keys.auth) throw createError({ status: 400, message: "Not a push subscription" })
const subscription: PushSubscription = { endpoint, keys: { p256dh: keys.p256dh, auth: keys.auth } }
await useStorage("push").setItem(await keyOf(endpoint), subscription)
return { subscribed: true }
},
})
// Guard this route: whoever can call it pushes to every subscriber.
export const notify = defineHandler({
route: "/api/push/notify",
method: "POST",
async handler({ title, body }: { title: string; body: string }, { event }) {
const vapid = useRuntimeConfig(event).vapid as Vapid
const store = useStorage("push")
let sent = 0
for (const key of await store.getKeys()) {
const subscription = await store.getItem<PushSubscription>(key)
if (!subscription) continue
const { gone } = await sendPush(subscription, JSON.stringify({ title, body }), { vapid, urgency: "high" })
if (gone) await store.removeItem(key)
else sent += 1
}
return { sent }
},
})
sendPush(subscription, payload, { vapid, ttl, urgency, topic, timeout }) resolves { status, gone }. status is the push service's answer, 201 when it took the message. gone is true for 404 and 410: the subscription no longer exists, so delete it. An HTTP status never throws; a network failure rejects with fetch's error. ttl is the seconds the service keeps the message (default 86400), urgency is "very-low", "low", "normal" (default) or "high", and a message with a topic replaces an earlier one of the same topic that was not yet delivered.
Limits and checks:
- A payload over 3993 bytes throws
sendPush: the payload is 5000 bytes; a push message holds at most 3993. - The endpoint comes from a browser, so
sendPushrefuses one that is nothttps:or whose host islocalhostor a private, loopback or link-local address. A redirect is never followed, so the VAPID token goes to no other host. A public name that resolves to a private address is not caught, since Workers have no DNS lookup; block that at the network if it matters. - Bad input throws before any request, and no message holds a key:
sendPush: vapid.subject must be a mailto: or https: URL (got "me@example.com"),sendPush: ttl must be an integer from 0 to 2419200 (got -1)and the like. The full list is in the reference.