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

Viewed 6561

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 !

2 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();
});

You can add a property home to false in the redirect config, in auth property at nuxt.config.js file

redirect: {
  login: '/login',
  logout: '/login',
  callback: false,
  home: false
}

and then, redirect the login to /

async login() {
  try {
    await this.$auth.loginWith('local', { data: this.form })
    this.$router.push('/')
  } catch {
   ...
  }
}
Related