Using Service Workers to send push notifications in Node.js
In this blog, we discuss Push Notifications in Node.js, another functionality that can be implemented by using Service Workers. They are useful if we need a quick way to communicate with our users.
A push notification is a message that pops up on a mobile device or web application, such as a sports score for a sports app, an invitation to a flash sale in shopping apps, or a coupon for downloading. App publishers can send push notifications to them at any time, so users don’t have to be in the app or using their devices to receive them.
We can create push notifications in Node.js, Express js, and Web push.
Initially, we need to create a directory for our Express.js app.
mkdir web-push-sample cd web-push-sample
Then install the needed libraries.
npm init npm i express body-parser web-push
Next, we will create a start script by adding node index.js to your start script which is present in the package. JSON.
{ "name": "web-push-sample", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "web-push": "^3.4.5" }, "scripts": { "start": "node index.js" } }
Generate VAPID Keys
We need to create a set of Vapid keys for the application. The VAPID stands for Voluntary Application Server Identification. These keys will allow us to send push messages without other messaging services. And they also identify who is sending the push notification.
./node_modules/.bin/web-push generate-vapid-keys
It will return like the below:
—————————————————————————————————————————————————————————————-
Public Key:
BO4imRW5SYfMtEUyfwMrrxvzJjuoThJ1FNqiUX3Z0C93Ajdrhdy0rX5iwvGBWHffmH3nP-NhVsF5XXbnHxsUnrg
Private Key:
yI31gBBUlJYKj_7wZmPZsLGFklxNMVSk_9UVpWBXEHc
—————————————————————————————————————————————————————————————-
Setting up the subscription route
Next, we need to create an express app and set up the route to allow clients to subscribe to your push notification
const express = require('express'); const webpush = require('web-push'); const bodyParser = require('body-parser'); const path = require('path'); // Create an express app. const app = express(); // Use body-parser to parse the request body that is sent from the client. app.use(bodyParser.json()); // We will store our client files in the./client directory. app.use(express.static(path.join(__dirname, "client"))) const publicVapidKey = "BOd2EQ8LTe3KAgMX9lWwTlHTRzv1Iantw50Mw6pUnsNr3pcxl8iglUs-YlQEQLo4UbJk9oyXs_BxgyAe0TCqKME"; const privateVapidKey = "4AoSsRHFaHv0Fupd2NRtrungJF2jkqgccTu-WEc781w"; // Setup the public and private VAPID keys to the web-push library. webpush.setVapidDetails("mailto:test@test.com", publicVapidKey, privateVapidKey); // Create a route to allow the client to subscribe to push notification.
app.post('/subscribe', (req, res) => { const subscription = req.body; res.status(201).json({}); const payload = JSON.stringify({ title: "Hello World", body: "This is your first push notification" }); webpush.sendNotification(subscription, payload).catch(console.log); }) const PORT = 5001; app.listen(PORT, () => { console.log("Server up and running on port " + PORT); });
Inside subscribe route we can start sending push notifications but it needs to pass the string as the value. If you want to send the JSON object, you need to send it as a string and need to parse it on the client side.
Below is an example of sending a push notification to the clients device.
const payload = JSON.stringify({ title: "Hello World", body: "This is your first push notification" }); webpush.sendNotification(subscription, payload).catch(console.log);