Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Push Notifications

Subscribing to Push

Subscribe users to web push: feature detection, requesting permission, converting the VAPID key, PushManager.subscribe, saving subscriptions and handling changes.

Subscribing is the client half of web push. The page has to check that push is supported, get permission from the user, ask the browser for a subscription tied to your VAPID public key, and send the result to your server. None of this can run inside the sandboxed preview, so the real code is read-only, and runnable stand-ins let you test the helper functions and the control flow.

The checklist

  1. Feature detection: service workers, PushManager, Notification.
  2. A registered, active service worker (navigator.serviceWorker.ready).
  3. Permission from the user, requested in response to a click.
  4. pushManager.subscribe() with userVisibleOnly: true and your public key.
  5. Save the subscription on the server, linked to the signed-in user.

Step 1: feature detection

JavaScript
function pushIsSupported() {
  return (
    "serviceWorker" in navigator &&
    "PushManager" in window &&
    "Notification" in window
  );
}

On iOS, PushManager is present only when the page runs as an installed web app, so an unsupported result may simply mean "not installed yet". Show your install hint instead of an error.

Step 2: convert the key

The VAPID public key you generate on the server is a URL-safe Base64 string. subscribe() wants it as a Uint8Array (or a BufferSource), so every project carries a small conversion helper. It is pure code, so you can run it here:

JS URL-safe Base64 to bytes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The padding line restores the = characters that URL-safe Base64 drops, and the two replace calls turn - and _ back into + and / so atob can decode it.

Step 3 and 4: permission and subscription

JavaScript
const VAPID_PUBLIC_KEY = "BNc...your-public-key...";

async function enablePush() {
  if (!pushIsSupported()) return { ok: false, reason: "unsupported" };

  const permission = await Notification.requestPermission();
  if (permission !== "granted") return { ok: false, reason: permission };

  const registration = await navigator.serviceWorker.ready;

  let subscription = await registration.pushManager.getSubscription();
  if (!subscription) {
    subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
    });
  }

  await fetch("/api/push/subscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(subscription),   // calls toJSON()
  });
  return { ok: true };
}

Notes on each part:

  • Notification.requestPermission() must be triggered by a user gesture on some browsers, and should be on all of them for good manners. Call enablePush() from a button's click handler.
  • getSubscription() returns the existing subscription, so pressing the button twice does not create duplicates. If the existing subscription was made with a different key, call unsubscribe() first.
  • userVisibleOnly: true is a promise that every push will show a notification. Chrome and Safari refuse to subscribe without it.
  • JSON.stringify(subscription) produces the endpoint, expirationTime and keys object the server needs.

Try it: the control flow with fakes

The simulation below replaces Notification and pushManager with objects you control. Change permission and existing to walk each branch.

JS enablePush with fake browser objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 5: the server endpoint

Your server stores subscriptions. A table needs at least the user ID, the endpoint (unique), the two keys and a created date. Upsert by endpoint, because the same device may subscribe again:

PHP
// Laravel-style controller (read-only)
PushSubscription::updateOrCreate(
    ['endpoint' => $request->input('endpoint')],
    [
        'user_id' => $request->user()->id,
        'p256dh'  => $request->input('keys.p256dh'),
        'auth'    => $request->input('keys.auth'),
    ]
);

Authenticate this route. An anonymous endpoint that accepts any subscription lets strangers fill your database.

Unsubscribing

Give users an off switch in your own settings screen:

JavaScript
async function disablePush() {
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.getSubscription();
  if (!subscription) return;

  await fetch("/api/push/unsubscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ endpoint: subscription.endpoint }),
  });
  await subscription.unsubscribe();
}

Tell the server first, then unsubscribe locally, so the server does not keep a record for a subscription that no longer exists.

Subscriptions change

Browsers can rotate or expire subscriptions. The service worker receives a pushsubscriptionchange event, and the right reaction is to subscribe again with the same key and send the new subscription to the server:

JavaScript
self.addEventListener("pushsubscriptionchange", (event) => {
  event.waitUntil(
    self.registration.pushManager
      .subscribe(event.oldSubscription.options)
      .then((subscription) =>
        fetch("/api/push/resubscribe", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ old: event.oldSubscription.endpoint, new: subscription }),
        })
      )
  );
});

Support for this event varies, so also re-check the subscription every time the app opens: compare getSubscription() with what the server has and resend it if they differ.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does subscribe() need the key converted with urlBase64ToUint8Array?

    applicationServerKey takes a BufferSource such as a Uint8Array, not the Base64 string.
  2. 2. What does getSubscription() return when nobody has subscribed yet?

    The promise resolves with null, which is why code checks the result before subscribing.
  3. 3. What does userVisibleOnly: true promise?

    Browsers use it to prevent silent background tracking through push.
  4. 4. Where should Notification.requestPermission() be called from?

    Prompting on load trains users to refuse, and some browsers require a gesture.

Summary

  • Detect support, ask permission from a click, then subscribe with the VAPID public key as bytes.
  • Reuse getSubscription() results; upsert on the server by endpoint.
  • Offer an unsubscribe switch, and handle pushsubscriptionchange plus a recheck on app start.
  • Authenticate the subscription endpoint on your server.

Next: Sending Push Messages