A simple implement of web push notifications.
- Node.js 8+
- One of these:
- Google Chrome 65+
- Firefox 59+ (enable
dom.moduleScripts.enabled
flag)
npm install
npm run dev
- Visit
http://localhost:3000/server
and create a key pair. - Open another tab and visit
http://localhost:3000/client
. - Push the button and grant the permission.
- Return to the first page, the server, and push the send button.
Read these first: How Push Works, Google's codelab
- Server Side
- Create and store
application server keys
.
- Create and store
- Client Side
- Retrieve
application server public key
from the server. - Subscribe to the push service using
application server public key
.- Get a permission from the user.
- Get a
PushSubscription
from the push service.
- Send the
PushSubscription
to the server.
- Retrieve
- Server Side
- Save the
PushSubscription
to the DB. - Generate the data that you want to send to the user.
- Make an API call to the push service using a library. The user's
PushSubscription
andapplication server keys
are needed.- Encrypt the data with the user public key.
- Send the data to the endpoint URL with a payload of encrypted data.
- Save the
- Push Service
- The push service routes the message to the user's device.
- User's Device
- User's device wakes up the browser, which finds the correct service worker and invokes a push event.
- The service worker wakes up just long enough to display the notification and then goes back to sleep.
This implement uses localStorage
to share data between server and client. That's a major - and maybe the only - difference from Google's codelab.
// client-side
const updateSubscriptionOnServer = (subscription) => {
// TODO: Send subscription to application server
window.localStorage.setItem('subscription', JSON.stringify(subscription))
}
// server-side
const subscription = JSON.parse(window.localStorage.getItem('subscription'))
// ...
const result = await webPush.sendNotification(subscription, data, options)
- Handle exceptions: I didn't handle exceptions on purpose to clarify my intentions.
- Replace
localStorage
with a database: We have to use databases for real world applications. - Handle
pushsubscriptionchange
event: I'm still confused with this. Please help me if you can.
- Web Push Notifications: Timely, Relevant, and Precise (Everything you need to know is here.)
- Adding Push Notifications to a Web App
- Introduction to Push Notifications
- The Service Worker Lifecycle
- Debugging Service Workers