Vue-Router: Identified an ongoing redirection loop in a navigation guard while transitioning from the home page to the login page

I need to implement a feature where pages are blocked if there is no authentication token and users are redirected to the login page. I have two .ts pages (main and routes)

routes:

import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/login/',
    name: 'Login',
    component: () => import('layouts/LoginLayout.vue')
  },

  {
    path: '/',
    component: () => import('layouts/DVRLayout.vue'),
    children: [
      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },
      { path: 'settings', component: () => import('pages/AppSettings.vue')},
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];
export default routes;

main

import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';


export default route(function () {

  const Router = createRouter({ routes });
  
  Router.beforeResolve(async(to, from, next) => {
    if(!document.cookie){
      next('/login')
    } else {
      next('/')
    }

  })
  return Router;
});

When the page loads with address localhost/#/, it immediately tries to redirect to /login and an error occurs:

*[Warning] [Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/login". Aborting to avoid a Stack Overflow. This will break in production if not fixed. (vue-router.js, line 43)

Unexpected error when starting the router: Error: Infinite redirect in navigation guard (anonymous function) — vue-router.mjs:3178*

Answer №1

Router.beforeResolve is triggered before each navigation, including navigations initiated by the guard itself. If the first redirect leads to /login, a new navigation session starts and the guard is activated again. Since !document.cookie remains true, it redirects once more to /login, creating an endless loop.

The else { next('/') } statement may not be the intended behavior. This code essentially directs users to "/" regardless of their chosen destination, as long as !document.cookie is false. It is possible that you simply want to use next(), which means "proceed with the current navigation path."

You can try the following revised code snippet:

Router.beforeResolve(async (to, from, next) => {
  if (!document.cookie && to.path !== '/login') {
    next('/login');
  } else {
    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

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

How to Use JQuery to Retrieve the Nearest TD Element's Text Content

Hey there, here is some HTML code that I need help with: <tbody> <tr> <td class="text-center"><input type="text" class="form-control cardSerialNumber"></td> <td class="text-center"><button type="button" onc ...

Convert an array to a string using a JavaScript function

I am encountering an issue with the code below: Every time I pass the Array to "track," I encounter an error. It seems like there might be a mismatch between passing an object and a string as input, but I am uncertain and unable to verify. for (var i = 0; ...

Logging in using Selenium WebDriver in Java

I'm just starting out with selenium webdriver and I need to automate a webpage for my project. Right now, I'm working on the login page but I'm having trouble with the login button. I'm not sure which locator to use for it. The login bu ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Struggling with implementing jquery Ajax and a php script to fetch information from a mysql database

I'm encountering issues with my current web app project in displaying a simple jpg image based on the selected radio button using jQuery AJAX along with a PHP script to interact with MySQL. Below is my ajax.js file: $('#selection').change( ...

Defer the rendering of Vue.js pages until the data request is completed

I am currently working on a page that retrieves data from the server using axios. My goal is to wait for the axios request to complete before rendering the page content. The reason behind this approach is that I already have a prerendered version of the ...

An easy way to activate the save button automatically

Is there a way to automatically enable the save button when a user checks the checkbox and enters text in the input field? I'm not sure what steps are needed or if there is an alternative approach to achieve this. jQuery("input[type='text&apos ...

Ensuring Consistent Headings While Scrolling

Imagine having headings structured like this: <h1 class="fixontop">heading 1</h1> content goes here. . . . long paragraph. <h1 class="fixontop">heading 2</h1> 2nd content goes here. . . . long paragraph. <h1 class="fixontop"> ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

When using Node.js, the process.exit() function will not terminate if there is an open createReadStream

My program interacts with Asterisk using EAGI, where Asterisk communicates with my Node.js application by sending data via STDIN and receiving commands via STDOUT. When a user ends the call, the Node.js process receives a SIGHUP signal for clean terminatio ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

Having trouble with jQuery's scrollLeft function on elements that are not currently visible

Within a large container DIV that contains numerous other elements and has a scroll bar, an issue arises when determining the value of scrollLeft. When the DIV is visible, the scrollLeft() function returns the correct value, but when the element is hidden, ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

Trouble with Material-UI Textfield Hinttext Functionality

When designing a textfield according to job requirements, I encountered an issue. After assigning a background color to the TextField, the hintText disappeared. To resolve this, I had to manually set the z-index of the label. Now, the hintText is visible, ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Getting data from an HTML file with AJAX

I have a JavaScript application where I am trying to retrieve an HTML file in order to template it. Currently, I am using the following method: var _$e = null; $.ajax({ type: "GET", url: "/static ...