vuejs - Redirect from login/register to home if already loggedin, Redirect from other pages to login if not loggedin in vue-router

Here's what I'm doing. First I'm using a meta data for the routes, so I don't need to manually put all routes that are not requiring login:

routes: [
  {
    name: 'About' // + path, component, etc
  },
  {
    name: 'Dashboard', // + path, component, etc
    meta: {
      requiresAuth: true
    }
  }
]

Then, I have a global guard like this:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!store.getters.isLoggedIn) {
      next({ name: 'Login' })
    } else {
      next() // go to wherever I'm going
    }
  } else {
    next() // does not require auth, make sure to always call next()!
  }
})

Here I am storing if the user is logged in or not, and not making a new request.

In your example, you have forgotten to include Login into the list of pages that "don't need authentication". So if the user is trying to go to let's say Dashboard, you make the request, turns out he's not logged in. Then he goes to Login, BUT your code checks, sees it's not part of the 3 "auth not required" list, and makes another call :)

Therefore skipping this "list" is crucial! ;)

Good luck!


If someone is still looking for an answer, you can reverse the logic. So, the same way you have requiresAuth, you will have hidden routes for authenticated users. (example with firebase)

    routes: [{
            path: '/',
            redirect: '/login',
            meta: {
                hideForAuth: true
            }
        },
         {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true
            }
        }]

And in your beforeEeach

router.beforeEach((to, from, next) => {
    firebase.auth().onAuthStateChanged(function(user) {
        if (to.matched.some(record => record.meta.requiresAuth)) {
            if (!user) {
                next({ path: '/login' });
            } else {
                next();
            }

        } else {
            next();
        }

        if (to.matched.some(record => record.meta.hideForAuth)) {
            if (user) {
                next({ path: '/dashboard' });
            } else {
                next();
            }
        } else {
            next();
        }
    });
});