I need to implement a feature where pages are blocked if there is no authentication token and users are redirected to the login page. I have 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;
});
When the page loads with address localhost/#/, it immediately tries to redirect to /login and an error occurs:
*[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*