Simplifying Push Notifications: Firebase Cloud Messaging Integration with Node.js

In this blog post, we’ll cover everything you need to know to effectively integrate Firebase Push Notifications with Node.js. Here’s a brief overview of what you can expect to learn.

Prerequisites

Node.js Environment: Ensure Node.js is installed on your development machine for running the backend application.

npm (Node Package Manager): Ensure npm is available for installing packages, including the Firebase Admin SDK.

Understanding of Firebase Cloud Messaging: Have a basic understanding of FCM, including sending messages and configuring targets.

Client-Side Integration: Integrate Firebase JavaScript SDK into your client-side application (e.g., React, Angular, Vue.js, or plain JavaScript).

Set up FCM within your Firebase project for the client-side application.

Obtain registration tokens from FCM on the client side to identify app instances. Implement logic to handle incoming notifications in your client-side application.

Introduction to Firebase Push Notifications

Firebase is a comprehensive platform provided by Google for building mobile and web applications. One of its powerful features is Firebase Cloud Messaging (FCM), which enables you to send push notifications to your users’ devices efficiently. When integrated with Node.js, you can leverage the Firebase Admin SDK to send push notifications programmatically from your server.

Firebase Push Notifications are a vital tool for engaging users and delivering timely updates in mobile and web applications.

With FCM, you can send two types of messages to clients:

  • Notification messages, are sometimes thought of as “display messages.” These are handled by the FCM SDK automatically.
  • Data messages are handled by the client app.

Related read: Real-Time Engagement: Firebase Push Notifications with React.js and Python

Firebase Project Creation

  • Visit Firebase Console
  • Sign in or Create Account: Sign in with your Google account. If you don’t have one, create a new account.
  • Create a New Project: Click “Add project” and enter a name, project ID, and select your region.
  • Finish Project Creation: Click “Create project” and wait for the project creation to complete.
Firebase-Dashboard
Fig: Firebase Project Dashboard
  • Project Dashboard: Once created, you’ll be redirected to the project dashboard where you can manage your Firebase project.
Push-Notification-Demo
Fig: Push Notification Demo

Create a New Node.js Project and Install Required Packages

  • Create a new directory for your Node.js project.
  • Open a terminal or command prompt, navigate to the project directory, and initialize a new Node.js project
> npm init -y
  • Install the necessary packages for your Node.js project
> npm install express cors
  • Set Up Express Server:
Project-Overview
Fig: Firebase Project Overview
import express, { json } from "express";
import cors from "cors";

const app = express();

app.use(cors());
app.use(express.json());

const PORT = process.env.PORT || 8000;

app.listen(PORT, () => {
console.log(`Server Started at Port ${PORT}`);
});

Firebase Admin SDK Setup

  • Install Firebase Admin SDK: In your Node.js project, install the Firebase Admin SDK package:
> npm install firebase-admin -save

Obtain Service Account Credentials:

  • In the Firebase Console, go to Project Settings > Service accounts.
  • Click on “Generate new private key” to download a JSON file containing your service account credentials.

Firebase-Project-Setting

unnamed-18
Fig: Firebase Project Setting
Set Up Environment Variables:
  • Store the path to the downloaded JSON key file in an environment variable. This is typically named GOOGLE_APPLICATION_CREDENTIALS.
  • Or if you are using Windows.

Take your Node.js app to the next level with Firebase Push Notifications. Hire Our Developers!

Important Step :

  • Add path of JSON file containing your service account credentials to GOOGLE_APPLICATION_CREDENTIALS variable and run on shell or terminal.
> export GOOGLE_APPLICATION_CREDENTIALS="/home/path****.json"

Here’s why you need to run export GOOGLE_APPLICATION_CREDENTIALS=”${path}” in the terminal:

