'Knowing when the javascript SDK has made a definite decision as to whether the user is logged in or not upon initial load

I'm trying to accomplish something rather simple here but it's turning out to be a bit of a head-scratcher.

Obviously we have the handy onAuthStateChanged event which allows me to listen to changes to auth status. So it's easy to be informed when the user logs in or out.

The issue is that during the initial application load, there doesn't seem to be a reliable way to tell if the user is simply not logged at all or if the sign-in is being processed in the background.

For example, if the user has a stored session (logged in from last time), and returns, initially onAuthStateChanged will return null, and then afterward it's triggered again and returns the user.

If the user is not logged in, it will return null and then do nothing.

The problem is I can't really tell if the first null is telling me that the user is not logged in at all versus the user is not logged in yet because it's being processed in the background.

I would like a way where I could know for sure either way.

Thanks!



Solution 1:[1]

if the user has a stored session (logged in from last time), and returns, initially onAuthStateChanged will return null, and then afterward it's triggered again and returns the user.

Even though I also thought that's how onAuthStateChanged worked for a long time, that is actually not how it works.

The SDK will only call onAuthStateChanged listeners once it has determined the initial authentication state. So if there are locally persisted credentials, it won't call onAuthStateChanged listeners until it has restored those credentials, or until it failed to do so.

While the SDK is trying to restore the persisted credentials, currentUser will be null though, which is one of the reasons why reacting to an auth state listener is better than reading currentUser everywhere.

If you're seeing a different behavior, please edit your question to show the minimal steps with which we can reproduce the behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen