[Vuejs]-Check Auth on routes not working in Vue js

4👍

You are right. Your guard is pushing to the login route infinite times because router.beforeEach method is triggered in every route navigation including the login. To avoid this you should differ between the routes that require authentication and those that don’t. You can do this by adding
meta: {requiresAuth: true,}, on the routes you want to guard. This results in your route to look like:

{
  path: '/',
  component: Home,
  meta: {
    requiresAuth: true,
  },
}

You can then check if the route you’re heading to requires authentication by adding: if (to.matched.some((record) => record.meta.requiresAuth)) condition in yourbeforeEach method. This results in your guard looking like:

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!(auth.isAuthenticated())) {
      router.push({ path: '/pages/login', name: 'page-login', component: '@/views/pages/login/Login.vue' })
    }
  } else {
    next()
  }
})

This will let you check authentication on required routes only and you can break the infinite loop by adding

meta: {
  requiresAuth: false,
},

on your login route.

Leave a comment