Why can I perform firebase operations from both server side functions and client side functions?
Answered
Sun bear posted this in #help-forum
Sun bearOP
Inside my app/ folder there is a tsx file that initializes a firebase app objects and exports it:
Within my page/index.tsx file I can use that app instance from both the client side code:
And from within server side code:
I don't understand why this works.
Can someone please explain what the lifecycle of the firebase 'app' object is and why it can be accessed this way?
For example, is the firebase app instance initialized when the server is built or when the code is run from a browser?
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app);
export {db, auth}Within my page/index.tsx file I can use that app instance from both the client side code:
export default function Home() {
useEffect(() => {
setDoc(doc(db, "collection", "124"), { name: "cool name" })
console.log("added documnet")
})
return (
...
)
}And from within server side code:
export async function getServerSideProps() {
setDoc(doc(db, "games", "124"), { name: "cool name" })
console.log("added documnet")
return {props:{}}
}I don't understand why this works.
Can someone please explain what the lifecycle of the firebase 'app' object is and why it can be accessed this way?
For example, is the firebase app instance initialized when the server is built or when the code is run from a browser?
9 Replies
the server and the browser are separated environments so the instance is initialized in both environments
@Rafael Almeida the server and the browser are separated environments so the instance is initialized in both environments
Sun bearOP
Tell me if this is correct please: When I run "npm run dev" and start the server, the code in the app/ folder that initializes firebase is run once, and then when I search "localhost:3000/" and access the server from the client side, I get some HTML and a js bundle, and that js contains another copy of that file and another instance of firebase is initialized?
if you are using firebase in a client component, then yes
Answer
if you are only using it in server components then the firebase lib won't be sent to the client
@Rafael Almeida if you are using firebase in a client component, then yes
Sun bearOP
So me importing that file and using it in a client component is what makes the lib be sent to the client
Okay, thank you very much for your help!
yeah exactly
np
Giant panda
But you shouldn't do that, ensure to you use the firebase admin SDK in server environment