I am playing around with Firebase and Svelte at the moment and wondering about the best way to set up a Firebase app object that I can use from several components. For example, I have two different components/pages (client side routing) that both need to get some data from Firestore. Currently, I am initializing the app object in both pages and they are doing their own thing after that, something like this:
// PageB.svelte
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase app
const app = initializeApp(firebaseConfig);
// Initialize Firestore
const db = getFirestore(app);
// Do something with the db object..
// PageA.svelte
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase app again
const app = initializeApp(firebaseConfig);
// Initialize Firestore again
const db = getFirestore(app);
// Do something with the db object..
I am initializing and creating two objects exactly the same in the components and this feels wrong and I would at least break out the config to a global config of some kind but I am not sure what to do with the Firebase objects.
Should I create a wrapper around the initialization and then import that into my pages or what would be the recommended solution? Something like this?:
// firebase.ts
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
export const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
// PageA.svelte
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase app again
const app = initializeApp(firebaseConfig);
// Initialize Firestore again
const db = getFirestore(app);
// Do something with the db object..
Is there a problem with initializing a firebase app several times or is it a problem to share the same instance? I am leaning towards the multi use instance at the moment since that would allow me to easily attach emulators in the dev environment as well but I am not sure what is the best approach.