Navigation guard error: Caught in an infinite redirect loop

I have set up a new vue3 router and configured different 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 working on implementing a feature for Google Auth Login, where access to the /cms route is restricted to a specific logged-in account. I am using a boolean value called loggedIn in the store which will be set to true when the correct user logs in, like this:

<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 configuration, I have added a beforeEach guard to handle routing based on the user's authorization status and previous page navigation:

router.beforeEach(async (to, from, next) => {
  // Redirect to login page if user tries to access cms without logging in
  if (!store.state.loggedIn && to.name === "cms") {
    return next({ name: "login" });
  }
  // Redirect to cms page if user is already logged in and tries to go back to /cms
  else if (store.state.loggedIn && to.name === "cms" && from.name === "login") {
    console.log("test");
    return next({ name: "cms" });
  }
  // Otherwise proceed to next page
  else {
    return next();
  }
});

However, after successful login by the authorized user, an error occurs with message "Uncaught (in promise) Error: Infinite redirect in navigation guard" and the page remains on the /login route instead of redirecting to /cms.

Answer №1

When the current route is already `cms`, an error occurs when you execute `next({ name: "cms" })`. Instead, simply use `next()`, eliminating the need for the `else if` statement:


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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery divs seem to "gaze up" towards the mouse pointer

I am attempting to recreate a fascinating effect using jQuery - where "cards" move in response to the mouse cursor as if they are looking up at it. I have come across a script that almost achieves what I need, but I require the ability to control the mov ...

Encountering an issue when trying to submit the form - "Cannot POST /public/register-controller

I am currently working on developing a login/signup system using Express.js, MySQL, and Node.js. However, I encountered an error when I clicked on the submit button: Cannot POST /public/register-controller This is my index.html: <!DOCTYPE html> ...

Guide to attempting an asynchronous function again in JavaScript with a time delay

I've been facing a challenge while trying to retrieve a record from a database. The issue of race conditions often leads to situations where the record might not be available when attempting the initial fetch. How can I implement retry logic to overco ...

JavaScript - Uncaught TypeError: type[totypeIndex] is not defined

After following a tutorial and successfully completing the project, I encountered a JavaScript error saying "Uncaught TypeError: totype[totypeIndex] is undefined". When I tried to log the type of totype[totypeIndex], it initially showed as String, but late ...

Is the JSON data not matching the file's content during validation?

After thorough testing, my JSON data appears to be functioning correctly with regular content. Here is a sample of the working JSON: Working Json { "language": "XYZ", "content": { "GEN": "this is test& ...

Using React, we can create a component by defining it as a constant and then

Currently, I have a React component that is created as a const and takes props. In another file, there is a function called selectChanged() {} which returns undefined every time the select value is changed. The code for the component is as follows: ... ...

Is there a way for me to move a user from one room to another room?

My friend and I both have our own rooms in a session. When I want to send him a message, I need to switch his room to the same one where I am. This is the code snippet for creating my own room with static sessions: socket.on('chat-in', function ...

Extracting Ajax responses and storing them as variables in JavaScript

Currently, I am developing a small PHP script and using the following code for an ajax query: var CODE = $('.code').val(); var CASE = $('.code').attr('case'); $.ajax({ type:'POST', ...

Safari on iOS 9 having trouble playing embedded YouTube videos

Recently, I discovered that my YouTube embedded videos are not playing on iOS devices when on my website unless you click in the top left corner of the video. Even after removing all extra YouTube parameters and using standard iFrame embed code, the issue ...

Encountering difficulties with integrating map controls into the Nuxt3/Vue3 mapbox feature for zooming

Recently, I started exploring Mapbox within my new Nuxt3 application. I managed to successfully render the map in my custom Map.vue component. However, I am facing trouble when trying to add controls and other options. Despite my efforts, I can't see ...

Discovering the Vue.js API key within a Laravel application

Hey there, I'm facing an issue while trying to access my YouTube API key that is stored in the .env file from within this code snippet: <template> <div class="YoutubeDash__wrapper"> <video-group :videos="videos"></video- ...

Avoid triggering the pointerenter event when touching and subsequently moving into an element

I am currently working on a React application where I want to enable a user to touch one element and then move to an adjacent element while keeping the touch continuous. The issue I am facing is that the pointerover and pointerenter events only trigger whe ...

Guide: Exchanging choices using jQuery and Address plugin

I am trying to find a way to exchange the values of two options with each other. I created a simple fiddle that successfully swaps input values, but when I tried it with select options, it didn't work as expected. The approach I'm using is based ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

There seems to be an issue preventing the Chrome browser from launching with the error message: "ERROR: connect ECONNREFUSED 127.0

My setup includes: Operating System: Windows 10 (64 bit) Browser: Chrome version 58 Node.js: 6.10.1 Npm: 3.10.10 Chromedriver: 2.29.0 After running my tests with Chrome using Selenium standalone, I encountered an error in the console where Selenium was ...

How to disable the underline styling for autocomplete in a React Material UI component

Seeking assistance with removing underline styling and changing text color upon focus within the autocomplete component of React Material UI. Struggling to locate the specific style needing modification. Appreciate any help in advance! ...