Node.js - Send Push Notification Message to Firebase

If you've a mobile application, you may want to send push notifications to users. There are some ways to send notifications, one of the most popular and easiest way is by using Firebase. It's a Backend-as-a-Service — BaaS application development platform. It has some features, one of which is Cloud Messaging, which is used to send targeted notifications to users. In this tutorial, I'm going to give example how to send push notifications using Firebase from Node.js application. This includes how to setup the Firebase account and how to setup Node.js application to be able to send notifications.

Setup Firebase Account

Register for a Firebase Account

The first thing you've to do is creating a Firebase account. Open the link below to start.

https://console.firebase.google.com/

Firebase Console - Create Project

If you don't have any project, add a new project. You'll be asked to enter the name for the project and accept the terms.

Get Service Account Key

In order to connect to your Firebase account, the Node.js application needs to be authenticated. It allows the generation of service account key used as credentials. Therefore, you need to create a new one. Click on the Settings icon -> Project Settings -> Service Accounts tab. Select Node.js and click on Generate new private key button.

Firebase Console - Generate Service Account Key

On the popup, click on Generate key button. A file should be downloaded to your computer.

Firebase Console - Generate Service Account Key

Setup Node.js Application

Install Dependencies

There is a library firebase-admin, which makes it easier to connect your Node.js application with Firebase service. package.json

  {
    "dependencies": {
      ...
      "firebase-admin": "~6.2.0",
      ...
    }
  }

Having installed the dependency, we can start to code. First, copy the service account key file to your project and load it by using require. Then, initialize the application by providing the credential (service account key) and database URL. The databse URL is in the format of https://your-app-name.firebaseio.com - you should see it when you created your service account key. Below is the full code example.

  const firebase = require("firebase-admin");

  const serviceAccount = require('path/to/your/firebase/secret.json');

  // The Firebase token of the device which will get the notification
  // It can be a string or an array of strings
  const firebaseToken = 'abcdeabcdeabcde';

  firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccount),
    databaseURL: "https://your-app-name.firebaseio.com"
  });

  const payload = {
    notification: {
      title: 'Notification Title',
      body: 'This is an example notification',
    }
  };

  const options = {
    priority: 'high',
    timeToLive: 60 * 60 * 24, // 1 day
  };

  firebase.messaging().sendToDevice(firebaseToken, payload, options);

Of course you've to get the Firebase token of the devices you want to send notification to. In order to send notification, the payload must have notification key which is an object which has two keys: title and body. The supported options are listed below.

  type MessagingOptions = {
    dryRun?: boolean;
    priority?: string; // normal or high
    timeToLive?: number; // in second
    collapseKey?: string;
    mutableContent?: boolean;
    contentAvailable?: boolean;
    restrictedPackageName?: string;
    [key: string]: any | undefined;
  };

Run the script to see if the code works. If you've setup everything correctly, you should see the notification on the devices.