Firebase push notifications on mobile devices

We all have been there. More and more notifications pop up on our mobile devices, and we keep asking ourselves how it all works. In this article I’m going to tell you how to set up notifications with Firebase Cloud Messaging (FCM) on an app built with Node.js and Ionic frameworks. What’s more, I will create a notification service that will make it possible to send push notifications to both Android and iOS. Let's first take a look at what notification are.

Push notifications

Push notifications are short messages that the web resource sends to mobile devices of its subscribers. These notifications return the user to the application he has already visited (and they do it much more efficiently than contextual advertising or any other type of mass mailings). The technical capabilities of push-mailings allow us to develop a more productive and “responsive” marketing strategy to user behavior.

Notifications with Firebase

FCM is a one-stop shop for implementing push notifications. So, if you need to deploy with more sophisticated messaging requirements, FCM is probably the right choice for you. Firebase Notifications is a flexible platform for notifications and does not require much coding. Using FCM allows developers to easily send messages, promote the development of applications, attract and retain users, and support marketing campaigns.

Environment setup

First of all, you need to sign in a Firebase account, and add a project in it. Enter the package name and click Register app for the application. Now download the google-services.json file. If you click on iOS, you will get GoogleService-Info.plist instead of the json file. Keep it at the root of your project. We also need to add the Firebase library to the project: npm install firebase --save

Now let’s move on to programming!

We’ll kick off by coding the frontend module that manages notifications. First, you need to store a Firebase token for each user when logging into profile.

import { NavController, Platform } from 'ionic-angular';
import { Firebase } from "@ionic-native/firebase";

export class LoginPage {
    firebaseToken: string;
    constructor(
        private platform: Platform,
        private firebase: Firebase,
        public navCtrl: NavController
    ) {
        if (this.platform.is('android')) {
            this.firebase.getToken()
            .then(token => {
                this.firebaseToken = token;
            });
        }
        if (this.platform.is('ios')) {
            this.firebase.getToken()
            .then(token => {
                this.firebaseToken = token;
            });
            this.firebase.hasPermission()
            .then(permission => {
                if (!permission.isEnabled) {
                    this.firebase.grantPermission();
                }
            });
        }
    }
    login() {
        this.navCtrl.push('LoginPage', { firebaseToken: this.firebaseToken });
    }
    signup() {
        this.navCtrl.push('SignupPage', { firebaseToken: this.firebaseToken });
    }
}

Now that we have users and their tokens, we can send notifications from one device to another. The backend Node.js module is the following:

const fcm = new FCM(“server_key”);  
const message = {
    to: “Firebase Token of receiver”,
    data: {
        your_custom_data_key: “accepted_invitation”
    },
    notification: {
        title: “Title of your push notification”,
        body: “Body of your push notification”
    },
};
fcm.send(message)
.then(function(response){
    console.log("Successfully sent with response: ", response);
})
.catch(function(err){
    console.log("Something has gone wrong!");
    console.error(err);
});

The server key is in your app Settings > Cloud Messaging. You can get more information on the message parameters in Firebase documentation Now we can receive notifications from our app, but clicking on one of them will simply launch the app. Next, we need to set up the behaviour so that clicking a specific push notification will open a relevant app screen.

How to customize the visibility of a particular page?

We can notice that we get the field your_custom_data_key: “accepted_invitation” from the backend. We can send any data via this field and set up different cases for conversions to the relevant pages of our application.

import { Platform } from 'ionic-angular';
import { Firebase } from "@ionic-native/firebase";
constructor(
    platform: Platform,
    private firebase: Firebase
) {
    platform.ready().then(() => {
        this.firebase.onNotificationOpen().subscribe(
        (notification) => {
            const redirect = notification.your_custom_data_key;
            const tap = notification.tap;
            let page = {component: " "};
        if(tap) {
            switch (redirect) {
                case 'accepted_invitation':
                page.component = ‘InvitationPage’;
                this.openPage(page);
                break;
                default:
            }
        }else {
            switch (redirect) {
                case 'accepted_invitation':
                this.presentToast(notification.body);
                break;
                default:
            }
        }
    }, (error) => {
        console.error(error);
    }
);

Now there you have it, the main process for storing firebase tokens, getting and opening notifications in the application. Most of the mobile apps now offer push notifications for better communication with the user. Unlike web apps, where users tend to opt out of notifications, mobile users mostly agree to receive them. There are tons of other opportunities to expand on from here, for example customer segment notifications, A/B testing, topic subscriptions and many more. Sounds interesting? Reach out Bitcom Systems experts for more tips!