Add Push Notifications
Add push only after the app has a clear notification reason. Permission prompts are product UX, not setup boilerplate.
Steps
- Register a service worker.
- Ask notification permission from a user gesture.
- Subscribe with
PushManagerand your public VAPID key. - Store the subscription on your server for the signed-in user.
- Send Web Push messages from the server.
- Show a notification in the service worker
pushevent. - Route clicks in
notificationclick. - 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.