Home > OS >  How to use firebase auth object in react?
How to use firebase auth object in react?

Time:09-19

I am having some issues understanding what exactly happens codewise when we write:

const auth = getAuth();

I am using React, the newest version. Do I have to initialize this in every file where I need to use it? Can this auth be passed as a parameter to an async function? Would that be considered a good practice?

I guess I am striving for a deeper understanding of how to use auth. If a user fails to sing in and provides incorrect details does the auth used in all files now mean that there is no current user if there was one previously? Thank you in advance for any help.

CodePudding user response:

The getAuth() returns the Auth instance of the default Firebase Application.

Do I have to initialize this in every file where I need to use it?

I usually recommend initializing any Firebase services in a single file (firebase.js/ts) and then import the instances from it. This ensures that Firebase SDK has been initialized. For example:

// firebase.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = { ... };

// Firebase Default App initialized before using any service
const app = initializeApp(firebaseConfig); 

export const auth = getAuth();
export const db = getFirestore();

You can import these wherever required:

import { auth, db } from "../path/to/firebase.js"

If you use getAuth() in every file there might be a case that initializeApp() has not been called yet and then calling any service like getAuth() might throw an error like this unless you ensure it is called before rest of your code runs e.g. using boot files when frameworks like Quasar:

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).


The getAuth() has no parameters in the code above because we only have one Firebase project/instance here. In case you are using multiple Firebase projects, then you would have to pass an Firebase app instance in the function to specify the project. It's might be easier when you need to do this in a single file. Checkout Are you supposed to pass the firebase app to getAuth() or leave the arguments as blank? for more information.

If a user fails to sing in and provides incorrect details does the auth used in all files now mean that there is no current user if there was one previously?

The getAuth() returns same instance every time (default in case of no params) and the state will be same in all pages/components. If a user is logged in with Account1, it'll be same across your web app.

  • Related