'Firebase emulator setup: getFirestore() or getFirestore(firebaseApp)?
When researching how to connect your app to the Firebase emulators (e.g., the Firestore emulator), I found the main documentation stating that we'd do it like this (Web version 9):
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
// firebaseApps previously initialized using initializeApp()
const db = getFirestore(); // <-- Notice they don't pass-in firebaseApp here
connectFirestoreEmulator(db, 'localhost', 8080);
I've also seen the getFirestore() call done like this:
import { initializeApp } from 'firebase/app';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
const config = { /* Firebase project config here */ };
const firebaseApp = initializeApp(config);
const db = getFirestore(firebaseApp); // <-- Notice firebaseApp passed-in
connectFirestoreEmulator(db, 'localhost', 8080);
The Firestore API docs for getFirestore() states that it:
"Returns the existing Firestore instance that is associated with the provided FirebaseApp. If no instance exists, initializes a new instance with default settings."
I'm confused about whether or not to pass-in my initialized firebaseApp when calling getFirestore() based on that description. I have multiple Firebase services that I want to emulate (and have talk to each other) so I would think that I should pass-in my firebaseApp.
Which is correct? Are there "gotchas" to be aware of?
Solution 1:[1]
If you only need to use a single Firebase app you can do either one, but if you have multiple apps, you need to initialize each of them giving them their configs and getting their specific firestore.
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
const db = getFirestore();
connectFirestoreEmulator(db, 'localhost', 8080);
Only works if you have an already initialized firebase app in your context and that there is only one.
If you wish to have more than one firebase app you need initialize each of them and specify what firestore you are trying to access.
By doing
import { initializeApp } from 'firebase/app';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
const config = { /* Firebase project config here */ };
const firebaseApp = initializeApp(config);
const db = getFirestore(firebaseApp);
connectFirestoreEmulator(db, 'localhost', 8080);
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 | Alexander Vestergaard Eriksen |
