Search code examples
javascriptfirebasegoogle-cloud-functions

How to resolve “The default Firebase app does not exist” error when calling Cloud Functions v2 from a client app?


I’m encountering an issue when calling Firebase Cloud Functions v2 from my client app. Specifically, I’m getting the following error:

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

I have already initialized Firebase in my client app, and I’m able to use other Firebase services (e.g., Firestore, Authentication) without any issues. Here’s the code I’m using to initialize Firebase and call a Cloud Function:

import { initializeApp } from 'firebase/app';
import { getFunctions, httpsCallable } from 'firebase/functions';

const firebaseApp = initializeApp(firebaseConfig);

const functions = getFunctions(firebaseApp, 'europe-west3');

const myFunction = httpsCallable(functions, 'myFunction');
try {
  const result = await myFunction({ someData: 'example' });
  console.log(result.data);
} catch (error) {
  console.error("Error calling function:", error);
}

Installed package: firebase": "^10.13.2"

I tried following the documentation (https://firebase.google.com/docs/functions/callable?gen=2nd#web_7) but I still get the error. Any advice is welcome.


Solution

  • For anyone encountering a similar issue: the problem was within the Cloud Function, specifically with getFirestore(). The function was supposed to read a document from a Firestore collection, but I forgot to invoke initializeApp() from firebase-admin/app.

    Here’s an example of how Cloud Functions can access Firestore:

    import { getApps, initializeApp } from 'firebase-admin/app';
    import { getFirestore } from 'firebase-admin/firestore';
    
    if (!getApps().length) initializeApp(); // <-- this was missing
    
    const docRef = await getFirestore().collection('example').doc(documentId);
    const doc = await docRef.get();
    

    By adding initializeApp(), the function was able to access Firestore properly.