Home > OS >  Vue JS Router Guard
Vue JS Router Guard

Time:08-08

I am learning Vue JS and so far so good. I have an API which I am using for my backend and on successful login, it is giving me access and a refresh token. In Vue, I am checking localStorage for the token and if null I need to redirect to the login page. If present I need to make an API call to check if valid and redirect to log in or the intended route depending on the response. So far the code below is what I have managed to put up but is saying Detected an infinite redirection in a navigation guard when going from "/" to "/". Aborting to avoid a Stack Overflow. This will break in production if not fixed

Here is may code

router.beforeEach((to, from, next ) =>{
  console.log(to.meta)
  let tokens = JSON.parse(localStorage.getItem('chikolo_tokens'))
  if (tokens!== null && to.meta.requiresAuth) {
    next()
  }
  else{
    next({ name: 'login' })
  }
  
})

Routes

{
  path: '/',
  name: 'login',
  component: Login,
  meta: { requiresAuth: false },
},
{
  path: '/admin/home/',
  name: 'home',
  component: AdminHome,
  meta: { requiresAuth: true },
  
},
{
  path: '/admin/users/',
  name: 'adminUsers',
  component: Users,
  meta: { requiresAuth: true },
},

How do I navigate to the login page if tokens is null?

CodePudding user response:

tokens!== null && to.meta.requiresAuth is always false for / route.

A redirect should happen only for routes that require auth:

  if (to.meta.requiresAuth && !tokens) {
    next({ name: 'login' })
  } else{
    next()
  }
  • Related