Home > Blockchain >  Vue Navigation Guard redirects when accessing URL directly
Vue Navigation Guard redirects when accessing URL directly

Time:04-17

I'm trying to set up Vue Navigation Guards. One of my guards redirects users from the Index component to the Dashboard component if they are authenticated with Firebase Auth.

It works fine if I navigate to the Index page via a router link from another component. However, if I go to the Index page by directly typing the URL in my browser, it does not correctly redirect the user.

How can I achieve this redirect regardless of how the user accesses the route?

const routes = [
  {
    path: '/',
    name: 'Index',
    component: () => import('../components/Index.vue'),
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../components/Dashboard.vue')
  }
]

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = firebase.auth().currentUser
  if(isAuthenticated && to.path === '/') {
    console.log(to.path);
    next('/dashboard')
  }
})

I have also tried beforeRouteEnter on the individually defined route, but this didn't work either.

CodePudding user response:

That's because your navigation guard gets called before you get user data from firebase. At this point firebase.auth().currentUser is null just as if you are not authenticated.

Check out this solution. It's very elegant and solves your problem.

  • Related