'How to implement Firebase(FCM) Push Notifications on nuxtjs / vuejs

Having devoted many hours to search the internet for a simple and straightforward way of how to implement Firebase FCM Push Notification on my nuxt project bore no fruit.



Solution 1:[1]

"Self driven problems solver..." is one of the lines on my resume and on this one I set out to live up to my words.

So here is how to implement FCM Push Notifications on your NuxtJs/Vuejs project

Step 1

Create your nuxt app like npx create-nuxt-app <your-app-name>

Step 2

Install firebase npm install firebase and @nuxt/firebase npm install @nuxt/firebase

Step 3

Creating your firebase project

  • Go to firebase console and create a project enter image description here

  • Give it a name enter image description here

  • Enable Google analytics if you like to then click on create

enter image description here

-Get some coffee as the projects creates ?

  • On this page you want to copy the config, which we will use later

enter image description here

  • Finally, we land on the home page of our project on firebase, looks like below image

enter image description here

  • Let's go back to our project

Step 4

On your nuxt.config.js add


  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    '@nuxtjs/firebase',    
  ],
  // firebase FCM starts here

  firebase: {
    lazy: false,
    config: {
      apiKey: <apiKey>,
      authDomain: <authDomain>,
      projected: <projectId>,
      storageBucket: <storageBucket>,
      messagingSenderId: <messagingSenderId>,
      appId: <appId>,
      measurementId: <measurementId>,
      databaseURL: <databaseURL>,
    },
    onFirebaseHosting: false,
    services: {
      messaging: true,
    }
  },


  messaging: {
    createServiceWorker: true,
    actions: [
      {
        action: 'goHome',
        url: 'https://localhost:3000'
      }
    ],
    fcmPublicVapidKey: <vapidKey> 
  },

To get your vapidKey navigate to Project Settings on your firebase console and select Cloud Messaging, scroll down and press on Generate Key Pair to have your vapidKey.See image below enter image description here

copy and paste it on your nuxt.config.js

Step 5

On the static folder at your project root create a file named firebase-messaging-sw.js and paste the input the configs as below

importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing the generated config
var firebaseConfig = {
      apiKey: <apiKey>,
      authDomain: <authDomain>,
      projected: <projectId>,
      storageBucket: <storageBucket>,
      messagingSenderId: <messagingSenderId>,
      appId: <appId>,
      measurementId: <measurementId>,
      databaseURL: <databaseURL>,
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function (payload) {
  console.log('Received background message ', payload);

  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

Step 6

On your index.vue configure it as follows

<template>
  <div>
    <h1>Get Notified</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      listenersStarted: false,
      idToken: "",
    };
  },
  mounted() {
    this.startListeners();
  },
  methods: {
    // FCM NOTIFICATION FUNCTIONS
    async startListeners() {
      await this.startOnMessageListener();
      await this.startTokenRefreshListener();
      await this.requestPermission();
      await this.getIdToken();
      this.listenersStarted = true;
    },
    startOnMessageListener() {
      try {
        this.$fire.messaging.onMessage((payload) => {
          console.info("Message received : ", payload);
          console.log(payload.notification.body);
        });
      } catch (e) {
        console.error("Error : ", e);
      }
    },
    startTokenRefreshListener() {
      try {
        this.$fire.messaging.onTokenRefresh(async () => {
          try {
            await this.$fire.messaging.getToken();
          } catch (e) {
            console.error("Error : ", e);
          }
        });
      } catch (e) {
        console.error("Error : ", e);
      }
    },
    async requestPermission() {
      try {
        const permission = await Notification.requestPermission();
        console.log("GIVEN notify perms");
        console.log(permission);
      } catch (e) {
        console.error("Error : ", e);
      }
    },
    async getIdToken() {
      try {
        this.idToken = await this.$fire.messaging.getToken();
        console.log("TOKEN ID FOR this browser");
        console.log(this.idToken);
      } catch (e) {
        console.error("Error : ", e);
      }
    },
  },
};
</script>

Step 7

Run npm run dev , open your console to see if the permissions to display notifications are granted. Accept if promoted to allow notifications.

Step 8

Navigate to Cloud Messaging on firebase Engage menu and click on Send your first message. Type the content you would like your notification to have and select your app as the target user, there we have it you should see a notification on your browser like so

enter image description here

That's all fellow nuxters, Happy Nuxting

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1