Firebase Push Notification for Ionic App – A Step by Step Guide

Push notification is the most effective way to keep your users engaged. Nearly every modern mobile app has some sort of push notification feature built into it. This is a step by step guide to implement push notification in your Ionic app using Firebase. We’ll use Cordova Firebase Plugin and AngularFire2 plugin to achieve this.

Step 1: Initial Setup

Let’s start a new Ionic project

ionic start firebaseDemo blank --type=ionic-angular

Install Cordova Firebase Plugin

ionic cordova plugin add cordova-plugin-firebase
npm install --save @ionic-native/firebase

Install AngularFire2 to access Firestore database

npm install --save angularfire2 firebase

Let’s import everything needed in the app.module.ts file

//...
import { Firebase } from '@ionic-native/firebase/ngx';

import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';

const firebase = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  messagingSenderId: "sender-id",
}

@NgModule({
  imports: [
    //...
    AngularFireModule.initializeApp(firebase), 
    AngularFirestoreModule
  ],
  providers: [
    //...
    Firebase,
    FcmProvider
  ]
})

Step 2: Create a Provider

Now we’ll generate a provider to generate, store FCM token in the Firestore database and to listen to the incoming messages. Type the command below in the terminal to generate a provider.

ionic generate provider fcm

Import the dependencies and declare the necessary methods in the fcm.ts file

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Firebase } from '@ionic-native/firebase/ngx';
import { Platform } from 'ionic-angular';
import { AngularFirestore } from 'angularfire2/firestore';


@Injectable()
export class FcmProvider {

  constructor(
    public firebaseNative: Firebase,
    public afs: AngularFirestore,
    private platform: Platform
  ) {}

  // Generate the FCM token
  async getToken() { }

  // Save the token to firestore
  private saveTokenToFirestore(token) {}

  // Listen to incoming FCM messages
  listenToNotifications() {}
}

Now, we need to generate a FCM token inside getToken() method

async getToken() {
    let token;
    token = await this.firebaseNative.getToken()
    return this.saveTokenToFirestore(token)
  }

Now we need to store the FCM token to the Firestore database. A user can have multiple devices. So, you might want to store the user id along with the FCM token.

private saveTokenToFirestore(token) {
    if (!token) return;
    const devicesRef = this.afs.collection('devices')
    const docData = { 
      token,
      userId: 'testUser',
    }
    return devicesRef.doc(token).set(docData)
  }

Now, we’ll modify the listenToNotifications() method to listen to the incoming messages.

listenToNotifications() {
  return this.firebaseNative.onNotificationOpen()
}

Now, we’ll call the getToken() method inside the constructor of app.component.ts file. If you have login functionality built in your app, you may want to generate the FCM token during the login process. But, for now we’ll generate the token at the time of running the app. So the app.component.ts file will look this.

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { FcmProvider } from '../providers/fcm/fcm'
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, fcm: FcmProvider) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      // Get a FCM token
      fcm.getToken()
    });
  }
}

Step 3: Create a new project in Firebase


Create a new project project from the Firebase dashboard and go through the steps. After filling the necessary steps download the google-services.json file and put it in the root in your Ionic project.

Create a new database(Cloud Firestore) inside your Firebase project. You should have both read and write permissions. Now, add a collection and name it ‘ devices ‘. It should look like this.

Step 4: Troubleshooting(Optional)

Now run the app. You might get an error.

What went wrong: 
Execution failed for task ':app:fabricGenerateResourcesDebug'. 
Crashlytics Developer Tools error.  

If you get this error open platforms\android\build.gradle and replace

classpath 'com.google.gms:google-services:4.1.0'

with

classpath 'com.google.gms:google-services:4.2.0'

Again if you see

Error: Uncaught (in promise): TypeError: Object(...) is not a function
TypeError: Object(...) is not a function
    at new AngularFirestore (http://localhost:8100/build/vendor.js:67771:88)
    at _createClass (http://localhost:8100/build/vendor.js:11579:20)
    at _createProviderInstance$1 (http://localhost:8100/build/vendor.js:11543:26)
    at resolveNgModuleDep (http://localhost:8100/build/vendor.js:11528:17)
    at _createClass (http://localhost:8100/build/vendor.js:11573:68)
    at _createProviderInstance$1 (http://localhost:8100/build/vendor.js:11543:26)
    at resolveNgModuleDep (http://localhost:8100/build/vendor.js:11528:17)
    at NgModuleRef_.get (http://localhost:8100/build/vendor.js:12765:16)
    at resolveDep (http://localhost:8100/build/vendor.js:13255:45)
    at createClass (http://localhost:8100/build/vendor.js:13119:85)
    at c (http://localhost:8100/build/polyfills.js:3:19752)
    at Object.reject (http://localhost:8100/build/polyfills.js:3:19174)
    at NavControllerBase._fireError (http://localhost:8100/build/vendor.js:54543:16)
    at NavControllerBase._failed (http://localhost:8100/build/vendor.js:54536:14)
    at http://localhost:8100/build/vendor.js:54583:59
    at t.invoke (http://localhost:8100/build/polyfills.js:3:14976)
    at Object.onInvoke (http://localhost:8100/build/vendor.js:5396:33)
    at t.invoke (http://localhost:8100/build/polyfills.js:3:14916)
    at r.run (http://localhost:8100/build/polyfills.js:3:10143)
    at http://localhost:8100/build/polyfills.js:3:20242

run

npm i rxjs@^6.0 rxjs-compat

Now, if you run the app your FCM token will be added to the Cloud Firestore.

Step 5: Sending Notification

Now, to send a notification, got to the Firebase dashboard an select your project. Click on Cloud Messaging under Grow.

In this screen fill the necessary details to send a notification. If you do everything correctly you should get a notification like this.

Full source code is available at https://github.com/sky741126/Ionic-Firebase-Notification

If you have any suggestion or question please leave a comment below. If you like this article or want to help me, please consider donating anything you can.