javascript – Vue Router: prevent user from accessing the login route if he is already logged in


I'm configuring the routes of my application in Vue.js , initially everything is OK, after logging in the user is redirected to the dashboard , now my question is how can I prevent the user from accessing the route " /login " (again) after he already logged in and redirect him back to the previous route? (which he was before typing in the address bar " /login ")

Reading the documentation, I know I can use navigation guards , and using the global router.beforeEach , which has three parameters: to , from and next , I know I can manipulate this behavior using from to return the user to the route above if he accesses " /login " while logged in, but I still can't get him to be redirected.

here is my code example: router/beforeEach.js

import { checkUserToken } from 'src/utils/storageData'

const isAuthRoute = route => route.path.indexOf('/login') !== -1

const isLogged = () => !checkUserToken()

const needAuth = auth => auth === true

const beforeEach = (to, from, next) => {
  const auth = to.meta.requiresAuth

  // verifica se a rota requer autenticação
  if (needAuth(auth)) {
    // verifica se o usuário já está autenticado
    if (!isAuthRoute(to) && !isLogged()) {
    } else {
      if (isLogged() && to.path === '/login') {
  } else {

export default beforeEach


import Vue from 'vue'

import VueRouter from 'vue-router'

import {routes} from './routes'

import beforeEach from './beforeEach'


const router = Vue.router = new VueRouter({
  linkActiveClass: 'active',
  saveScrollPosition: true,
  mode: 'history',
  base: __dirname,

// pega as configurações do import acima

export default router


In the '/login' route you can define beforeCreate by calling a goback() method, see

beforeCreate () {
    if (isLogged()) {
methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
Scroll to Top