Send Firebase Web Push Notification with NodeJs

NodeJs

Sending Web Push Notification using NodeJs

Recently I was exploring NodeJs for learning and I had bit tough time in figuring out how to send Firebase PushNotifications with NodeJs. In this blog, I am going explain how to do this.

What is Web Push Notification?

Web push notifications are clickable rich content messages sent to your device by a website or a web app. Push notifications are delivered to your mobile device or desktop, even when your browser is closed. These notifications can only be sent to users who have subscribed for these notifications from a specific website. As these notifications are pushed to user’s device, users don’t have to be present on the specific website to receive these notifications.

Push Notifications are best used for delivering content in a timely manner and engage users. Other common use cases include retargeting, activation and retention.

For this blog we assume that you have added Firebase registration process on server side and getting following three fields from your client app.

1) Auth Key

2) p256dh

3) Endpoint

You will get this three things when you register for web push notification with Firebase. You have to save this on server for sending push notifications.

First of all for sending web push notifications you will need to install npm module web-push

If you have not installed it yet. Please install it first.

npm install web-push –save

Now that you have it installed, use following code to send Web Push Notifications.
const webpush = require(‘web-push’);
const sub = {
            “keys” : {
                “auth” : “AUTH_KEY”,
                “p256dh” : “P256DH”
            },
            “endpoint” : “END_POINT”
    };
const params = {
        title: ‘Test title’,
        message: ‘Hi How are you doing?’
    };
webpush.setGCMAPIKey(‘YOUR_API_KEY);
webpush.sendNotification(sub, new Buffer(JSON.stringify(params), ‘utf8’))
         .then(
             function (data) {
                 console.log(“sucesss”);
             },
             function (err) {
                console.log(err);
             }
         )
         .catch(function (ex) {
             //return callback(new Error(ex), null);
         }
    );
That’s it and now you will be able to send PUSH notifications using NodeJs
Hope this helps you.

Leave a Reply

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