Error fetching access token when sending a firebase cloud message from a cloud function

82 views Asked by At

I am trying to send a message to an iOS device using cloud functions with the code below, but it generates the following error when I deploy it in the terminal using

firebase deploy --only functions

Error sending message: FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".

import * as admin from "firebase-admin";
import * as serviceAccount from "../../credentials/my-app-credentials.json";

admin.initializeApp({
  // credential: admin.credential.cert(serviceAccount),
  credential: admin.credential.cert(serviceAccount as admin.ServiceAccount),
});


const message: admin.messaging.Message = {
  notification: {
    title: "Test notification",
    body: "Sent from firebase cloud functions",
  },
  token: "<REDACTED>", 
};

admin.messaging().send(message)
  .then((response) => {
    console.log("Successfully sent message:", response);
  })
  .catch((error) => {
    console.error("Error sending message:", error);
  });

Other notes:

  • I am on the blaze plan
  • When using the Compose notification page in firebase with a test message it works and it get's delivered to the iOS device.
  • I have set up a service account with a key
  • Other functions that access my firebase database work
  • I tried a few variations to do admin.initializeApp, but none of them worked
  • I am new to working with cloud functions
2

There are 2 answers

4
Frank van Puffelen On BEST ANSWER

Ensure that the my-app-credentials.json is in the same directory as your Cloud Functions source file(s), or under that directory. If it isn't, it won't be deployed and thus won't be present when the function is run on Google Cloud Platform.

4
Renaud Tarnec On

Since this is Cloud Function code you don't need to pass any argument to the admin.initializeApp() method.

By doing admin.initializeApp() you actually initialize the Admin SDK with Google Application Default Credentials, as explained in the documentation.

This approach is also explained in the "Get started" page of the Cloud Functions documentation.