'The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. at FirebaseAppError

I am learning to use Firebase Cloud Function and I am following Firebase's official tutorial video for Learn JavaScript Promises (Pt.1)

When I run a local server and go to the HTTP link I get

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

I tried finding the solution but couldn't find anywhere. I got some vaguely related question but for javascript and my code is in typescript. I did add the suggested syntax in both .js and .ts file

admin.initializeApp(functions.config().firebase);

But still, I get the same error

Here is my index.tcs.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// Start writing Firebase Functions
// https://firebase.google.com/docs/functions/typescript

export const getVoucher = functions.https.onRequest((request, response) => {
    const promise = admin.firestore().doc('/voucher/Eg2AtnGmKmX8Y0vBZiBG').get()
    const p2 = promise.then(snapshot=>{
        const data = snapshot.data()
        response.send(data)
    })
    p2.catch(error => {
        //Handlle the error
        console.log('error: '+error)
        response.status(500).send(error)
    })
});

The function works as intended when deployed to firebase tho.



Solution 1:[1]

word of advice, sometimes this comes even if you initialized the app properly, at that point just check whether your db instance is placed inside the function not global.

#nodejs

var db = admin.database();//inside function

Solution 2:[2]

This might sound like crazy, But I had the same issue. Then I've changed my "admin.initializeApp();" place like below. Then it works.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const app = express();
//put here.
admin.initializeApp();

const db = admin.firestore();

const firebaseConfig = {
// config data
};

const firebase = require('firebase');

firebase.initializeApp(firebaseConfig);

Solution 3:[3]

you have to initialize app admin.initializeApp() before you use firestore or any other feature.

Solution 4:[4]

i am use typescript, a pattner singleton, because admin.initializeApp(); needs a only instance

import admin from 'firebase-admin';
export default class firebaseDAO {

    private static _intance: firebaseDAO;
    db: any;
    private constructor() {

        admin.initializeApp();
        this.db = admin.firestore();
    }

    public static get instance() {
        return this._intance || (this._intance = new this());
    }

    // iniciar un metodo
    start() {
    }
}

create a DAO

import firebaseDAO from '../database/firebase.dao';

constructor(){
    this.db =  firebaseDAO.instance.db;
}

async getPacientes() {
    try {
        const userQuerySnapshot = await this.db.collection('pacientes').get();
        const users: any[] = [];
        userQuerySnapshot.forEach(
            (doc: any) => {
                users.push({
                    id: doc.id,
                    data: doc.data()
                });
            }
        );
        this.response.resultado=users;
        return  this.response;
    } catch (error) {
        this.response.resultado=null;
        return  this.response;
    }
}

Solution 5:[5]

Try it:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
const firebase = require('firebase');    

// service account file custom for serve    
var serviceAccount = require("serviceAccount.json"); // for deploying you need to delete it

// admin credential for localhost or emulator
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "database_url"
});

// Firebase SDK configuration        
const config ={
    //firebase config
};

firebase.initializeApp(config);
    
const db = admin.firestore();

Solution 6:[6]

I could solve this problem by initializing the app directly after importing the firebase-admin

before

import * as algoliasearch from 'algoliasearch';
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import { setFirstActivity } from './core/activities/helpers';
import { sendFCMWhenMsaHasBeenCreated } from './core/fcm';

// here is the issue
const project = admin.initializeApp();
import FieldValue = admin.firestore.FieldValue;
import Timestamp = admin.firestore.Timestamp;

result error message

after

import * as algoliasearch from 'algoliasearch';
import * as admin from 'firebase-admin';
// here is the solution
const project = admin.initializeApp();
import * as functions from 'firebase-functions';
import { setFirstActivity } from './core/activities/helpers';
import { sendFCMWhenMsaHasBeenCreated } from './core/fcm';


import FieldValue = admin.firestore.FieldValue;
import Timestamp = admin.firestore.Timestamp;

result after deploying successful result

this worked for me

Solution 7:[7]

There is a performance argument to have the admin initializeApp within the function and not global scope.

You keep a global boolean var that you can use to decide whether your specific function needs to initialize.

Here's a great YouTube video on this topic by Firebase that's well worth a watch: https://www.youtube.com/watch?v=v3eG9xpzNXM

Example:

GLOBAL:

let isSpecificFunctionAdminInitialised = false;

WITHIN FUNCTION:

const admin = require("firebase-admin");
if (!isSpecificFunctionAdminInitialised) {
  admin.initializeApp(functions.config().firebase);
  isSpecificFunctionAdminInitialised = true;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Natalia Kolisnyk
Solution 2 Shanga
Solution 3 Theja Wijesiriwardane
Solution 4 Martin Brisiak
Solution 5 Kartik Chauhan
Solution 6 Anthony Nahas
Solution 7 HungryArthur