Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 528
Bob.B Avatar asked Aug 07 '19 15:08

Bob.B


3 Answers

You should just call admin.initializeApp() at the global scope of your code. Don't pass any parameters to accept the default service account, which should have permission to read and write your Cloud Firestore database.

like image 104
Doug Stevenson Avatar answered Nov 05 '22 17:11

Doug Stevenson


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
like image 28
Natalia Kolisnyk Avatar answered Nov 05 '22 18:11

Natalia Kolisnyk


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);
like image 22
Shanga Avatar answered Nov 05 '22 17:11

Shanga