TheRedTopHat
TheRedTopHat

Reputation: 57

Avoiding Firebase duplicate results in Cannot read property 'apps'

I am trying to use Firebase in a TypeScript/NextJS project but I've been unsuccessful in getting it to work. I am able to import it and initialize an app:

import * as firebase from "firebase/app";
import { collection, getDocs } from "firebase/firestore";

const firebaseConfig= ({
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
});

firebase.initializeApp(firebaseConfig);

However, when I reload the page I get this error:

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

To mitigate this I replaced,

firebase.initializeApp(firebaseConfig);

with

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
 } else {
    firebase.app();
 }

but now I get the error TypeError: Cannot read property 'length' of undefined.

Intellisense on apps says Property 'apps' does not exist on type, but I don't know what to do with this information. Any help is appreciated.

Upvotes: 0

Views: 526

Answers (2)

jnpdx
jnpdx

Reputation: 52397

In version 9, you should be able to use getApps for the test instead:

import { getApps, initializeApp } from "firebase/app"

if (!getApps().length) initializeApp(firebaseConfig)

https://firebase.google.com/docs/reference/js/v9/app.md#getapps

Upvotes: 5

Frank van Puffelen
Frank van Puffelen

Reputation: 599061

The syntax you're using is for 8.x and earlier versions of the Firebase SDKs, so I recommend using those. Version 9 introduces a completely different, modular syntax - as shown in @jnpdx's answer.

Upvotes: 1

Related Questions