Jan Berndt
Jan Berndt

Reputation: 1055

How to load a firebase admin key in node js?

I want to use the firebase admin SDK to give my node server free access to my database. This is the code of index.js in my functions folder:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Initialize app
admin.initializeApp({
  credential: admin.credential.cert("logininfo.json"),
  databaseURL: "https://thenameofmydatabase.firebaseio.com/",
  databaseAuthVariableOverride: {
    uid: "nameserver"
  }
});

In the same folder, I have my logininfo.json, which looks something like this (censored the keys for obvious reasons):

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}

However, I get the error Failed to parse certificate key file: Error: ENOENT: no such file or directory when trying to deploy to firebase hosting.

How do I fix this and is there a more secure / elegant way to handle this? Can I just change the GOOGLE_APPLICATION_CREDENTIALS variable somewhere in firebase hosting?

Upvotes: 5

Views: 5133

Answers (1)

Ankit Manchanda
Ankit Manchanda

Reputation: 582

It can be done by 2 different ways:

By Path:

    const functions = require("firebase-functions");
    const admin = require("firebase-admin");
    const serviceAccount = require("path/to/logininfo.json");

    // Initialize app
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://thenameofmydatabase.firebaseio.com/",
      databaseAuthVariableOverride: {
        uid: "nameserver"
      }
    });

By Object:

const functions = require("firebase-functions");
        const admin = require("firebase-admin");

        // Initialize app
        admin.initializeApp({
          credential: admin.credential.cert({
               "type": "service_account",
               "project_id": "...",
               "private_key_id": "...",
               "private_key": "...",
               "client_email": "...",
               "client_id": "...",
               "auth_uri": "https://accounts.google.com/o/oauth2/auth",
               "token_uri": "https://oauth2.googleapis.com/token",
               "auth_provider_x509_cert_url": 
               "https://www.googleapis.com/oauth2/v1/certs",
               "client_x509_cert_url": "..."
        }),
          databaseURL: "https://thenameofmydatabase.firebaseio.com/",
          databaseAuthVariableOverride: {
            uid: "nameserver"
          }
        });

Upvotes: 5

Related Questions