Search code examples
javascriptvue.jshttp-redirectvue-router

Vue-Router: Detected an infinite redirection in a navigation guard when going from "/" to "/login"


I want to block pages if there is no authentication token and redirect to login page. I've got two .ts pages (main and routes)

routes:

import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/login/',
    name: 'Login',
    component: () => import('layouts/LoginLayout.vue')
  },

  {
    path: '/',
    component: () => import('layouts/DVRLayout.vue'),
    children: [
      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },
      { path: 'settings', component: () => import('pages/AppSettings.vue')},
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];
export default routes;

main

import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';


export default route(function () {

  const Router = createRouter({ routes });
  
  Router.beforeResolve(async(to, from, next) => {
    if(!document.cookie){
      next('/login')
    } else {
      next('/')
    }

  })
  return Router;
});

On load page address is localhost/#/, then it immediately try to redirect to /login and error appears:

*[Warning] [Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/login". Aborting to avoid a Stack Overflow. This will break in production if not fixed. (vue-router.js, line 43)

Unexpected error when starting the router: Error: Infinite redirect in navigation guard (anonymous function) — vue-router.mjs:3178*


Solution

  • Router.beforeResolve runs before every navigation, even navigations initiated by the guard itself. The first redirect to /login starts a new navigation so the guard activates again and !document.cookie is still true so it redirects again to /login and this repeats forever.

    The else { next('/') } is also probably not what you want. It means no matter where the user tries to navigate, as long as !document.cookie is false, always direct them to "/". I think you just mean to call next() which means "continue with the current navigation, wherever that may be"

    Try

    Router.beforeResolve(async (to, from, next) => {
      if (!document.cookie && to.path !== '/login') {
        next('/login');
      } else {
        next();
      }
    });