Firebase onAuthStateChanged and beforeEach (Navigation Guard)



  • I am seeing an issue in my Quasar app with regards to browser refresh and firebase authentication.

    When a user logs in and then clicks on the browser refresh, then the firebase.auth().currentUser returns null (as this executes asynchronously). This means that when the beforeEach gets executed the currentUser is null and the user is prompted with the logon page. However I see that when the callback to onAuthStateChanged() is getting invoked the user is getting set correctly.

    Is there any pattern by which, in a Quasar app, the onAuthStateChanged() can be used in navigation process so that existing user session is reused?

    // router/index.js 
    ...
    firebase.auth().onAuthStateChanged(user => {
      console.log('onAuthStateChanged Invoked => ' + user);
    });
    
    router.beforeEach((to, from, next) => {
      let currentUser = firebase.auth().currentUser; 
      let requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    
      if (requiresAuth && !currentUser) {
        next('signin');
      } else {
        if (requiresAuth && currentUser.emailVerified === false) {
          next('signin');
        } else {
          next();
        }
      }
    });
    ...
    

    One pattern that is used in Vue applications is to initialize the app within the onAuthStateChanged callback. From the Quasar docs, I dont see how this can be done.



  • Came across this solution in the Vuejs forum https://forum.vuejs.org/t/vue-routes-firebase-auth-sync-problem/4470

    Solution is to wrap the firebase.auth().currentUser within a Promise and then execute the logic within the beforeEach based on the resolution of the Promise.