Trying Out Web Push Notifications
- #JavaScript
 - #PWA
 - #Security
 - #Tips
 
- 2022/07/13
 
Trying Out Web Push
Notifications matter for web services. Beyond in-app notices or email, web push is another channel worth exploring. Here is a lightweight implementation flow.
Flow
- Load 
serviceWorker.js. - In the service worker, register a handler for the 
pushevent. - User visits the page.
 - Browser prompts for permission; the user grants it.
 - Use the public key to subscribe.
 - On success you receive an endpoint and token.
 - Send the endpoint/token to your server.
 - When you need to notify the user, have the server POST to the endpoint with the token (encrypt the payload).
 - If the service worker is active, it catches the push event and displays the notification.
 
Sample code
https://github.com/hirotoyoshidome/exp-web-push
Notes
- Keep the private key on the server; use it when POSTing the message.
 - Do not expose the private key publicly.
 - Push does not work in incognito windows (the console shows an error).
 - If the user denies permission, you cannot force notifications—no endpoint/token is issued.
 - In Chrome DevTools (Application tab) you can send test messages to a service worker.
 - Server-side pushes accept only one text payload, but you can place JSON in the notification 
datafield to pass URLs etc., and open pages when the user clicks the notification. - Encrypt messages when pushing from the server. Use a library (Python, Node.js, etc.) to handle the details.
 
Closing
Setting up push required more steps than I expected, but adding another notification channel can be worthwhile.
 Share: 
X (Twitter)