A guide to setting up Firebase(FCM) Push Notifications on nuxtjs / vuejs

Despite extensive hours scouring the internet for a user-friendly method to incorporate Firebase FCM Push Notification into my nuxt project, I came up empty-handed.

Answer №1

Learn how to set up FCM Push Notifications for your NuxtJs/Vuejs project

Step 1

To begin, create your nuxt app using the command

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

Step 2

Next, install firebase by running npm install firebase and @nuxt/firebase with npm install @nuxt/firebase

Step 3

Create your Firebase project by following these steps:

https://i.sstatic.net/nBhnf.png

-Grab a cup of coffee while the project sets up ☕

  • Make sure to copy the configuration details displayed on the page for later use

https://i.sstatic.net/ujEtN.png

  • You will now be redirected to the homepage of your Firebase project as shown in the image below

https://i.sstatic.net/WnzUh.png

  • Now return to your project setup

Step 4

In your nuxt.config.js, add the following configurations


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

  firebase: {
    lazy: false,
    config: {
      apiKey: <apiKey>,
      authDomain: <authDomain>,
      projectId: <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> 
  },

Obtain your vapidKey by navigating to Project Settings on the Firebase console and selecting Cloud Messaging. Generate the Key Pair and get your vapidKey as shown in the image below https://i.sstatic.net/y3zAU.png

Copy and paste this key into your nuxt.config.js

Step 5

In the static folder at the root of your project, create a file named firebase-messaging-sw.js. Insert the provided configs as demonstrated 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>,
      projectId: <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

Configure your index.vue 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 , check your console to see if notification display permissions have been granted. Allow notifications if prompted.

Step 8

Head over to Cloud Messaging on your Firebase dashboard under the Engage menu. Click on Send your first message to compose the content of your notification and select your app as the target user. You should then receive a notification on your browser like shown in the image below

https://i.sstatic.net/Wjn82.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Enhance your arrays using a React form

As a new React developer, I have a question about updating arrays with a form. Currently, I have the following arrays defined in my state: state = { loading: true, projects: [], tokens: [] , authors: [] , ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

How can I create a customized scrollbar for a div element in an Angular 2.0 CLI project?

I am attempting to create a sleek horizontal scroll bar within one of my div elements, similar to the example shown here: https://i.stack.imgur.com/ziWhi.png My project is based on the angular2 CLI. Progress so far: I came across this package angular2-s ...

embedding js files into html with node.js

When it comes to messaging via websockets between a HTML5 client and server running on node.js, I decided to use JSON as the message format. To streamline this process, I created common javascript code that defines different message content types and trans ...

Include a dynamic key in the setState function in React

In my current state, I have different dropdown options: this.state = { dropdown1: false, dropdown2: false, dropdown3: false } I am looking to access and update these dropdowns using this.setState, where the number after 'dropdown' is dy ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Unable to establish a WebSocket connection in Django channels due to connectivity issues

As I dive into creating a socket-based application using Django-Channels, I've encountered an issue with connecting to the WebSocket. To demonstrate this problem, I set up a test project. The error message displayed in the JS Console: WebSocket con ...

The session will stay active even after the skill has finished performing a task by setting the parameter "shouldEndSession

I'm encountering an issue regarding my Alexa skill certification. Although I have passed all the requirements, I received feedback that includes the following points: Upon completing a task, the session remains open without any prompt to the user. It ...

Checking for an empty value with javascript: A step-by-step guide

Below is an HTML code snippet for checking for empty or null values in a text field: function myFormValidation() { alert("Hello"); var name = document.getElementById("name").value; alert(name); if (name == null || name == "") { document.ge ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

An asynchronous function will never conclude its execution

Exploring the native async and await features in Node 7.6.0 has left me puzzled. I can't seem to figure out why my async call is just hanging instead of resolving. NLP module: const rest = require('unirest') const Redis = require('io ...

Using jQuery to show an Ajax loader while the page is loading

Is it possible to display a loader (gif) before the HTML is loaded and during a page transition? I have seen this type of effect on many websites and am curious if it can be implemented. If so, is it achievable using jQuery, AJAX, and PHP? I know how to ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

Accessing the selected value from a dropdown list filled with data from a PHP array in HTML

My HTML and PHP code consists of a select dropdown that looks like this: <select name="category" id="_category" class="_cateogry" onchange="submitTheForm() > option value="">Please select</option> <?php foreach ($categories as $cont ...