0
votes

I'm struggling to get Firebase Cloud Messaging sdk to work with Nuxt JS

I keep getting " An error occurred while retrieving token. FirebaseError: Messaging: A problem occured while subscribing the user to FCM: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. "

This is my code in the fcm.js which I'm running as a plugin in nuxt.config.js

import firebase from "../firebase/init";

firebase
  .messaging()
  .usePublicVapidKey(
    "BDYE2EYHdIp8qHjTKcJYPvO4PgaAH2pSruP55FOtNs5jWsgdeg7YK6OgJ0daSu21kN7aSzU19NRXRqC4bfITZYQ "
  );

firebase
  .messaging()
  .getToken()
  .then((currentToken) => {
    console.log(currentToken);
    if (currentToken) {
      sendTokenToServer(currentToken);
      updateUIForPushEnabled(currentToken);
    } else {
      // Show permission request.
      console.log(
        "No Instance ID token available. Request permission to generate one."
      );
      // Show permission UI.
      updateUIForPushPermissionRequired();
      setTokenSentToServer(false);
    }
  })
  .catch((err) => {
    console.log("An error occurred while retrieving token. ", err);
    showToken("Error retrieving Instance ID token. ", err);
    setTokenSentToServer(false);
  });

At the same time, if you are wondering if the user is authenticated. The user is definitely authenticated because I am able to access firestore data and access routes in my pages that I've guarded and I can see the UID details in my vuex store. So that side has no issue. I've also tried removing the usePublicVapidKey() line and it also doesn't work.

Thank you.

1
Make sure that the firebase messaging function is called only after the user authentication is done and your store is populated ? - s4k1b
Tried that already. Same error - limjix
does anything need to be in the firebase-messaging-sw.js for it to work? its currently empty - limjix

1 Answers

1
votes

Found the problem

firebase
  .messaging()
  .usePublicVapidKey(
    "BDYE2EYHdIp8qHjTKcJYPvO4PgaAH2pSruP55FOtNs5jWsgdeg7YK6OgJ0daSu21kN7aSzU19NRXRqC4bfITZYQ "
  );

In firebase console, theres a copy button that appears beside the key pair. When click on that and pasting....it adds a random space at the end of the key pair.