Home > Back-end >  Uncaught (in promise) Error: Infinite redirect in navigation guard
Uncaught (in promise) Error: Infinite redirect in navigation guard

Time:07-18

I have a vue3 router defined with the following routes

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  {
    path: "/gallery",
    name: "gallery",
    component: () =>
      import(/* webpackChunkName: "gallery" */ "../views/GalleryView.vue"),
  },
  {
    path: "/cms",
    name: "cms",
    component: () =>
      import(/* webpackChunkName: "cms" */ "../views/CmsView.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "cms" */ "../components/Login/LoginPage.vue"),
  },
];

I am trying to implement a Google Auth Login feature where the /cms path can only be accessed if a specific account is logged in. I have a boolean in the store called loggedIn which will be flipped to true in the component. As shown

<script setup>
import { decodeCredential, googleLogout } from "vue3-google-login";
import store from "@/store/index";
import router from "@/router/index";
const callback = (response) => {
  const userData = decodeCredential(response.credential);
  if (userData.email === "my_email") {
    store.state.loggedIn = true;
    router.push({ path: "/cms" });
  } else {
    store.state.loggedIn = false;
    googleLogout();
  }
};
</script>

In the router I am doing a beforeEach to check which page to route to based on where a user is coming from and if a specific user is signed in as shown.

router.beforeEach(async (to, from, next) => {
  // If not logged in and trying to access cms
  if (!store.state.loggedIn && to.name === "cms") {
    return next({ name: "login" });
  }
  // If logged in and trying to access cms after login
  else if (store.state.loggedIn && to.name === "cms" && from.name === "login") {
    console.log("test");
    return next({ name: "cms" });
  }
  // Else just route to next page
  else {
    return next();
  }
});

Everything seems to work except when the correct user signs in. A Uncaught (in promise) Error: Infinite redirect in navigation guard is thrown and the page isn't redirected to /cms instead choosing to stay on the /login page.

CodePudding user response:

It's a mistake to do next({ name: "cms" }) when cms is already current route. It should be next(), then else if becomes redundant:

  if (!store.state.loggedIn && to.name === "cms") {
    return next({ name: "login" });
  }
  else {
    return next();
  }
  • Related