Add Push Notifications

Add push only after the app has a clear notification reason. Permission prompts are product UX, not setup boilerplate.

Steps

  1. Register a service worker.
  2. Ask notification permission from a user gesture.
  3. Subscribe with PushManager and your public VAPID key.
  4. Store the subscription on your server for the signed-in user.
  5. Send Web Push messages from the server.
  6. Show a notification in the service worker push event.
  7. Route clicks in notificationclick.
  8. Handle unsubscribe, expired subscriptions, and denied permission.

Client Subscription

async function enableNotifications(publicVapidKey: Uint8Array) {
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') return false;

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

  await fetch('/api/push-subscriptions', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(subscription),
  });

  return true;
}

Security Rules

  • Authenticate subscription registration.
  • Bind each subscription to the right user/device.
  • Protect CSRF-sensitive endpoints.
  • Do not log full subscription secrets.
  • Rate-limit sends and support unsubscribe.