Reputation: 13366
When I try to use initializeApp()
in a new Firebase cloud function (organized in a separate file, exported via index.ts), I get the error: "The default Firebase app already exists"
I have three files, index.ts, http.ts, and pubsub.ts.
index.ts:
export { function1 } from './http'
export { function2 } from './pubsub'
http.ts (already using initializeApp and has been working great):
import * as functions from 'firebase-functions'
import fetch from 'node-fetch'
import { initializeApp } from 'firebase-admin/app'
import { getFirestore } from 'firebase-admin/firestore'
const app = initializeApp()
const db = getFirestore(app)
const config = functions.config()
export const function1 = functions...
I need to use app in another file, pubsub.ts:
import * as functions from 'firebase-functions'
import { initializeApp } from 'firebase-admin/app'
import { getAuth } from 'firebase-admin/auth'
import { getFirestore } from 'firebase-admin/firestore'
const app = initializeApp()
const auth = getAuth(app)
const db = getFirestore(app)
export const function2 = functions...
I've seen suggestions such as !admin.apps.length ? admin.initializeApp() : admin.app();
but I'm using the latest version of Firebase Admin SDK and it's not imported the same way.
Additionally, I imagine once I manage to resolve the issue of initializeApp, the same will occur with db
-- as it is used in both as well.
I checked the Firebase docs and I don't see mention of using the Firebase Admin SDK when cloud functions are organized into separate files (it does discuss organizing functions like this, however).
Thanks in advance. 🙏
Upvotes: 1
Views: 537
Reputation: 252
I think the problem is that you are initialising admin app. You import:
import { initializeApp } from 'firebase-admin/app'
This is fine if you want to perform some admin SDK logic like verifyIdToken
. Basically anything from here: https://firebase.google.com/docs/auth/admin.
I think you should import it like this:
import {getApp, initializeApp} from "firebase/app";
if you want to have your client app initialised.
Then you can call getAuth
or getFirestore
from web client Firebase SDK. Anything from here: https://firebase.google.com/docs/auth/web/start
Upvotes: 0
Reputation: 1164
the getApp() and getApps() methods look like solid candidates to check whether your app is already initialised: https://firebase.google.com/docs/reference/js/app.md#getapp and perform conditional initialisation based on this.
Upvotes: 1