5

Trying to use navigation guard, but next('/auth/login') gives infinite loop:

router.beforeEach((to, from, next) => {
  auth.validate().then((valid) => {
    if (!valid) {
      next('/auth/login')
    } else {
      next()
    }
  })
})

router is define:

const router = new Router({
  routes: [
    {
      name: 'login',
      path: '/auth/login',
      component: login
    }
})
Alvin
  • 8,219
  • 25
  • 96
  • 177

2 Answers2

4

It seems to me like when your auth is not valid your router is sending you to /auth/login and on that page you get sent again. I handle this differently in my app, but with your code you can add a way to check where the page is comming from, using the from object in your route.

You need something to check if current route is /auth/login then ignore don't redirect.

example:

 if (!valid && from.path !== '/auth/login') {}

This will not redirect back to /auth/login because you are coming from that page.

samayo
  • 16,163
  • 12
  • 91
  • 106
0

I bumped into a similar issue the last time. In my case, I have pages that are public and others that need authorization. I added an isPublic: boolean property to the meta object. In your case, it would have been

(!valid && isPublic === false) ? next({ path: '/auth/login' }) : next();

I hope this helps. I am open to corrections too. Thanks

Isaac
  • 1
  • 2