Isaac Hatilima
Isaac Hatilima

Reputation: 233

Vue JS Router Guard

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?

Upvotes: 1

Views: 1915

Answers (2)

Estus Flask
Estus Flask

Reputation: 223104

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()
}

Upvotes: 1

mukama
mukama

Reputation: 11

 Kindly try this 

const  routes = [
    /** admin*/
    {
        path: '/admin/home',
        name:'adminHome',
        component: homeAdminIndex,
        meta:{
            requiresAuth :true
        }
    },
    /** pages*/
    {
        path: '/',
        name:'Home',
        component: homePageIndex,
        meta:{
            requiresAuth :false
        }
    },

router.beforeEach((to,from) =>{
  if (to.meta.requiresAuth && !localStorage.getItem('token')){
      return { name: 'Login'}
  }
  if (to.meta.requiresAuth == false && localStorage.getItem('token')){
      return { name: 'adminHome'}
  }
})

Upvotes: 1

Related Questions