Nuxt don't see a authenticated user

Viewed 62

I am doing user authentication, but I ran into a problem. First, when loading, the middleware is loaded, it does not see the authorized user through $fire.auth.onAuthStateChanged. And if you go to another page (without reloading page), user is appear. How to make him see it at the first boot?

Here is my middleware

export default function ({app, route, redirect}) {
  console.log('middleware')
  app.$fire.auth.onAuthStateChanged(user => {
    if (user) {
      console.log('user+')
      if (route.path === perm.signin || route.path === perm.signup) {
        return redirect('/')
      }
    } else {
      console.log('user-')
      if (route.path !== perm.signin || route.path !== perm.signup) {
        return redirect(perm.signin)
      }
    }
  })
}

and what I received (1st pic) when first enter to app in console.log(middleware, user-). But if I go to another page I receive middleware, user+.

enter image description here

I need user + to be on the first start

1 Answers

onAuthStateChanged fires the callback you provided as argument after the middleware has run. In other words the callback's return statements are not being run when the middleware runs. You could either ensure the middleware is called after the first authentication attempt, but this would slow down the initial startup of the application. So you could expose the nuxt router to the onAuthStateChanged handler and router.push('/login') or router.push('/somewhere') from there.

Related