101

With the following, the first time it's called it works, but then fails on subsequent calls with "FirebaseApp name [DEFAULT] already exists!"

public FirebaseDatabase conn(Context c) {
         FirebaseOptions options = new FirebaseOptions.Builder()
                .setApiKey("key")
                .setDatabaseUrl("url")
                .setApplicationId("ID")
                .build();


        /////I tried Try and Catch with no success//////
        FirebaseApp app = FirebaseApp.initializeApp(c, options);

        /// for this : FirebaseApp app = FirebaseApp.initializeApp(c, options, "some_app");
        //// will fail with "FirebaseApp name some_app already exists!"
        return FirebaseDatabase.getInstance(app);
}

All of the above is an attempt to connect to a second Firebase App.

Relm
  • 7,923
  • 18
  • 66
  • 113

20 Answers20

225

On firebase web, you check if already initialized with:

if (firebase.apps.length === 0) {
    firebase.initializeApp({});
}
Franck Jeannin
  • 6,107
  • 3
  • 21
  • 33
Daniel Laurindo
  • 2,628
  • 1
  • 14
  • 4
55

In v9, Firebase has been modularized for better tree shaking. So we can no longer import entire app and check the apps property AFAIK. The below approach can be used instead.

import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

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

Nitin
  • 7,187
  • 6
  • 31
  • 36
  • I tried this but I get this error - https://stackoverflow.com/questions/72028182/how-to-initialize-firebase-in-firebase-version-9-firebase-v9/72029160#72029160 – user3399180 Apr 28 '22 at 05:00
21

Firebase Version 9

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

const createFirebaseApp = (config = {}) => {
  try {
    return getApp();
  } catch () {
    return initializeApp(config);
  }
};

const firebaseApp = createFirebaseApp({/* your config */})
Max Ma
  • 1,060
  • 9
  • 15
17

For those wondering how to do the same as the accepted answer, in Android:

if (FirebaseApp.getApps(context).isEmpty()) {
    FirebaseApp.initializeApp(context);
}

and in an instrumented test environment, use this context:

InstrumentationRegistry.getContext()
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
7

You can try to get the Firebase app instance, in it's code firebase checks if it's initialized, if not it throws an IllegalStateException.

    try{
        FirebaseApp.getInstance();
    }
    catch (IllegalStateException e)
    {
        //Firebase not initialized automatically, do it manually
        FirebaseApp.initializeApp(this);
    }
Jorge Arimany
  • 5,814
  • 2
  • 28
  • 23
6

I think what you want to do is check the list of running apps before initializing your app. Each of the SDKs have a method for getting this array, in android it's getApps:

https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp.html

Then you can check to see if your app is already initialized.

In my case I just ended up checking the length of the array (I'm using the javascript / web sdk so I'm sure it's a little different for Android) and initializing a new app if it is 0.

KCE
  • 1,159
  • 8
  • 25
3

In firebase admin SDK for java, initialize the app if and only if there is no app.

if (FirebaseApp.getApps().isEmpty()) {
    FirebaseApp.initializeApp();
}
Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
2

I faced the similar issue. I solved the following problem by deleting the already initialized app.

    // Access your firebase app
    let app = firebase.app();
    // Delete your app.
    app.delete(app);

Solution works for web.

1

Not sure in android, but how about using a singleton method. In JS you can do this. Hope this helps someone

// 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';
rMili
  • 104
  • 7
1
import * as firebase from "firebase/app";
firebase.apps.map(e => e.name); // Give you an array of initialized apps
Jürgen Brandstetter
  • 7,066
  • 3
  • 35
  • 30
1

For those who are using dotNet FirebaseAdmin SDK

if (FirebaseApp.GetInstance("[DEFAULT]") == null)
{
    var createdApp = FirebaseApp.Create(new AppOptions()
    {
        Credential = GoogleCredential.FromFile("private-key.json")
    });
}
Zeeshan Ahmad Khalil
  • 793
  • 1
  • 12
  • 29
0

I faced the similar issue, I resolved it as following:

  1. Create a var for the application and initialize it with null
  2. Take reference of the application while initialization
  3. Check before initializing it again

//global variable
var firebaseResumeDownloadAdd = null;

//inside function check before initializing
if(firebaseResumeDownloadAdd==null){
   firebaseResumeDownloadAdd =
   firebase.initializeApp(functions.config().firebase);
}
0

in Android, depending on Daniel Laurindo's answer:

if (FirebaseApp.getApps(context).size != 0) {

} 
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
Mina Farid
  • 5,041
  • 4
  • 39
  • 46
0

A cleaner solution for ES6+ is


if (!firebase.apps.length) {
 ...
}
mr3mo
  • 135
  • 1
  • 10
0

Simple use Java 8 Stream and Optional featured.

Code below as

FirebaseApp.getApps()
.stream()
.filter(firebaseApp -> 
    firebaseApp.getName().equals("APP_NAME"))
   .findFirst()
   .orElseGet(() -> FirebaseApp.initializeApp(firebaseOptions, "APP_NAME"));
Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
0

Th Use Platform check to initialize according to environment

On firebase web, you check if already initialized with

use the below snippet while launching MYAPP()

import 'dart:io';

void main() async {

WidgetsFlutterBinding.ensureInitialized();

if (Platform.isAndroid || Platform.isIOS) {

await Firebase.initializeApp();

} else {

if (Firebase.apps.isEmpty) {

  await Firebase.initializeApp(

      // connect for web to firebase
      options:firebaseOptions

}

} runApp(const MyApp());

}

awes0m
  • 1
  • 1
0
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
RaySun
  • 139
  • 1
  • 5
0

For web, you could use:

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

const firebaseConfig = {/* YOUR CONFIG */}

function createFirebaseApp(config) {
    try {
        return getApp()
    } catch {
        return initializeApp(config)
    }
}

const firebaseApp = createFirebaseApp(firebaseConfig)
0

As of now, I Do not have access to comments or likes. But I think this point is important to make.

Many good answers here, but it is also essential to talk about the best answers and performance.

Ideally, you want to minimize code that goes into your production and also want to make sure that there are no unnecessary pieces out there. Thus, a tree-shaking solution is best.

I do following

import { initializeApp, getApps, cert } from "firebase-admin/app";

const secret = JSON.parse(process.env.FIREBASE_SECRET || "{}");

if (!getApps().length) initializeApp({ credential: cert(secret) });
Explorer
  • 45
  • 12
-1

If you are using Nativescript to build an hybrid mobile app for Android | iOS you can use this script:

import * as firebase from 'nativescript-plugin-firebase';

_initFirebase(): Promise<any> {
    if (!(firebase as any).initialized) {
      return firebase.init({}).then(
        () => {
          console.info('firebase started...');
        },
        (error) => console.error(error)
      );
    }
  }


edyrkaj
  • 169
  • 3
  • 3