skip to Main Content

I am building a Flutter web app using FirebaseAuth for authentication, and I am trying to figure out how to load the correct route when the user a) is authenticated, and b) the user refreshes the web page.

When the app loads, firebase gets initialised and then fetches the user’s auth state, returning it about 2 seconds later in an authStateChanges handler.

The problem I have is that by the time the auth state is returned, my app has already determined which route should be presented to the user, namely, login (since, as far as the app is concerned, the user is not yet authenticated).

This results in the user first being navigated to login, and then later, when the auth state is updated, they can be navigated somewhere else – which is a crappy UX.

In the Firebase Auth docs under the section "Persisting Authentication State" it says "The Firebase SDKs for all platforms provide out of the box support for ensuring that your user’s authentication state is persisted across app restarts or page reloads" – and then goes on to say "On web platforms, the user’s authentication state is stored in IndexedDB."

Does that mean, on page reloads, I need to access the auth state of the user directly from the IndexedDB? Or does it mean Firebase returns the value stored there for me automatically?

If I am supposed to consume IndexedDB directly, how do I do that, and what key should I use?

2

Answers


  1. Firebase persists and restores the user’s authentication state automatically. You don’t need to do anything for that.

    To respond to authentication state changes in your app, listen to onAuthStateChanged as shown in the first code snippet in the documentation on getting the current user. This method returns a stream, so if you want to show the current user in the UI, you can use a StreamBuilder.

    Login or Signup to reply.
  2. then when firebase auth still determined if this user authenticated or not, instead of showing login page directly you can show the loading screen.

    the easy way you can use go router.

    and set :

    GoRouter(
    ....
    initialLocation: LoadingPage(),
    redirect: _goTologinPageorHomePageBasedAuthStatus()
    ..)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search