Windows-Powershell-Terminal
Fig: Windows Powershell Terminal
  • Authentication: Firebase uses service accounts to authenticate server-to-server communication. These service accounts are represented by a JSON file that contains a private key and other authentication information. By setting the GOOGLE_APPLICATION_CREDENTIALS environment variable, you’re telling Firebase SDKs where to find this JSON file containing the credentials.
  • Security: Storing sensitive information like service account credentials directly in your codebase is not recommended due to security concerns. By specifying the path to the JSON file containing the credentials using an environment variable, you keep these credentials separate from your code and minimize the risk of accidental exposure.
  • Flexibility: Using an environment variable allows you to easily switch between different service account credentials for different environments (e.g., development, staging, production) without modifying your code. You can set the environment variable differently on each environment, pointing to the corresponding JSON file.

Initialize Firebase Admin SDK:

  • In your Node.js application, initialize the Firebase Admin SDK with the service account credentials:
  • Add GOOGLE_APPLICATION_CREDENTIALS environment variable.

Add the relative path of the JSON file containing your service account credentials to GOOGLE_APPLICATION_CREDENTIALS variable

const GOOGLE_APPLICATION_CREDENTIALS="push-notificat******.json"
import { applicationDefault, initializeApp } from "firebase-admin/app";

process.env.GOOGLE_APPLICATION_CREDENTIALS;

initializeApp({
credential: applicationDefault(),
projectId: "push-notification-demo***", // <FIREBASE_PROJECT_ID>
});

Send Push Notification Using FCM

  • With Firebase Admin SDK initialized, you can now use it to send messages via FCM. Here’s a basic example
import { getMessaging } from "firebase-admin/messaging";
  • You construct a message object containing the notification payload, including the title and body of the notification. You specify the device registration token of the device you want to send the notification.
  • Specify the registration token of the device to which you want to send the notification. This token uniquely identifies the device within the Firebase Cloud Messaging system.
  • After sending the notification, you handle the response from the Firebase Cloud Messaging (FCM) server. If the notification is sent successfully, you’ll receive a response with details about the message ID. If there’s an error, you’ll receive an error response.
app.post("/sendNotification", (req, res) => {
const receivedToken = req.body.fcmToken; // Fcm token received by front end application
const message = {
notification: {
title: "Notification Received !",
body: "You received this push notification using Firebase and Node js ",
},
token: receivedToken,
};
getMessaging()
.send(message)
.then((response) => {
res
.status(200)
.json({ message: "Notification Sent", token: receivedToken });
console.log("Notification Sent");
})

.catch((error) => {
res.status(400).send(error);
console.log("Error sending message:", error);
});
});
  • If you want to send notifications to multiple devices, you can modify the message object to include an array of device registration tokens
const message = {
notification: {
title: "Notification Title",
body: "Notification Body",
},
tokens: [
"device_registration_token_1",
"device_registration_token_2",
"device_registration_token_3",
"device_registration_token_4",
//list containing up to 500 registration tokens.
],
};

Test Implementation

  • Start your Node.js application and trigger the push notification sending logic to verify that notifications are being sent successfully.

If you’ve already integrated the Firebase JavaScript SDK into your client-side application and obtained the registration tokens from Firebase Cloud Messaging (FCM) on the client side, you can use these registration tokens to send notifications from your server-side Node.js application.

  • Here, I am using Postman to test Push Notifications using FCM Token on the client side
Send-Notification
Fig: Notification Received Overview

Unleash the full potential of push notifications to enhance user engagement and provide a personalized experience for your audience.

coma

Conclusion

Firebase Cloud Messaging (FCM) equips Node.js applications with powerful real-time push notification capabilities, fostering user engagement. This guide has provided insights into setting up FCM, sending notifications, and leveraging its features. Delve deeper into FCM to tailor notifications for your specific application requirements. Thank you for exploring FCM with us.

Keep Reading

Keep Reading

Launch Faster with Low Cost: Master GTM with Pre-built Solutions in Our Webinar!

Register Today!
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?