[Vuejs]-Vue 2 router in beforeEach localStorage is not defined

2👍

You are either using Nuxt, or just the Vue SSR package. So you have to make sure, the code gets executed only on client:

router.beforeEach((to, from, next) => {
  if (!process.client) {
    next()
    return
  }
    
  const accessNeed = ['Dashboard']

  if (window && window.localStorage.getItem("token")){
    if (!accessNeed.includes(to.name)) {
      next({ name: 'Home' })
    } else{
      next()
    }
  }

  next()
})

Leave a comment