Build a server for sending web push notifications.

Dhananjay Purohit
3 min readJul 7, 2020

While writing this article, a notification pops up on my device from Intel Driver & Support Assistant informing about the software updates available for my device. I know you are thinking about why it’s important, then just imagine you are sitting in a coding contest and there is an update in a problem you left behind after trying a lot and move on to the next, then how will you know about it? Obviously, a notification message can help you to let you know the same. The same thing is used by many websites hosting coding contests like Codeforces.

How is the complete thing works?

  1. The client app installs a script called service worker (A script that your browser runs in the background) even when the web app is not open in any tab.
  2. The client app requests user permission to display notifications.
  3. After getting permission from the user, the client app sends a subscription object to the server which will be stored in a database for sending push notifications timely.
  4. The notifications are scheduled by the server for sending them to the client timely.

Without involving a lot of jargons lets move over to implement a simple web push notification server.

In this tutorial, we will implement a simple Node.js server for sending push notifications on getting a post request from the client.

Dependencies required:-

Setup the dependencies for server

npm install body-parser cors dotenv express web-push

Generating VAPID keys

To generate the VAPID keys, run the following command:-

./node_modules/.bin/web-push generate-vapid-keys

VAPID keys:- A way to restrict the validity of a subscription to a specific application server.

Create a .env file for generated public and private VAPID key

PUBLIC_VAPID_KEY=
PRIVATE_VAPID_KEY=

Copy the above code and fill the generated VAPID keys into it.

Making the server know what to do

Create a file index.js and copy the below code:-

As you can see from the code our server will respond with a notification on getting a post request from the client. The GET endpoint is to test our server.

You can start the server by running the command node index.js and by hitting http://localhost:9000/

To test the server delivering push notifications correctly or not, try the below web app.

Generate the subscription object through the web app by entering the public VAPID key and the post request endpoint.

Congrats, if you see a push notification sent by your server to the web app.

You can also check out the code:-

Have any queries or suggestions, feel free to connect me on LinkedIn or Twitter.

--

--

Dhananjay Purohit

Summer Of Bitcoin’22 @Alby | GSoC'21 @Orcasound | LFX’21 CNCF- @LitmusChaos | Full Stack Developer | Open-source contributor