Mohammed Ismail
Mohammed Ismail

Reputation: 304

How can I fetch Firebase API key from Express backend and then do firebase.initializeApp()

Right now my Firebase.js file looks like this (fetching api key from .env from client)

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export const db = firebase.firestore();
db.settings({
  timestampsInSnapshots: true,
  merge: true,
});

export const auth = app.auth();
export default app;

And my index.js (server/express js) looks like this

const express = require("express");
const app = express();
require("dotenv").config();

const port = process.env.PORT;

app.get("/getapi", (req, res) => {
  res.send([
    process.env.FIREBASE_API_KEY,
    process.env.FIREBASE_AUTH_DOMAIN,
    process.env.FIREBASE_PROJECT_ID,
    process.env.FIREBASE_STORAGE_BUCKET,
    process.env.FIREBASE_MESSAGING_SENDER_ID,
    process.env.FIREBASE_APP_ID,
  ]);
});

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`);
});

I want to fetch the api key and other values from server and then initialize firebase. I have tried using the fetch method and problem is firebase is initializing even before fetch.

Fetch request: problem is "data outside" is undefined because it is running before its fetching

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";

var obj, app;

fetch("/getapi")
  .then((response) => response.json())
  .then((data) => {
    app = firebase.initializeApp({
      apiKey: data[0],
      authDomain: data[1],
      projectId: data[2],
      storageBucket: data[3],
      messagingSenderId: data[4],
      appId: data[5],
    });
    obj = data;
    console.log("Date inside: ", obj);
  });

console.log("Data outside: ", obj);

export const db = firebase.firestore();

db.settings({
  timestampsInSnapshots: true,
  merge: true,
});

export const auth = app.auth();
export default app;

Upvotes: 1

Views: 307

Answers (1)

Mohammed Ismail
Mohammed Ismail

Reputation: 304

So I tried and found out that there is no way that we can fetch first and initialize, so I had to go other way around.

Upvotes: 1

Related Questions