Skip to content
Advertisement

firebase.auth().currentUser is null at page load

I successfully check the user’s authentication state with onAuthStateChange observer and redirect the user to the profile page. However, I already want to show some user-specific data on the profile, (e.g. description). For that, I need the currentUser object to be initialized and populated, which takes some time (I need uid from there to get some data from firestore). Thus, I’m looking for some way to wait until this process finishes successfully. I’m trying to use async/await syntax on the profile page, but the result returned is null.

For now, I’m using local storage when I want to get the data to the next page.

What could be the best way to wait for the currentUser object to be loaded using async/await syntax? I believe that the reason could be that firebase returns null as the first result and then correct uid – after some auth functionality is loaded.

Advertisement

Answer

What you’re describing is working as expected. If you want code to run only after the user’s sign-in state has been restored, it needs to be inside an auth state change listener as shown in the first code snippet in the documentation on getting the currently signed in user:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    // 👈 Your code that needs an active user goes here
  } else {
    // User is signed out
    // ...
  }
});

There is no way to use await here, as onAuthStateChanged doesn’t return a promise, but instead fires each time the user’s authentication state changes.

Advertisement