[Vuejs]-Vue router is safe?

-1👍

Nothing is stopping that final next() from running which makes your entire navigation guard redundant.

Either wrap it in an else block, eg

if(to.matched.some(record => record.meta.requiresAuth)) {
  // your code
} else {
  next()
}

or change your code to exit (via return) at the appropriate spots

router.beforeEach(async (to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    let user = JSON.parse(localStorage.getItem('user'))

    if (user && user.token){
      await user_service.isLogged(to.path).then(response => {
       //wait for a response from the server if the token is valid
        switch (response.status){
          case 200:
            return next()
          case 403:
            return next({path: '/403'})
          case 401:
          default:
            return next({path: '/login'})
        }
      })
    } else {
      return next({path: '/login'})
    }
  }
  next()
})

Leave a comment