FCM - connected NodeJS, I'm getting this error "code": "app/invalid-credential"

106 Views Asked by At

I'm trying to FCM push notification through to Nodejs

No code changes in this below code but today I'm getting error but yesterday it's worked perfectly.

Error from FCM :-

    "code": "app/invalid-credential",
    "message": "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\"."
}

Code :-

import { initializeApp, applicationDefault } from "firebase-admin/app";
import { getMessaging } from "firebase-admin/messaging";

initializeApp({
  credential: applicationDefault(),
  projectId: "ecfile-test",
});

app.post("/send", function (req, res) {
  const receivedToken = req.body.fcmToken;

  const message = {
    notification: {
      title: "Notif",
      body: "This is a Test Notification",
    },
    token:
      "mytoken",
  };

  getMessaging()
    .send(message)
    .then((response) => {
      res.status(200).json({
        message: "Successfully sent message",
        token: receivedToken,
      });
      console.log("Successfully sent message:", response);
    })
    .catch((error) => {
      res.status(400);
      res.send(error);
      console.log("Error sending message:", error);
    });
});

1

There are 1 best solutions below

5
supertux On

You need to call initialiseApp passing a valid service account JSON instead of default credentials. Read about making a service account here

import * as admin from 'firebase-admin'
import * as creds from './path-to-service-account-key.json'


initializeApp({
  credential: admin.credential.cert({...creds}),
  projectId: "ecfile-test",
});

The .json should look like this, but populated

{
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": "
}