Vize

use-push-subscription

Manage a Web Push subscription.

Package @vizejs/composable/use-push-subscription
Own the source vize lib pull composable:use-push-subscription
Runtime exports usePushSubscription
Gzip budget 2560 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 { usePushSubscription } from "@vizejs/composable/use-push-subscription";

Try it

Subscribe to schedule alerts

Subscribe to push messages from your server with a service worker registration.

Open the interactive example

What to observe: Subscribe to alerts creates a subscription once a service worker is registered; send its JSON to your server.

Pass registration from useServiceWorker. The key in the example is a placeholder for your VAPID public key. 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
Subscribe to schedule alerts: initial state
Initial state
Subscribe to schedule alerts: 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 { usePushSubscription } from "@vizejs/composable/use-push-subscription";

const mounted = useMounted();
// Pass your service worker registration, for example from useServiceWorker().
const { supported, subscription, subscribe, unsubscribe } = usePushSubscription({
  immediate: false,
});
const vapidPublicKey =
  "BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U";
</script>

<template>
  <div class="composable-example">
    <p>Subscribe to schedule-change alerts sent by your server.</p>
    <div class="example-actions">
      <button
        type="button"
        :disabled="!mounted || !supported || subscription !== null"
        @click="() => subscribe({ applicationServerKey: vapidPublicKey, userVisibleOnly: true })"
      >
        Subscribe to alerts
      </button>
      <button type="button" :disabled="!subscription" @click="() => unsubscribe()">
        Unsubscribe
      </button>
    </div>
    <output aria-live="polite">{{
      !mounted
        ? "Checking browser support…"
        : supported
          ? subscription
            ? "Subscribed to alerts."
            : "Not subscribed."
          : "Push messages are not available in this browser."
    }}</output>
  </div>
</template>

Runtime contract

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

API

usePushSubscription

Manage a Web Push subscription. Uses the push manager of options.registration, or of navigator.serviceWorker.ready by default. The existing subscription is loaded when the registration becomes known; subscribe accepts the VAPID key as a base64url string. json is the snapshot to send to a push server. Nothing needs cleanup; pending results are ignored after the owning reactive scope stops. Server rendering: nothing is read, supported is false and the subscription is null. Inside a component the host is resolved after mounting, so hydration renders this server state first.

function usePushSubscription( options: UsePushSubscriptionOptions = {}, ): PushSubscriptionControls
const push = usePushSubscription();
const enable = async () => {
  await push.subscribe({ applicationServerKey: VAPID_PUBLIC_KEY });
  await fetch("/api/push", { method: "POST", body: JSON.stringify(push.json.value) });
};

Types

PushSubscriptionJsonLike

JSON form of a push subscription (PushSubscription.toJSON()).

Member Type Description
endpoint? string | undefined Push service endpoint.
expirationTime? number | null | undefined Expiration time in epoch milliseconds, if any.
keys? Readonly<Record<string, string>> | undefined Base64url-encoded keys (p256dh, auth).

PushSubscriptionLike

Minimal PushSubscription consumed by usePushSubscription.

Member Type Description
endpoint string Push service endpoint.
expirationTime number | null Expiration time in epoch milliseconds, if any.
toJSON () => PushSubscriptionJsonLike Serialize for a server.
unsubscribe () => Promise<boolean> Cancel the subscription.

PushManagerSubscribeOptions

Options forwarded to PushManager.subscribe.

Member Type Description
applicationServerKey BufferSource VAPID public key bytes.
userVisibleOnly boolean Only user-visible notifications.

PushManagerLike

Minimal PushManager consumed by usePushSubscription.

Member Type Description
subscribe (options: PushManagerSubscribeOptions) => Promise<PushSubscriptionLike> Create (or return the existing) subscription.
getSubscription () => Promise<PushSubscriptionLike | null> Current subscription, if any.
permissionState (options?: { readonly userVisibleOnly?: boolean }) => Promise<PushPermissionState> Permission state for push.

PushRegistrationLike

Registration-like owner of a push manager.

Member Type Description
pushManager PushManagerLike The registration's push manager.

UsePushSubscriptionOptions

Options for usePushSubscription.

Member Type Description
registration? MaybeRefOrGetter<PushRegistrationLike | null | undefined> Service worker registration owning the push manager. null while it is not known yet.
immediate? boolean Load the existing subscription as soon as a registration is known.

PushSubscribeOptions

Arguments of PushSubscriptionControls.subscribe.

Member Type Description
applicationServerKey string | BufferSource VAPID public key as a base64url string or raw bytes.
userVisibleOnly? boolean Only user-visible notifications (required by most browsers).

PushSubscriptionSnapshot

Serializable snapshot of the current subscription.

Member Type Description
endpoint string Push service endpoint.
expirationTime number | null Expiration time in epoch milliseconds, or null.
keys Readonly<Record<string, string>> Base64url-encoded keys (p256dh, auth).

PushSubscriptionControls

Reactive state and actions returned by usePushSubscription.

Member Type Description
supported ComputedRef<boolean> Whether the Push API is available.
subscription Readonly<ShallowRef<PushSubscriptionLike | null>> Current subscription, or null.
json ComputedRef<PushSubscriptionSnapshot | null> JSON snapshot of the current subscription, or null.
error Readonly<ShallowRef<unknown>> Most recent failure, cleared by the next successful action.
subscribe (options: PushSubscribeOptions) => Promise<PushSubscriptionLike | null> Subscribe to push messages. Rejects with a tagged TypeError when the key string is not valid base64url.
unsubscribe () => Promise<boolean> Cancel the current subscription.
refresh () => Promise<PushSubscriptionLike | null> Re-read the existing subscription.
permissionState ( userVisibleOnly?: boolean, ) => Promise<PushPermissionState | "unsupported"> Query the push permission state.