franfrLor
franfrLor

Reputation: 99

Vue router 4 and beforeEach

I added this code in my router:

Router.beforeEach((to, from, next) => {
    // redirect to login page if not logged in and trying to access a restricted page
    const publicPages = ['/login']
    const authRequired = !publicPages.includes(to.path)
    const user = <Utilisateur>JSON.parse(<string>localStorage.getItem('user'))
    // console.log('user', user, authRequired, to, from, next)

    if (authRequired && !user && to.path !== '/connexion') {
      // console.log('redirect')
      next({ name: 'connexion', query: { from: to.fullPath } })
    }

    next()
  })

This warning message is displayed when the redirection is triggered, do you know how I can solve this problem?

|Vue Router warn]: The "next" callback was called more than once in one navigation guard when going from "/" to "/". It should be called exactly one time in each navigation guard. This will fail in production.

Upvotes: 1

Views: 1759

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should add else block that runs next():

Router.beforeEach((to, from, next) => {
    // redirect to login page if not logged in and trying to access a restricted page
    const publicPages = ['/login']
    const authRequired = !publicPages.includes(to.path)
    const user = <Utilisateur>JSON.parse(<string>localStorage.getItem('user'))
    // console.log('user', user, authRequired, to, from, next)

    if (authRequired && !user && to.path !== '/connexion') {
      // console.log('redirect')
      next({ name: 'connexion', query: { from: to.fullPath } })
    } else{
      next()
   }
  })

for more details please check this

Upvotes: 1

Related Questions