Skip to content

Possible race condition when calling signInAnonymously immediately after getAuth()  #7049

Open
@shaibt

Description

[REQUIRED] Describe your environment

  • Operating System version: iOS 16.3.1
  • Browser version: Safari 16.3.1
  • Firebase SDK version: 9.15.0
  • Firebase Product: auth

[REQUIRED] Describe the problem

Steps to reproduce:

On loading, our React app immediately loads a component that does the following:

  • calls getAuth()
  • runs a hook to setup onAuthStateChanged
  • once onAuthStateChanged handler is called for 1st time we check for a valid user object
  • If no valid user object exists call signInAnonymously

What we're observing in our production env on an irregular basis is that the onAuthStateChanged is called multiple times with different a uid everytime.
More specifically, the 1st time app is opened on a "clean" browser, there is no persisted user uid for Firebase auth so the onAuthStateChanged handler fires with null user, we perform signInAnonymously, and onAuthStateChanged is fired again with valid uid.
Next time app is opened (few mins later) we can see onAuthStateChanged fired mutliple times in sequence with an alternating uid provided - one time the previous uid from the first-time open and a new uid.

Expectation is that the previous session's uid will be provided OR that a new uid be created but would not change - onAuthStateChanged should not be called with multiple diff values of uid for the same browser session.

Relevant Code:

 export default function ClientAuthProvider() {
const [user, setUser] = useState(null);
const auth = getAuth(firebaseApp);

useEffect(() => {
        const unsub = onAuthStateChanged(auth, user => {
            if (user) {
                setUser(user);
            } else {
                signInAnonymously(auth)
                   .catch(error => {               
                       setUser(null)
                   })
             }
        })
        return () => {
            unsub();
        }
    }, []);

 }

This wasn't reproducible in testing envs and happens only on occasion on production.
Could it be that calling getAuth() multiple times would create more than 1 instance of the auth service? Could it be that calling signInAnonymously too early would cause a race condition in auth service to generate two uid for same browser?
This issue looks similar in some ways to the issue described in #6827

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions