Vize

use-service-worker

Register a service worker and follow its update lifecycle.

Package @vizejs/composable/use-service-worker
Own the source vize lib pull composable:use-service-worker
Runtime exports useServiceWorker
Gzip budget 2304 B

Minimal setup

Use a Vue 3.5+ project with Vue SFC compilation configured (see Vite+ integration).

vp install @vizejs/composable

Import the entry directly. Call lifecycle-bound utilities inside <script setup> so cleanup follows the component scope; consult the runtime contract for this entry's SSR and hydration behavior.

import { useServiceWorker } from "@vizejs/composable/use-service-worker";

Try it

Enable offline mode

Register a service worker on request and offer a reload when an update is waiting.

Open the interactive example

What to observe: Enable offline mode registers /sw.js in an app that serves it; Reload to update appears when a new version is waiting.

Serve the worker script from your app's public directory. skipWaiting sends the configured message to the waiting worker. Every example renders a neutral message until it mounts, so server and client markup match, and then explains what to do when the browser lacks the API.

Compare the initial and interacted states
Enable offline mode: initial state
Initial state
Enable offline mode: state after the verified interactions
After the verified interactions

Copy the example

Save this complete SFC in your Vue project. Its public imports and source are the same ones executed in the preview.

<script setup lang="ts">
import { useMounted } from "@vizejs/composable/use-mounted";
import { useServiceWorker } from "@vizejs/composable/use-service-worker";

const mounted = useMounted();
// Serve `/sw.js` from your app's public directory.
const { supported, state, updateAvailable, register, skipWaiting } = useServiceWorker("/sw.js", {
  immediate: false,
});
</script>

<template>
  <div class="composable-example">
    <p>Install offline support on request and offer a reload when an update is waiting.</p>
    <div class="example-actions">
      <button type="button" :disabled="!mounted || !supported" @click="() => register()">
        Enable offline mode
      </button>
      <button type="button" :disabled="!updateAvailable" @click="() => skipWaiting()">
        Reload to update
      </button>
    </div>
    <output aria-live="polite">{{
      !mounted
        ? "Checking browser support…"
        : supported
          ? `Service worker: ${state}`
          : "Service workers are not available in this browser."
    }}</output>
  </div>
</template>

Runtime contract

Utility Category Stability SSR Hydration Cleanup Targets Host globals Uses
useServiceWorker networking experimental deterministic-fallback caller-managed reactive-scope web, desktop window tryOnScopeDispose

API

useServiceWorker

Register a service worker and follow its update lifecycle. Tracks updatefound and each worker's statechange so state mirrors the installing, waiting and active workers. updateAvailable turns true once an installed worker waits while another one controls the page; skipWaiting() then posts the configured message to it, and onControllerChange runs once it takes control. Listeners are removed when the owning reactive scope stops; outside a scope they live as long as the registration. Server rendering: nothing is registered, supported is false and every state is null.

function useServiceWorker( scriptUrl: MaybeRefOrGetter<string | URL>, options: UseServiceWorkerOptions = {}, ): ServiceWorkerControls
const sw = useServiceWorker("/sw.js", {
  onControllerChange: () => window.location.reload(),
});
const applyUpdate = () => sw.skipWaiting();

Types

ServiceWorkerLike

Minimal ServiceWorker consumed by useServiceWorker.

Member Type Description
state ServiceWorkerStateName Current lifecycle state; changes fire statechange.
postMessage (message: unknown) => void Post a message to the worker.

ServiceWorkerRegistrationLike

Minimal ServiceWorkerRegistration consumed by useServiceWorker.

Member Type Description
installing ServiceWorkerLike | null Worker being installed, if any; a new one fires updatefound.
waiting ServiceWorkerLike | null Installed worker waiting to take over, if any.
active ServiceWorkerLike | null Active worker, if any.
scope string Registration scope URL.
update () => Promise<unknown> Check the server for an updated script.
unregister () => Promise<boolean> Unregister; resolves whether the registration was removed.

ServiceWorkerRegisterOptions

Options forwarded to ServiceWorkerContainer.register.

Member Type Description
scope? string Registration scope.
type? "classic" | "module" Script type.
updateViaCache? "imports" | "all" | "none" HTTP cache policy for update checks.

ServiceWorkerContainerLike

Minimal ServiceWorkerContainer (navigator.serviceWorker).

Member Type Description
controller ServiceWorkerLike | null Worker controlling this page; changes fire controllerchange.
register (scriptUrl: string | URL, options?: ServiceWorkerRegisterOptions) => Promise<ServiceWorkerRegistrationLike> Register a service worker script.

ServiceWorkerStates

States of the registration's workers (null when absent).

Member Type Description
installing ServiceWorkerStateName | null State of the installing worker.
waiting ServiceWorkerStateName | null State of the waiting worker.
active ServiceWorkerStateName | null State of the active worker.

UseServiceWorkerOptions

Options for useServiceWorker.

Member Type Description
container? MaybeRefOrGetter<ServiceWorkerContainerLike | null | undefined> Service worker container for alternate runtimes and tests.
scope? string Registration scope.
type? "classic" | "module" Script type.
updateViaCache? "imports" | "all" | "none" HTTP cache policy for update checks.
immediate? boolean Register as soon as the composable is created (browser only).
skipWaitingMessage? unknown Message posted to the waiting worker by skipWaiting().
onControllerChange? (controller: ServiceWorkerLike | null) => void Called on controllerchange (for example to reload the page after a new worker took control).

ServiceWorkerControls

Reactive state and actions returned by useServiceWorker.

Member Type Description
supported ComputedRef<boolean> Whether the Service Worker API is available.
registration Readonly<ShallowRef<ServiceWorkerRegistrationLike | null>> Current registration, or null before registering.
state Readonly<Ref<ServiceWorkerStates>> States of the installing, waiting and active workers.
updateAvailable ComputedRef<boolean> Whether a waiting worker is ready to replace the controlling one.
error Readonly<ShallowRef<unknown>> Most recent failure, cleared by the next successful action.
register () => Promise<ServiceWorkerRegistrationLike | null> Register (or re-register) the script.
update () => Promise<boolean> Check the server for an updated script.
skipWaiting () => boolean Post the skip-waiting message to the waiting worker.
unregister () => Promise<boolean> Unregister the service worker.