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.
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With