0
votes

When I start the functions locally (firebase serve --only functions), it can read & write the Firestore data but when it comes to send the push notification it fails with the following error. It was working since yesterday. Today i updated my MacOS to Big Sur and then it stopped working.

Unauthorized Error 401 An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions.

Following is the function that tries to send the notification:

exports.test = functions.https.onRequest(async (req, response) => {
    var data = {};
    const token = await util.getTokenByEmail('[email protected]');
    let payload = {}, notiData = {}, notification = {}
    notification.title = notiData.title = `Test msg`;
    notification.body = `Test msg`;
    notiData.message = `Test msg`;
    payload.notification = notification;
    payload.data = notiData;
   try {
     await admin.messaging().sendToDevice(token, payload);
   } catch (e) {
      console.log(`Error: ${e}`); // Unauthorized Error 401
       data.error = e;
   }
   response.status(200).json({ data: data });
});

I followed the steps given here and also set the GOOGLE_APPLICATION_CREDENTIALS.

export GOOGLE_APPLICATION_CREDENTIALS="Volumes/demo/Firebase/key.json"

I am downloading the key.json from the Firebase -> Settings -> Service Accounts.

enter image description here

1
Please edit the question to show the code that isn't working the way you expect.Doug Stevenson

1 Answers

1
votes

It turned out that, I was setting the GOOGLE_APPLICATION_CREDENTIALS only for that terminal session. Once I set the path to $HOME/.zshrc, it started working. Thanks for your time and help.