[Vuejs]-Nuxt newbie – Firebase auth not working on refresh

0👍

TBH I don’t know Vue, Nuxt, or Firebase, but my first guess was that at the point where you ask Firebase to return the currentUser, it is not yet fully initialized or something of the sort. Firebase docs seem to agree:

Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user’s sign-in status, you don’t need to handle this case.

Have you tried using the authentication state observer? It looks like this:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

I would recommend setting this up as early in the code as possible, to make sure that you never miss the authentication status change. You could start with something like this:

setUserLoggedin({ commit }, user) {
  const userPromise = new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        console.log('got user', user);
        resolve(true);
      } else {
        // No user is signed in.
        resolve(false);
      }
    });
  });

  commit('LOGIN_STATUS', true);

  console.log(`Re-affirming login user object is ${JSON.stringify(user)}`);
  commit('LOGIN_USER', {
    loginInstanceId: 'a-key-to-track-each-login-session',
    useruniqueid: user.thisUserid,
    emailaddress: user.email,
    uid: user.thisUserid,
  });

  return userPromise;
}

I am quite sure this would not be good enough as a final solution but it might help you get on the right track if my guess was right.

0👍

I had same problem that received unauthenticated error after refresh or reload, problem was from propertyName of user endpoint , If you return user directly , not with object 'user':{...}, you should put propertyName : false in auth options of nuxt config, you can check what result auth will receive by execute this code directly

let user = await this.$auth.requestWith(    
    'local',    //strategy name
    null,       //endpoint
    { url: '/api/user', method: 'get', propertyName: false } // options.endpoints.user
);

Leave a comment