How to check `Current User` in Vue Router?

I base on Vue, Vuex

  • Store
export default {
  state: {
    currentUser: null,
  },
  },
  mutations: {
    updateCurrentUser(state, user) {
      state.currentUser = user
    },
  },
  actions: {
    // Login
    login({ commit }, formData) {
      return new Promise((resolve, reject) => {
        Meteor.loginWithPassword(
          formData.username,
          formData.password,
          error => {
            if (error) {
              reject(error)
            } else {
              commit('updateCurrentUser', Meteor.user())
              resolve('success')
            }
          }
        )
      })
    },
    // Call this on `created of AppLayout` 
    loadCurrentUser({ commit }) {
      Tracker.autorun(() => {
        if (Meteor.user()) {
          console.log('Action: loadCurrentUser')
          commit('updateCurrentUser', Meteor.user())
        }
      })
    },
  },
}
  • Router
// import store ........

router.beforeEach((to, from, next) => {
    NProgress.start()

      // Check user
      if (store.currentUser) {
        next()
      } else {
        next({ path: '/' })
      }

But problem when I refresh page, get currentUser = null

I don’t know if this helps:



function requireAuth (to, from, next) {
  if (!Meteor.userId()) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else {
    next()
  }
}


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

        {
            path: '/login',
            name: 'login',
            meta: {
                contentTitle: 'Login'
            },
            component: Login
        },


        {
            path: '/',
            name: 'AppLayout',
            component: AppLayout,
            children: [
              { path: '/', component: Dashboard },
            ],


            beforeEnter: requireAuth
        },

    ]
});

Thats how we look if the user is logged in.

I don’t know what you are trying to achieve …

1 Like

thanks for your reply.
So it mean that we must add beforeEnter: requireAuth on every router.
What difference with attach it on global router?

I think if you do that, you can’t even access the login page. but I’m not sure.
We add it for every side.

So you can add also frontend permissions.