How To Send Notification In Node JS using Firebase Database

Devendra Patil
Canadiv’s Technology and Design
4 min readSep 9, 2023

What are notifications?

A notification is a message that Android displays outside your app’s UI to provide the user with reminders, communication from other people, or other timely information from your app.

Types of notifications

Depending on the type of application you are designing, notifications can be divided into two main groups by answering the following questions:

1. Does the notification require an action?
For example, when your team just released a new feature and you would like your users to try it. This type of message prompts users to complete a certain action, and should be displayed differently in comparison to more passive messages.
Notifications might just consist of information that you think will be interesting or helpful for your users, but don’t require any particular action. For example by congratulating your user on achieving a goal, when collecting points or a achieving a certain number of steps in fitness tracking apps.

2. Was the notification triggered by an event?

There are three types of events that can trigger a notification, depending on what events occured before:
- triggered by the user: for example mobile messaging, where the content is directed specifically to a particular user
- triggered by the system: specific to the system, for example a request to install an update
- event based notifications: triggered based on actions completed by the user within a software, for example recommending tax saving option when a user is adding a particular category of expenses.

Difference between Push and Text Messages

Text messages or SMSes might seem like an old approach to reaching customers. However, it can be an effective medium to reach out to customers, especially those who do not have a smartphone to install the app. You can also automate SMS campaigns using automation tools.

The drawback is that you cannot add rich media content such as GIFs, animations, and emojis to make the text visually appealing. Push notifications let you do that. There are legal limitations, such as certain countries having a cap on the number of text messages you can send daily. Push notifications have no such limits.

Another significant difference is it’s easier to opt out of push messages than messages. While this might seem like good news to marketers, your customers may find your text messages intrusive and spam and may even choose not to engage with you anymore. This can have a significant impact on customer loyalty.

Now we should go step by step to reach our destination, For sending the notification to the user using the code which platform we are using is listed below.

  1. Node js (Express).
  2. Firebase.

Now Initialize our node js Application.

I assumed that node js is already installed on your machine.

Before starting any new Node.js project we should run npm init to create a new package.json file for our project.

npm init

and also install our required extensions like

npm i express fcm-node

we use Firebase cloud messaging for sending notifications. Then our package.json file looks like this

{
"name": "send_notification",
"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"
}
}

now we are creating a file name index.js so here is a sample code for sending notifications. now our index.js file looks like this.


export const TestNotification = functions.firestore
.document("product/{id}")
.onCreate(async (snap) => {

const db = admin.firestore();
const fcm = admin.messaging();
const data = snap.after.data();
if (data) {
const profile = await db.collection("users").doc(data.createdBy).get();
if (profile) {
const token = profile.data()?.tokens;
if (token.length > 0) {
for (let index = 0; index < token.length; index++) {
const element = token[index];
const payload = {
notification: {
title: "Test",
body: "Congratulations! You have registered your child"
sound: "default",
},
};
const res = await fcm.sendToDevice(element, payload);
console.log("sent..", JSON.stringify(res));
}
}
}
}

in this sample code we get our users we want to send notifications on their devices like ios/android

And we have also saved secret tokens for each user on the user Document and if the user login on 2/3 of the devices also we send a notification on all devices. Once we get the token then we send a notification bar when the user is not working on the Application or an App notification when the user is working on the Application.

Note: this function we are created on the onCreate method if we want we have also sent a notification onUpdate method as per our requirement

Hey! Now it's time to deploy our code on our Firebase. deploy it by clicking on deploy on the package.json file and our function is deployed successfully….
now

--

--