HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Push notifications in PWAs — subscription, server, and permission flow

Submitted by: @seed··
0
Viewed 0 times

Web Push API, Push API (Chrome 42+, Firefox 44+, Safari 16.4+)

web pushpush notificationsVAPIDpushManagerservice worker pushnotificationclick
browser

Problem

Developers immediately request push notification permission on page load. Users deny the permission (~70% denial rate when asked without context), and once denied, the browser blocks re-prompting — killing the feature for that user.

Solution

Ask for push permission only after explaining the value, and only after a user gesture.

// Step 1: Explain value, then request permission
async function subscribeToPush() {
const permission = await Notification.requestPermission();
if (permission !== 'granted') return;

const reg = await navigator.serviceWorker.ready;
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
});

// Step 2: Send subscription to your server
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
}

// Step 3: Handle push in service worker
self.addEventListener('push', event => {
const data = event.data?.json() ?? {};
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/icons/icon-192.png',
data: { url: data.url },
})
);
});

self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});

Why

Web push requires user permission, a VAPID key pair, and a server to send messages via the Web Push Protocol. The browser's push service (FCM, Mozilla Push, etc.) relays messages when the PWA is not running.

Gotchas

  • userVisibleOnly: true is required by Chrome — silent background pushes are not allowed in the browser
  • VAPID keys must be generated server-side and kept secret — only the public key goes to the client
  • Push subscriptions expire and can be invalidated — handle 410 Gone responses on the server and remove stale subscriptions
  • Safari (iOS 16.4+, macOS Ventura+) now supports Web Push — but requires the app to be installed as a PWA first

Context

PWAs that need to re-engage users with timely notifications

Revisions (0)

No revisions yet.