This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

How To Make Push Notification Using Node.js and Service Worker


We’d discover push notifications on cellular actually helpful as a result of an internet server can talk straight with the app when it needs.

However app customers have to grant permission to obtain the push notifications first.

We will merely create the push notification utilizing solely Node.js, Categorical.js and Net-Push.



Pattern Code

You’ll find sample code here that is the entire code of this tutorial.



Let’s Get Began!

Let’s create a listing that accommodates our Categorical.js app.

mkdir web-push-sample
cd web-push-sample
Enter fullscreen mode

Exit fullscreen mode

Then set up mandatory libraries.

npm init 
npm i categorical body-parser web-push
Enter fullscreen mode

Exit fullscreen mode

Subsequent we’ll create begin script by add node index.js to your begin script

{
  "identify": "web-push-sample",
  "model": "1.0.0",
  "predominant": "index.js",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.2",
    "categorical": "^4.17.3",
    "web-push": "^3.4.5"
  },
  "scripts": {
    "begin": "node index.js"
  }
}
Enter fullscreen mode

Exit fullscreen mode



Generate VAPID Keys for push notifications

VAPID, which stands for Voluntary Utility Server Identification is a brand new option to ship and obtain web site push notifications. Your VAPID keys assist you to ship net push campaigns with out having to ship them by way of a service like Firebase Cloud Messaging (or FCM). As a substitute, the appliance server can voluntarily establish itself together with your net push supplier.

I’ve two advisable methods to create VAPID Keys



1) Generate from vapidkeys.com

Simply undergo the web site, enter the e-mail deal with. It’s used to provide particulars concerning the sender. Use it as an identifier.

Then click on the “generate” button. You must get the JSON object that accommodates topic which is your given e-mail deal with.

And you’ll get each private and non-private keys.

VAPID Keys generated from vapidkeys.com

Very easy proper?



2) Generate by Command Line

For those who do not need to use the net providers, you possibly can generate it by way of the command line. So open your terminal and enter this command.

./node_modules/.bin/web-push generate-vapid-keys
Enter fullscreen mode

Exit fullscreen mode

It ought to returns one thing like this…

=======================================

Public Key:
BO4imRW5SYfMtEUyfwMrrxvzJjuoThJ1FNqiUX3Z0C93Ajdrhdy0rX5iwvGBWHffmH3nP-NhVsF5XXbnHxsUnrg

Non-public Key:
yI31gBBUlJYKj_7wZmPZsLGFklxNMVSk_9UVpWBXEHc

=======================================
Enter fullscreen mode

Exit fullscreen mode



Setup the Subscription Route

Subsequent you will have to create categorical app and setup the route for enable shopper to subscribe to your push notification

const categorical = require('categorical');
const webpush = require('web-push');
const bodyParser = require('body-parser');
const path = require('path');

// Create categorical app.
const app = categorical();

// Use physique parser which we'll use to parse request physique that sending from shopper.
app.use(bodyParser.json());

// We are going to retailer our shopper information in ./shopper listing.
app.use(categorical.static(path.be part of(__dirname, "shopper")))

const publicVapidKey = "BOd2EQ8LTe3KAgMX9lWwTlHTRzv1Iantw50Mw6pUnsNr3pcxl8iglUs-YlQEQLo4UbJk9oyXs_BxgyAe0TCqKME";

const privateVapidKey = "4AoSsRHFaHv0Fupd2NRtrungJF2jkqgccTu-WEc781w";

// Setup the private and non-private VAPID keys to web-push library.
webpush.setVapidDetails("mailto:take a look at@take a look at.com", publicVapidKey, privateVapidKey);

// Create route for enable shopper to subscribe to push notification.
app.publish('/subscribe', (req, res) => {
    const subscription = req.physique;
    res.standing(201).json({});
    const payload = JSON.stringify({ title: "Hi there World", physique: "That is your first push notification" });

    webpush.sendNotification(subscription, payload).catch(console.log);
})

const PORT = 5000;

app.pay attention(PORT, () => {
    console.log("Server began on port " + PORT);
});
Enter fullscreen mode

Exit fullscreen mode

Inside subscribe route we can even begin to sending first push notification however it have to cross the string as the worth.
If you wish to sending the JSON object, you will have to ship as a string, and parse it on shopper facet.

Beneath are the instance on sending push notification to the shopper.

const payload = JSON.stringify({ title: "Hi there World", physique: "That is your first push notification" });

    webpush.sendNotification(subscription, payload).catch(console.log);
Enter fullscreen mode

Exit fullscreen mode



Create Service Employee to Eat Push Notification

