How can i access the Firebase Service Account stored in an Environment Variable

Viewed 269

I have firebase service account in my .env file . The main problem is I am unable to access those in index.js file. I have already tried similar questions in stackoverflow . But those were not helpful to me.

Here is my index.js:

const express = require("express");
const app = express();
const cors = require("cors");
const { MongoClient } = require("mongodb");
const { ObjectId } = require("mongodb");
const admin = require("firebase-admin");
require("dotenv").config();
const port = process.env.PORT || 5000;
//firebase admin initialization
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
admin.initializeApp({
credential : admin.credential.cert(serviceAccount),
}),
});

//middleware
app.use(cors());
app.use(express.json({ limit: "50mb" }));

The occurred error :

error image

.env file:

env file

1 Answers

I had also gone through the same problem. I think this isn't the correct way to retrieve the environment variables.

You can try to retrieve it like this-

//firebase admin initialization
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
admin.initializeApp({
  credential: admin.credential.cert({
    projectId: serviceAccount.project_id,
    clientEmail: serviceAccount.client_email,
    privateKey: serviceAccount.private_key.replace(/\\n/g, "\n"),
  }),
});

Hope it'll work.

Related