I get an infinite loop when i try to navigata to login page

here is the router.beforeEach function, when the client is not authenticated then he navigate to login page.

router.beforeEach(async (to, from, next) => {
  if ( to.name !== 'signup' || to.name !== 'login' ) {
    if (await checkAuth()) {
     next()
    } else {
      next({name: 'login'})
    } 
  } else {
    next()
  } 
})

Solution 1:

It's because of how you write your condition.

if you're going to login page while unauthenticated the flow goes like:

  • 'login' !== 'signup' (true)
  • await checkAuth() (false)
  • execute next({ name: 'login' })

Maybe you meant:

const pagesForAuthOnly = []
const pagesForGuestsOnly = ['login', 'signup']
const authenticated = await checkAuth()

if (pagesForAuthOnly.includes(to.name)) {
  if (authenticated) {
    next()
  } else {
    next({ name: 'login' })
  }
} else if (pagesForGuestsOnly.includes(to.name)) {
  if (authenticated) {
    next({ name: 'home' })
  } else {
    next()
  }
} else {
  next()
}