'Getting "app is not defined" error after applying "Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)." error fix

At first I was getting the "Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)." error. I saw online that wrapping firebase initialization with "if (!firebase.apps.length) {}" would fix the problem. Now I'm getting an error that says "app is not defined". How do I work around this?

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

if (!firebase.apps.length) {
    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 auth = app.auth();
export default app;



Solution 1:[1]

I solved the issue this way :

 let firebaseApp ;

  if (!firebase.apps.length) {
     firebaseApp = firebase.initializeApp(firebaseConfig);
  }
  else {
    firebaseApp = firebase.app(); // if already initialized, use that one
  }

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

The problem here is you are defining const app = ... but it gets defined only for the if scope ( it's how it works in js ). That's why initialize a variable using let and then assign values to it

Solution 2:[2]

An example with Firebase 9 / Modula — all you need to do with the example below is call initializeAppIfNecessary().

import { initializeApp, getApp } from "firebase/app";

function initializeAppIfNecessary() {
  try {
    return getApp();
  } catch (any) {
    const firebaseConfig = {
      apiKey: "...",
      authDomain: "...",
      projectId: "...",
    };
    return initializeApp(firebaseConfig);
  }
}

const app = initializeAppIfNecessary();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zorayr