Vue Router beforeEach not being called

Viewed 5222

I'm currently having trouble finding a bug in router code, it worked before and I don't know when or how I broke it. I already checked in older versions but it seems to not have changed. The problem is that even when I'm deleting all code out of the beforeEach Hook in my router and just using a console.log() statement, nothing gets printed in the console and my auth-guard is therefore not working. I tried to change the order according to this: https://forum.vuejs.org/t/router-beforeeach-if-manually-input-adress-in-browser-it-does-not-work/12461/3 but nothing changed.

I am having the following code:

router/index.js

router.beforeEach = (to, from, next) => {
  console.log('he?')
  const currentUser = Firebase.auth().currentUser
  const isGold = store.getters['user/isGold']
  const requiresAuth = to.matched.some(route => route.meta.requiresAuth)
  const requiresGold = to.matched.some(route => route.meta.requiresGold)

  console.log(requiresGold, isGold, 'halloooooooo?')

  if (currentUser && to.name === 'Login') {
    next('/dashboard')
  }

  if (requiresGold && !isGold) {
    console.log('trigger')
  }

  if (requiresAuth && !currentUser) {
    next('/login')
  } else {
    next(false)
  }
}

main.js

Firebase.auth().onAuthStateChanged(user => {
  if (user) {
    const getToken = () => {
      return user.getIdToken(true).then(token => {
        store.dispatch('user/setToken', token)
      })
    }
    getToken().then(() => {
      store.dispatch('user/setUser')
      setInterval(getToken, 3540 * 1000)
    })
  }
  new Vue({
    el: '#app',
    store,
    router,
    template: '<App/>',
    components: { App }
  })

})

Thanks in advance for any help!

1 Answers

You do not assign to router.beforeEach. router.beforeEach is a method, and you call it with a function. (docs) This is how you should use the router navigation guard:

router.beforeEach((to, from, next) => {
  console.log('he?')
  const currentUser = Firebase.auth().currentUser
  const isGold = store.getters['user/isGold']
  const requiresAuth = to.matched.some(route => route.meta.requiresAuth)
  const requiresGold = to.matched.some(route => route.meta.requiresGold)

  console.log(requiresGold, isGold, 'halloooooooo?')

  if (currentUser && to.name === 'Login') {
    next('/dashboard')
  }

  if (requiresGold && !isGold) {
    console.log('trigger')
  }

  if (requiresAuth && !currentUser) {
    next('/login')
  } else {
    next(false)
  }
});
Related