Solving The Issue: Firebase App named '[DEFAULT]' already exists

Recently whilst I was attempting to port over a TypeScript/Webpack based Aurelia application to work with Aurelia’s newly released server-side rendering functionality, I encountered an annoying error with Firebase Firebase App named '[DEFAULT]' already exists.

Previously, my code looked like this:

import * as firebase from 'firebase';

const config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

export default firebase.initializeApp(config);

Because of the way server-side rendering works, it meant that Firebase was being spun up multiple times in my app. This previously wasn’t a problem because of one codebase. To fix it, you just need to alter your default export a little bit.

Firebase has a little unknown array of apps, which allows us to check its length. If there are no apps, the length will be zero so we initialise our app, otherwise, we export our Firebase app instance.

import * as firebase from 'firebase';

const config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

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

Save the above in a file called firebase.js or firebase.ts and then import it into parts of your app where you need Firebase.