How to send push notifications to android devices in Nodejs

How to send push notifications to android devices in Nodejs

01 December 2021

In this blog, we will explore how to send push notifications to android devices from the Nodejs applications.

Push notifications are the notification which pops up on the mobile screen using fcm messages.

Firebase Cloud Messaging is a used to that helps to safely deliver messages at no cost.

First, we need to sign in at firebase using a Google account. There will be a ‘Go to console’  link, you need to click on the link and will be redirected to the dashboard.

If you don’t have any project, click on ‘create project’.

How-to-send-push-notifications-to-android-devices-in-Nodejs-image1-1024x497

You need to provide the name of the project, accept the terms, and do all the necessary steps. After completing it, a new project will be created and will be redirected to the dashboard.

We are done creating the firebase account.

To send the push notification to an android device, we will need the following:

  • FCM Server Key
  • Registration Token

FCM Server Key:

FCM Server Key will be generated automatically when we create a firebase project. Go to project settings and go to cloud Messaging tab and Inside project credentials, you can find server key.

We need to copy the ‘Server Key’ value and use it while sending push notifications.

Registration Token:

Registration Token will be generated from the mobile application and sent to the NodeJS backend using the API from where we will send the push notification.It is used to inform the Nodejs backend to which device it should send.

Nodejs Backend

In the Node Js project, you can use the ‘fcm-node’ package for sending push notifications to the android device.

  • Installation of fcm-node
    $ npm install fcm-node
  • Copy the fcm server key from the firebase account and pass the key to the FCM constructor.
  • Create a message object and invoke the send() function
  • Message object:
    • to:- provide the registration token (device token)
    • collapse key:-  provide the collapse key
    • Notification object:- create a notification object providing the title of the notification (will be shown on mobile), message body, sound, and delivery receipt boolean value.
    • We can send only notification or only data or include both (data or notification)

Example Code:

How-to-send-push-notifications-to-android-devices-in-Nodejs-image2

search
Blog Categories
Request a quote