We are going to want 3 information in shopper listing to begin to eat our push notifications

1) index.html – Our touchdown web page that can make use our predominant javascript file.
2) shopper.js – Our predominant JavaScript file which can register our service employee.
3) employee.js – Our Service Employee JavaScript file which can deal with the push notifications.

Let’s create index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Appropriate" content material="IE=edge">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Push Notification Utilizing Net-Push</title>
</head>
<physique>
    <h1>Push Notification Utilizing Net-Push</h1>

    <script src="./shopper.js"></script>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Then create the shopper.js and register our employee.

We might want to copy our public keys and retailer it to some variable.

const publicVapidKey = "BOd2EQ8LTe3KAgMX9lWwTlHTRzv1Iantw50Mw6pUnsNr3pcxl8iglUs-YlQEQLo4UbJk9oyXs_BxgyAe0TCqKME";
Enter fullscreen mode

Exit fullscreen mode

Then we write the operate to subscribe the push notification.
We create the subscription object then ship the POST request to our API endpoint and fix that subscription object because the payload.

async operate registerServiceWorker() {
    const register = await navigator.serviceWorker.register('./employee.js', {
        scope: '/'
    });

    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: publicVapidKey,
    });

    await fetch("/subscribe", {
        methodology: "POST",
        physique: JSON.stringify(subscription),
        headers: {
            "Content material-Kind": "software/json",
        }
    })
}
Enter fullscreen mode

Exit fullscreen mode

Lastly we make use this operate after we test that our present net browser helps Service Employee

if('serviceWorker' in navigator) {
    ship().catch(console.log)
}
Enter fullscreen mode

Exit fullscreen mode

So the ultimate look of shopper.js will likely be like this


async operate registerServiceWorker() {
    const register = await navigator.serviceWorker.register('./employee.js', {
        scope: '/'
    });

    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: publicVapidKey,
    });

    await fetch("/subscribe", {
        methodology: "POST",
        physique: JSON.stringify(subscription),
        headers: {
            "Content material-Kind": "software/json",
        }
    })
}
Enter fullscreen mode

Exit fullscreen mode



Create Service Employee

Create employee.js we’ll add occasion listener inside this file. After we present the notification, we might want to cross title and physique because the parameters.

We add occasion listener to push occasion. Parse information as a JSON object. Then can self.registration.showNotification methodology then cross title and physique.

self.addEventListener('push', operate(e) {
    const information = e.information.json();
    self.registration.showNotification(
        information.title,
        {
            physique: information.physique,
        }
    );
})
Enter fullscreen mode

Exit fullscreen mode

That’s all about it!



Let’s take a look at notification service.

On this instance I’ll use Google Chrome for testing.

Please just remember to enable notification on Google Chrome.
For those who utilizing Mac it would disabled on the primary time. And you will have to allow it.

Go to Notification Middle then discover the Google Chrome and permit notification. Make certain the Enable Notification enabled.

Enable notification for Google Chrome on Mac



Begin Our Service

Begin the app utilizing the command beneath

npm begin

Server began on port 5000
Enter fullscreen mode

Exit fullscreen mode

Open your browser and navigate to http://localhost:5000

It ought to present the push notification permission request dialog. Simply click on enable.

Push Notification Subscription Dialog

however in some case it may not present. However have the lock icon in navigation bar. Clicking on it and permit

Unblock Push Notification

Then you need to get the primary notification. (If not refresh the web page as soon as)

Sample of notification

Congratulations! You probably did it. That is your first push notification.



Tip: Simulate Extra Push Notification

We will simulate extra push notification that we will obtain. Let assume that you simply nonetheless shopping by way of Google Chrome Proper now you possibly can open the Google Chrome DevTool and go to Utility tab navigate to ServiceWorker menu.

You will note your employee.js file has been registered there.

Scroll down a bit, you possibly can see the push textual content field.

Put some take a look at JSON object there and press push button then you possibly can see extra notifications. Simply take pleasure in with it.

That is means in case you ship any extra push notification out of your net server. It’s going to additionally appeared on person’s browsers as nicely (so long as they select to subscribe to your push notification)



Conclusion

We will simply create our push notifications utilizing web-push with out utilizing a third occasion service like Firebase Cloud Messaging (FCM).

Through the use of the brand new means to supply self hosted push notifications referred to as VAPID (Voluntary Utility Server Id)

Then we create and set up Service Employee that interacts after receiving the brand new push notifications. Exhibiting notification is the selection. The important thing level is that after you subscribe to web-push efficiently, you possibly can obtain push information anytime. You may use that info in methods you possibly can’t think about.



Assets

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?