Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Redirected when going from "/login" to "/" via a navigation guard." is appearing?

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 !

like image 966
Osman Rafi Avatar asked Oct 27 '25 15:10

Osman Rafi


1 Answers

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.

  • Change the // path to /
  • call next like return next to exit the function, or structure your if statements so that only one will run.
  • Set loggedIn inside the guard or it will only be evaluated once, when the router is created

Here'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();
});
like image 162
Dan Avatar answered Oct 30 '25 17:10

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!