5

this is the request that I made using node


// Initialize the default app
var admin = require('firebase-admin');

var app = admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: process.env.FIREBASE_DATABASE
});

console.log(process.env.FIREBASE_DATABASE);


router.post('/', (req, res, next) => {

    app.auth().getUserByEmail("j.100233260@gmail.com")
    .then(function(userRecord) {
            // See the UserRecord reference doc for the contents of userRecord.
            console.log('Successfully fetched user data:', userRecord.toJSON());
            res.json(userRecord.toJSON())
        })
        .catch(function(error) {
                console.log('Error fetching user data:', error);
                res.json(error)

            });

        }

        );

I set the env var on my machine

enter image description here

for my firebase database I used env

enter image description here

given as

databaseURL: "https://fssssss.firebaseio.com",

from the firebase admin GUI ,

the error in Postman when I request this route

{
    "code": "app/invalid-credential",
    "message": "Failed to determine project ID: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND"
}

I followed the docs and google returned no results, no idea what to do. thanks.

  • 1
    Where are you running this code? – Frank van Puffelen Feb 18 '20 at 23:18
  • It seems like you're not configuring the Admin SDK correctly. Are you trying to initialize it through the `FIREBASE_CONFIG` environment variable? https://firebase.google.com/docs/admin/setup#initialize-sdk – Frank van Puffelen Feb 18 '20 at 23:28
  • 1
    If you're trying to initialize the Firebase Admin SDK with no arguments, you should definitely **fuly explain in your question** what you're doing to make sure it gets the correct configuration, and how you are certain that it's set up correctly. Because it seems to me, from the error message you show, that whatever you're doing isn't correct, and the Admin SDK is trying to contact google metadata servers, which are not accessible from your own server. – Doug Stevenson Feb 18 '20 at 23:32
  • I decided to use with arguments, updated it now. –  Feb 18 '20 at 23:50

5 Answers5

9

Method 1: Just pass the path of your service account key

const firebase_admin = require('firebase-admin');
const serviceAccount = require("/path/to/yourserviceaccountkey.json");
const admin = firebase_admin.initializeApp({
  credential: firebase_admin.credential.cert(serviceAccount);
});

Method 2 (more secure): The method above is considered less secure than the method below:

const firebase_admin = require('firebase-admin');
const admin = firebase_admin.initializeApp({
    credential: admin.credential.applicationDefault()
});

Then run the app like this:

GOOGLE_APPLICATION_CREDENTIALS=/path/to/yourserviceaccountkey.json node index.js

Or through a package.json script:

"start" : "GOOGLE_APPLICATION_CREDENTIALS=/path/to/yourserviceaccountkey.json node index.js"

You can also set the environmental variable likes this in a terminal session, before you run Node:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

References

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
Nouman Mukhtar
  • 329
  • 4
  • 6
  • 1
    Not the recommended approach. – sjsam Jan 04 '22 at 04:35
  • @sjsam Then what is? – 1252748 Mar 06 '22 at 19:02
  • @1252748 set the `GOOGLE_APPLICATION_CREDENTIALS` as mentioned in [this](https://stackoverflow.com/a/60291295/1620779) answer. And let Firebase Admin SDK automatically figure out which Firebase Project to use. – sjsam Mar 11 '22 at 00:06
  • @sjsam Thanks. Does setting that locally allow the `credential:admin.credential.applicationDefault(),` function to work when code is pushed to GCP, or does that only work for local development? – 1252748 Mar 11 '22 at 15:58
6

This isn't working the way you expect:

admin.credential.applicationDefault()

You can't use this on a server that you control without additional configuration. This only works by itself when running on Google services when you want to use the default service account for your project. When running on your own server, there is no default. You have to be explicit and download service account credentials to use during initialization. At the very least, you'll need to follow the instructions in the documentation:

To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.

To generate a private key file for your service account:

  • In the Firebase console, open Settings > Service Accounts.
  • Click Generate New Private Key, then confirm by clicking Generate Key.
  • Securely store the JSON file containing the key.

When authorizing via a service account, you have two choices for providing the credentials to your application. You can either set the GOOGLE_APPLICATION_CREDENTIALS environment variable, or you can explicitly pass the path to the service account key in code. The first option is more secure and is strongly recommended.

So you will need to download the service account file, set GOOGLE_APPLICATION_CREDENTIALS correctly, then your code will work. The service account credentials are not optional.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

If you followed the instructions for initializing the SDK by setting the environment variable using this command:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

You may have to double check that the name of the service account file matches the path you downloaded.

For example when I downloaded the service-account-file.json, mine was named my-firebase-project.json, but I used the export command without updating the filename.

Once that was fixed, the issue disappeared.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

You need to add projectId

admin.initializeApp({
   credential: admin.credential.applicationDefault(),
   projectId: `xxx-xxxxxx-xxx`, // this line
   databaseURL: environment.firebaseDbUrl
});

Note: You'll get the projectId from firebase project settings page. See image

enter image description here

WasiF
  • 26,101
  • 16
  • 120
  • 128
0

Reason why you are getting this error even after setting the GOOGLE_APPLICATION_CREDENTIALS environment variable correctly is because it needs to be set in every session when you run the firebaseAdmin initialize method. Hence you should set it every time using below in your package.json file:

"scripts": {
    "build": "npx tsc",
    "start": "export GOOGLE_APPLICATION_CREDENTIALS=/Users/abc/Documents/Code/my_folder/my_app_6abcd31ffa3a.json npm run build && ts-node index.ts",
    "test": "test"
  },
abhay anand
  • 323
  • 3
  • 7