[Vuejs]-Configure router.beforeEach

0👍

Thomas Kleßen is totally right in his comment:

  1. You should add meta: { requiresAuth: true } only to the routes that need the user to be authenticated. It is not the case of the login page (nor the Register and Home ones I guess).
  2. In router.beforeEach() you should check if the “target” needs the user to be authenticated, i.e. the to (and not the from, which corresponds to the page you are coming from).

However you need to add an extra check: if the user is not authenticated you need to redirect her/him to the login page. For that you can use firebase.auth().currentUser, as follows. See the corresponding Firebase doc here.

const routes = [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/complete_registration',
      name: 'Complete Registration',
      component: CompleteRegistration
    },
    {
      path: '/profile',
      name: 'Profile',
      component: Profile,
      meta: { requiresAuth: true }
    },
    {
      path: '/otherProtectedPage',
      name: 'OtherProtectedPage',
      component: OtherProtectedPage,
      meta: { requiresAuth: true }
    }
]

const router = new VueRouter({routes, mode: 'history'})

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record  => record.meta.requiresAuth)
    const currentUser = firebase.auth().currentUser

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

Leave a comment