Firebase Cloud Messaging to receive Push Notification in Ionic 4 Vue app using Capacitor.

Swati Munda
TechShots
Published in
4 min readMay 3, 2020

We will be focusing on the Ionic framework 4 with Vue as the front-end framework, and Capacitor as runtime and build environment and firebase-admin for both IOS and Android.

Structure of post

  1. Firebase setup for IOS and Android & Package Installation
  2. Push notification code implementation
  3. Build and test from FireBase console.
  4. Configure server with firebase-admin to send push from the server.
  5. Send push notification from the server.

Let’s get started with the Ionic Vue Push Notification app!

# Firebase setup for IOS and Android

Android:

Assuming that your app is already set up with firebase.
You’ll first have to create an Android app in Firebase console. During the process, it will ask you to enter the app’s package name and provide google-services.json.

Download google-services.json and add to your project in android/app folder.

Your App/build.gralde should have

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

Your Project/build.gralde should have

dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.3.2'
}

You can update to latest Gradle as the new version is already available.

IOS:

Register the IOS app and download GoogleService-Info.plist and place it inside ios/App/App.

# Package Installation

capacitor-fcm

Capacitor plugin to enable features from Firebase Cloud Messaging

npm i capacitor-fcm

This plugin is intended to be used combined with Capacitor API for Push Notifications. Capacitor only provides APN token whereas this plugin offers the possibility to work with FCM tokens and more.

import { FCM } from "capacitor-fcm";const fcm = new FCM();

Implementation :

Get FCM token instead of the APN one returned by the capacitor.

PushNotifications.register()fcm.getToken().then(r => alert(`Token ${r.token}`)).catch(err => console.log(err));

# Push notification code implementation

The Capacitor has an in-built Push Notifications API that provides methods for registering a device to receive notifications from a server, along with processing received notifications and responding to them.

Access it by importing in your app

import { Plugins, PushNotification} from '@capacitor/core';
const { PushNotifications } = Plugins;
import { Plugins, PushNotification} from '@capacitor/core';
const { PushNotifications } = Plugins;
export default {
async pushInit() {
try {
PushNotifications.addListener('registrationError', (error) => {
console.log(`error on register ${JSON.stringify(error)}`);
});

PushNotifications.addListener('pushNotificationReceived'
(notification) => {
console.log(`notification ${JSON.stringify(notification)}`);
});

PushNotifications.addListener('pushNotificationActionPerformed',
async (notification) => {
// Do something
});

PushNotifications.register();
const fcmToken = await fcm.getToken();
} catch (e) {
console.log(e);
}
},
};

You can call pushInit() when your app just starts(in App.vue).

#Test push on android and ios from Firebase Console

To send a notification, we can use Firebase console → Cloud messaging section. Just put your registration token (device token, which you received after registering the device on FCM) and message. Click send.
You will see a notification pop up on your device.

Let’s extend this topic and send a notification from the server.

# Configure server with firebase-admin to send push from the server.

The Firebase Admin Node.js SDK enables access to Firebase services from privileged environments (such as servers or cloud) in Node.js.

The Firebase Admin Node.js SDK is available on npm as firebase-admin:
On server-side, do the following:

$ npm install --save firebase-admin

To use the module in your application, require it from any JavaScript file:

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

To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.

You can check how to authenticate and download the key here :

https://firebase.google.com/docs/admin/setup/#initialize-sdk

Initialize the SDK as shown:

Here I have generated a private key file that is in JSON format.

const app = admin.initializeApp({
credential: admin.credential.cert(path to private key file),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground — essentially, whether or not it is active at the time of receipt.

  • When in the background, apps receive the notification payload in the notification tray and only handle the data payload when the user taps on the notification.
  • When in the foreground, your app receives a message object with both payloads available.

Here is a JSON-formatted message and how the same message can be used across platforms (ios and android):

{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Kill the Notifications",
"body":"Kill'em all!"
},
"android":{
"ttl":"86400s",
"notification"{
"click_action":"OPEN_ACTIVITY_1"
}
},
"apns": {
"headers": {
"apns-priority": "5",
},
"payload": {
"aps": {
"category": "NEW_MESSAGE_CATEGORY"
}
}
},
}
}

Code to send messages:

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
tokens: registrationTokens,
data: notification_payload, // the payload which we discussed above with appropriate notification title and body.
}
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');

That’s it. It is done.

I hope you are able to set up your push notifications. Feel free to reach out to me if found any issues or stuck somewhere. I would be happy to help. Thanks.

--

--