Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)

For my Nuxt/Vue.js app I need to export various Firestore-related elements as opposed to just firebase.firestore().

However I'm getting some Firebase App named '[DEFAULT]' already exists (app/duplicate-app) error for the default export and I don't understand why:

import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
  apiKey: '...',
  authDomain: '...',
  databaseURL: '...',
  projectId: '...',
  storageBucket: '...',
  messagingSenderId: '...'
}
const firebaseApp = firebase.initializeApp(config)
firebase.firestore().settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
const fb = firebase
export { db, fb }
export default firebaseApp

There is no duplicate that I can identify in this export default line, so what's wrong?

like image 971
drake035 Avatar asked Mar 04 '23 20:03

drake035


2 Answers

The way I handle it is I have a firedb file that I import as needed (throughout the App or just in Vuex). Because the file keeps getting referenced, the config keeps re-loading, which causes the same error.

The way I've dealt with it to add this line after the config definition

if (!firebase.apps.length) {
  firebase.initializeApp(config);
}

I've got an example in condesandbox at https://codesandbox.io/s/vuex-ws-2-60fzg

With your code it would be a little more difficult, since you're exporting the firebaseAppconst. But this may work for you (not tested)

import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
  apiKey: '...',
  authDomain: '...',
  databaseURL: '...',
  projectId: '...',
  storageBucket: '...',
  messagingSenderId: '...'
}
const firebaseApp = firebase.apps && firebase.apps.length > 0 ? firebase.apps[0] : firebase.initializeApp(config)

firebase.firestore().settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
const fb = firebase
export { db, fb }
export default firebaseApp
like image 130
Daniel Avatar answered Apr 07 '23 23:04

Daniel


You can check firebase.apps to see if its loaded. If your only loading it once, then you can just check the length. If you have multiple then you could check each apps name.

// Config file

import * as firebase from "firebase";

    const config = {...};

    export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();

    // Other file
    import firebase from '../firebase';
    ...
    console.log(firebase.name);
    console.log(firebase.database());

If you use firestore, use :

export default !firebase.apps.length
  ? firebase.initializeApp(config).firestore()
  : firebase.app().firestore();
like image 40
Chanaka Weerasinghe Avatar answered Apr 07 '23 23:04

Chanaka Weerasinghe