Home  >  Q&A  >  body text

Navigation guard encountered infinite redirect error: Uncaught (promise)

I have a vue3 router that uses the following route definition

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'm trying to implement a Google Authentication login feature where only a specific account can access the /cms path if logged in. I have a boolean called loggedIn in the store that will flip to true in the component. As shown in the picture

<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'm doing a beforeEach action to check which page to route to based on where the user came from and whether the specific user is logged in (as shown in the picture).

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 be fine except when the correct user is logged in. Uncaught (Promise) Error: An infinite redirect was thrown in the navigation guard, and the page was not redirected to /cms but chose to stay on the /login page.

P粉291886842P粉291886842295 days ago353

reply all(1)I'll reply

  • P粉165823783

    P粉1658237832023-12-30 00:39:57

    It is an error to execute next({ name: "cms" }) when cms is already the 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();
      }

    reply
    0
  • Cancelreply