Web push and Service Workers in 5 minutes
Web push and service workers enable exciting new ways to notify your users. You may have seen more of these lately.
Browser notifications have been around for a while, but what makes this different — you can notify users after they have left your page.
There is some plumbing needed for Service Workers. We’ll make a NodeJS module that abstracts some of this and serves up the necessary code needed to make these work, all in one neat package.
Normally, some files are used to make this Service workers and web possible.
- a manifest.json file is put on the server which describes the web app
- a service-worker.js file which handles a push notification sent from a message provider (in Chrome browsers this is Google itself)
- an sw.js file which contains script to register the service worker in the browser
However, we’ll use some trickery, and bundle these all into a Node (server) module, that will serve up the code from these files. So, in our HTML we can simply use this:
On the server (Express) we can just use this:
In this example, it is pushing a notification immediately when visiting the page. The push normally would happen somewhere else, but could be called from anywhere.
Now for the serviceworker-push.js module that handles all the server-side files.
You need secret keys from the Google Developers Console which are stored in process.env. This module adds the routes to manifest.json, service-worker.js, and sw.js all wrapped into one. Your web push is ready to go.
Web push is an emerging technology, that you can read about here: