Guides

Service worker push notification example (vanilla JavaScript)

The browser side of web push in about 60 lines of plain JavaScript, with the details that tutorials usually leave out.

Short answerRegister a service worker, call pushManager.subscribe() with userVisibleOnly: true and your VAPID public key, send the subscription JSON to your server, and in the service worker listen for push (call showNotification inside event.waitUntil) and notificationclick (open or focus the URL).

This is the browser half of web push with no libraries: subscribing, receiving, showing and handling clicks. You’ll need a VAPID key pair (make one with the VAPID key generator) and a server that sends pushes, such as web-push for Node.

The two files

  • /sw.js: the service worker. It must be served from your own domain, at the root if it should cover every page, with a JavaScript content type.
  • Some code in your page (here, app.js) that registers the worker and subscribes.

1. Register and subscribe (page code)

const VAPID_PUBLIC_KEY = 'BElz...your 87-character public key...';

function toBytes(b64url) {
  const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - b64url.length % 4) % 4);
  return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
}

async function enablePush() {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    return console.warn('Push is not supported in this browser');
  }
  const reg = await navigator.serviceWorker.register('/sw.js');

  // Must run from a click handler: Safari and Firefox ignore it otherwise.
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') return;

  let sub = await reg.pushManager.getSubscription();
  if (!sub) {
    sub = await reg.pushManager.subscribe({
      userVisibleOnly: true,                      // required by every browser
      applicationServerKey: toBytes(VAPID_PUBLIC_KEY),
    });
  }
  // Send endpoint + keys (p256dh, auth) to your server and store them.
  await fetch('/api/push-subscriptions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(sub),
  });
}

document.querySelector('#enable-push').addEventListener('click', enablePush);

The JSON your server receives looks like this:

{
  "endpoint": "https://fcm.googleapis.com/fcm/send/dQ4...:APA91b...",
  "expirationTime": null,
  "keys": { "p256dh": "BN3...", "auth": "k8J..." }
}

2. Show the notification (service worker)

// sw.js
self.addEventListener('push', (event) => {
  let data = {};
  try { data = event.data ? event.data.json() : {}; } catch (e) { data = { body: event.data && event.data.text() }; }

  const title = data.title || 'New update';
  const options = {
    body: data.body || '',
    icon: data.icon || '/icon-192.png',
    image: data.image,                 // shown by Chrome and Edge only
    badge: '/badge-72.png',            // monochrome icon for the Android status bar
    tag: data.tag,                     // same tag replaces an older notification
    data: { url: data.url || '/' },
    actions: data.actions || [],       // up to 2, Chrome and Edge only
  };

  // waitUntil keeps the worker alive until the notification is shown.
  event.waitUntil(self.registration.showNotification(title, options));
});

The most common bug is calling showNotification without event.waitUntil. The worker can be stopped before the notification appears, and Chrome then shows a generic “This site has been updated in the background” message instead.

3. Handle the click

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = new URL(event.notification.data.url, self.location.origin).href;

  event.waitUntil((async () => {
    const tabs = await clients.matchAll({ type: 'window', includeUncontrolled: true });
    const open = tabs.find((t) => t.url === url);
    if (open) return open.focus();       // reuse an open tab
    return clients.openWindow(url);      // or open a new one
  })());
});

Action buttons arrive in the same event with event.action set to the button’s action id.

4. Send from the server

// Node.js, npm install web-push
import webpush from 'web-push';

webpush.setVapidDetails('mailto:[email protected]', process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY);

try {
  await webpush.sendNotification(subscription, JSON.stringify({
    title: 'Your export is ready', body: 'orders.csv, 2.4 MB', url: '/exports/42',
  }), { TTL: 3600 });
} catch (err) {
  if (err.statusCode === 404 || err.statusCode === 410) {
    // The subscription is gone: delete it from your database.
  }
}

5. Test it

  • Chrome DevTools, Application, Service workers: check the worker is activated. The “Push” button there fires a test push event with text data.
  • Tick “Update on reload” while developing, or the old worker keeps running after you edit sw.js.
  • Push works on http://localhost without HTTPS, but nowhere else.
  • To rule out your code, check that the browser can receive push at all with the push tester.

What production needs on top

The example covers the happy path. A production setup also has to: delete subscriptions that return 404 or 410; re-check the subscription on every visit (it can change); send in parallel with rate limiting so a large list doesn’t take hours; track displays and clicks; and show a soft prompt before the browser’s permission box. SuperWicket does all of that behind one script tag. Its service worker is a one-line importScripts, so you can also add it to a worker you already have. See how to add push to a website.

Frequently asked questions

Why must userVisibleOnly be true?

Chrome and the other browsers only allow subscriptions that promise to show a notification for every push. Silent pushes aren’t allowed on the web.

Why is my push event firing but no notification appears?

showNotification must be called inside event.waitUntil(). If the promise is missing or rejects, the browser may show a generic “site updated in the background” message or nothing at all.

Do I need Firebase for web push?

No. Chrome’s push service is run on Firebase Cloud Messaging infrastructure, but you send to it with the standard Web Push protocol and VAPID. No Firebase project or SDK is needed.

Try it on your own site

The Free plan has no time limit and needs no card. Add one script tag, or share a hosted subscribe page if you can’t upload files.