Push notifications let you send messages to users even when they are not actively using your web app. They are one of the most powerful re-engagement tools available to PWAs, bridging the gap between web and native experiences.
How Web Push Works
The push notification system involves three parties:
Your Server → Push Service (FCM/APNs) → User's Browser → Service Worker → Notification
- The user grants notification permission
- The browser creates a push subscription with a push service
- Your server stores the subscription endpoint
- When you want to notify the user, your server sends a message to the push service
- The push service delivers the message to the browser
- The service worker receives the push event and displays a notification
Notification Permission
Before sending any notifications, you must request permission:
Permission States
| State | Meaning |
|---|---|
default | User has not been asked yet |
granted | User allowed notifications |
denied | User blocked notifications (cannot re-ask) |
Best practice: Do not ask for permission immediately on page load. Wait until the user takes an action that shows they want notifications (like clicking a "Get notified" button).
Simple Notifications (No Push Server)
You can show notifications directly from the page without a push server:
Handling Notification Clicks
In the service worker, listen for notification clicks:
Push Subscriptions
To receive push messages from your server, create a push subscription:
Generate VAPID Keys
VAPID (Voluntary Application Server Identification) keys authenticate your server with the push service.
npm install web-push
npx web-push generate-vapid-keysThis outputs a public and private key pair. Store the private key on your server and use the public key in the browser.
Subscribe the User
Server-Side Push
Send push messages from your Node.js server:
Handling Push Events in the Service Worker
Notification Best Practices
Do
- Ask for permission at a contextually relevant moment
- Provide a clear "why" before requesting permission
- Make notifications actionable with relevant deep links
- Use the
tagproperty to replace outdated notifications - Let users control notification preferences in your app
Do Not
- Ask for permission on the first page load
- Send too many notifications (users will block you)
- Send notifications without value to the user
- Use notifications for advertising
- Forget to handle the
notificationclickevent
Building a Notification Preferences UI
Practical Exercise
Build a complete push notification system:
Key Takeaways
- Push notifications require user permission, a service worker, VAPID keys, and a server-side push library.
- Always ask for notification permission at a relevant moment, not on page load.
- Use the
tagproperty to group and replace related notifications. - Handle
notificationclickin the service worker to deep-link users into your app. - Let users manage their notification preferences and provide an easy way to unsubscribe.