Here the router guard is working fine on my vue app, but after logging in, the following error appears on console.
Uncaught (in promise) Error: Redirected when going from "/login" to "/" via a navigation guard.
Here is my code snippet.
const routes = [
{
path: "/login",
component: () => import("../views/Auth/Login"),
meta: { hideForAuth: true },
},
{
path: "/",
component: DashboardLayout,
meta: { requiresAuth: true },
children: [
{
path: "home",
name: "Home",
component: () => import("../views/Home"),
},
],
},
];
The Auth guard:
const loggedIn = localStorage.getItem("auth");
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!loggedIn) {
next({ path: "/login" });
} else {
next();
}
} else {
next();
}
if (to.matched.some((record) => record.meta.hideForAuth)) {
if (loggedIn) {
next({ path: "//" });
} else {
next();
}
} else {
next();
}
});
Can't figure out the problem. Thanks in advance !
Since next does not exit the guard, the guard will call next a minimum of 2 times per route because you have 2 separate if statements and both will run.
// path to /next like return next to exit the function, or structure your if statements so that only one will run.loggedIn inside the guard or it will only be evaluated once, when the router is createdHere's one way to do it that also covers routes having no meta:
router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem("auth");
const isAuth = to.matched.some((record) => record.meta.requiresAuth);
const isHide = to.matched.some((record) => record.meta.hideForAuth);
if (isAuth && !loggedIn) {
return next({ path: "/login" });
} else if (isHide && loggedIn) {
return next({ path: "/" });
}
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With