Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase onAuthStateChanged giving null on opening a link on new tab

I am using firebase for authentication in react app. Whenever I open a link in my app on new tab auth.onAuthStateChanged gives a null rather than giving the signed in user. I don't face this issue whenever I reload my page. But this happens whenever I open a nav link on new tab. I had gone through all the similar articles from stack overflow and other resources and changed my code accordingly the problem still remains the same. currently my code looks like this

const firebaseApp = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export const auth = firebaseApp.auth();



useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        setCurrentUser(user);
        setLoading(false);
      } else {
        setCurrentUser(null);
        setLoading(false);
      }
    });
  }, []);

If you have faced similar issue. Please help!

like image 415
Gokul Rajan Avatar asked Oct 25 '25 12:10

Gokul Rajan


1 Answers

I am dealing with a similar situation today.

I am using the newer Firebase Auth API so the issue might differ from yours.
For me, the issue is caused by calling setPersistence on javascript loading.

I basically call getAuth then setPersistence; this lead to reinitialize local storage persistence on document load.

When I open a new tab, the current tab's onAuthStateChanged gets triggered by setPersistence called in the new tab.
IMO, this should be classified as a bug.

Anyway, the modern (current SDK when I post this answer) workaround is to assign persistence mode from the beginning. That is using initializeAuth instead of getAuth and supply persistence mode there.

For me, it is:

const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
  persistence: [
    browserLocalPersistence,
    indexedDBLocalPersistence,
  ],
  popupRedirectResolver: browserPopupRedirectResolver,
});
// `setPersistence` was removed
like image 87
Curious Sam Avatar answered Oct 28 '25 03:10

Curious Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!