Test if Firebase is Initialized on Node.JS / Lambda

by Max Rohde,

Firebase is build on the assumption that it will only be initialized once.

This can be a problem in Node.JS applications sometimes, especially if they are run as part of an Amazon Lambda function.

This can lead to errors as the following:

Firebase App named '[DEFAULT]' already exists.

Thankfully, there is an easy way to check if Firebase has already been initialized (firebase.initializeApp). Just wrap your call to initializeApp in the following:

if (firebase.apps.length === 0) {
    firebase.initializeApp({
        serviceAccount: {
            ...
        },
        databaseURL: ...
    });
}

Sources

Categories: javascript