How to set up Firebase Push Notifications with Ionic & Vue.js
Tags: ionic, vue, firebase, mobile
Published: 2021-05-10 10:31:25

Did you have issues configuring Push Notifications with Ionic & Vue.js? Did you not found the documentation for Vue, but only for Angular? *This is something I had too* and that's why I have decided to make this post. By the end, you have your Ionic application ready and working with Firebase's Cloud Messaging service.
Plus, you will found a repository with a basic app that has already everything up to work.

So let's begin!

# Step 1 - Create our app

First of all, make sure to create a new Ionic Vue.js app with [Ionic CLI](https://ionicframework.com/docs/cli). Open your Terminal or CMD/PowerShell and write

```ionic start --type=vue```

Set all the requirements for your application and open the folder of your project with your favourite code editor.

Open the file **capacitor.config.json** and set an **appId**. Could be for example: **com.myionicapp.demo**
![appId](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cim8zyz7ugdd5k66klr5.png)

Now go on [Firebase](https://firebase.google.com/), select Get Started & Add Project.

On Android package name set the appId that you had set previous on your **capacitor.config.json**.
![Firebase appId](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ds609d1kp96fir8k1x5n.png)

Save **google-services.json**. We need it later to configure correctly our application with Firebase.
![JSON File](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjy969wrptdx94yrsgez.png)

# Step 2 - Integrate Firebase plugin

To begin, we need to install [Capacitor Firebase Cloud Messaging plugin](https://github.com/capacitor-community/fcm). You can do with a simple command: ```npm i @capacitor-community/fcm```

Open your **App.vue** file with your code editor. And... Oh, wait!

Thanks to **Elbphilharmonie** via [StackOverFlow](https://stackoverflow.com/questions/66206543/capacitor-typeerror-cannot-read-property-gettoken-of-undefined)
We now know how to set it correctly and avoid the result of **undefined**. 
*I had it too*
First, we need to import FCM by add this line to **App.vue**:
```import { FCM } from '@capacitor-community/fcm';```

Then after components, add this line:
```,
  data() {
    return {
fcm: new FCM()
    }
  },
```
In this way, we have avoided this potential issue. But we need to execute it to generate a token and communicate with [Push Notifications](https://capacitorjs.com/docs/apis/push-notifications) from Capacitor.

# Step 3 - Integrate Capacitor Plugin

Let's begin by importing Push Notifications' plugin. Add this line to **App.vue**:
```import { Plugins } from '@capacitor/core';
const { PushNotifications } = Plugins;```

And a [mounted](https://v3.vuejs.org/api/options-lifecycle-hooks.html#mounted) method with this function:
```
// Request permission to use push notifications
    // iOS will prompt user and return if they granted permission or not
    // Android will just grant without prompting
PushNotifications.requestPermission().then(result => {
      alert("result " + JSON.stringify(result));
    });
         // Add registration error if there are.
        PushNotifications.addListener("registrationError", (error) => {
          console.log(`error on register ${JSON.stringify(error)}`);
        }),
        // Add Notification received
          PushNotifications.addListener(
            "pushNotificationReceived",
            (notification) => {
              console.log(`notification ${JSON.stringify(notification)}`);
            }
          ),
          // Add Action performed
          PushNotifications.addListener(
            "pushNotificationActionPerformed",
            async (notification) => {
                alert("notification " + notification)
              console.log("notification succeeded");
            }
          ),
          // Initialize the registration with FCM Token
          PushNotifications.register();
        const fcmToken = this.fcm.getToken();
       alert(JSON.stringify(fcmToken));
        console.log("token:" + JSON.stringify(fcmToken));
  },
```

**Remember:** You cannot test this function with a web browser. Because FCM and Push Notifications plugin doesn't have a web implementation.

# Step 4 - Build Android app

We need to add support for the Android platform. Let's do it by following the [Ionic documentation](https://ionicframework.com/docs/vue/your-first-app/6-deploying-mobile).

*For your convenience, I leave here all the steps that you need.*

```
ionic build
ionic cap add android
ionic cap copy
ionic cap sync
ionic cap open android
```

Before you build the app, you need first to copy the file **google-services.json** from Firebase into **android/app**. Then on Android Studio, 
select app -> the folder with the name of your app -> **MainActivity.java**

And add the following code after ```import java.util.ArrayList;```
```
import com.getcapacitor.community.fcm.FCMPlugin;
```

Then into **// Initializes the Bridge**
```
add(FCMPlugin.class);
```

Save it.

# Step 5 - Optional

**Is your MainActivity.java flagged with the red color?** Something went wrong and the main issue is Android Studio isn't capable to load the package com.getcapacitor.community.fcm.FCMPlugin. 
Thanks to **wekas** at [Ionic Forum](https://forum.ionicframework.com/t/capacitor-community-firebase-analytics-not-working/199294/3), we have the solution for this issue.
On Android studio follow these steps:

```
Build -> Clean Project
File -> Sync Project With Gradle Files
Run
```

Voilà! Now build your Android App and test it on your device.

# Step 6 - Test the notification

We can send a test notification to see if everything is set up correctly.
Connect to [Firebase](https://firebase.google.com/) select your project --> See all features --> Cloud Messaging -> Send your first message.
![Firebase Cloud Messaging](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tpw1thbqu91fklln7llt.png)

Set a title and text for it.
![Firebase Push Notification](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdde9y2fzd9p3hafcltw.png)

Now you can try to send a push notification only on your device with the token. You can have it by debugging and look into the console. Follow the [Ionic Documentation](https://ionicframework.com/docs/troubleshooting/debugging) for debugging your Ionic app.
![Firebase Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/im0m53upcfcjgdzo0qpo.png)

Or you can set the notification by completing all the Firebase steps. This will work with all devices that have installed your Ionic app. No matter if your application is open or not.

![Success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vgcy835zkv5q5hxmfv9.jpg)

# Step 7 - iOS

I'm sorry, but currently, I cannot test the application on iOS. I will update as soon I can.

# Step 8 - Source code

Do you prefer to take a look at the code? Please see [here](https://github.com/marcoimproda/ionic-vue-push-notifications-demo). I have uploaded a demo application.
Don't forget to upload your google-services.json and build & sync the code with Android Studio.

# Thanks

I hope this post could help everyone that needs to enable push notifications on their Ionic Vue application. I did my best to make it plain and simple and to provide a stable resource with an up-to-date tutorial to follow. That's it.
Let me know if you find it helpful and until then, see you next time. Ciao :)


# References
[Push Notifications with Ionic/Angular](https://capacitorjs.com/docs/guides/push-notifications-firebase)
[Firebase Cloud Messaging to receive Push Notification in Ionic 4 Vue app using Capacitor.](https://medium.com/techshots/learn-to-use-firebase-cloud-messaging-to-receive-push-notification-in-ionic-4-vue-app-using-13f5a4458b87)
[Capacitor - TypeError: Cannot read property 'getToken' of undefined](https://stackoverflow.com/questions/66206543/capacitor-typeerror-cannot-read-property-gettoken-of-undefined)
[Android Package io.stewan.capacitor.fcm.FCMPlugin does not exist](https://github.com/capacitor-community/fcm/issues/5)
[Capacitor-community / firebase-analytics not working](https://forum.ionicframework.com/t/capacitor-community-firebase-analytics-not-working/199294/3)