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

A guide on handling and presenting an array of objects using AngularJS

I am currently working on a project where I have a large array of objects that need to be filtered, processed, and then displayed to the user. The application is built using node-webkit and I am using AngularJS and jQuery for routing, DOM manipulation, and ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

Access-Control-Allow-Headers does not permit the use of request header X-CSRF-TOKEN

Currently, I am utilizing Vue and Axios to make a get request to embed.rock. axios({ method: 'get', url: 'https://api.embed.rocks/api?url=' + this.url, headers: { 'x-api-key': 'my-key' } }) Oddly enou ...

IDGenerator Vuex

One of the challenges I'm facing is creating unique identifiers for my components. I've been considering storing a global variable in Vuex, like lastGeneratedID: 0, along with a mutation to increment this value. The current solution involves co ...

Fullcalendar Bootstrap popover mysteriously disappears

I'm having issues with my Bootstrap popovers being hidden under the rows in FullCalendar. I've tried using container: 'body' and trigger: 'focus', but they don't seem to work. The function that's causing this proble ...

Constructing an interactive table from a JSON dataset using Node.js and Express

Just starting out with Node.JS here! I'm currently working on creating a page with multiple tables and information using NodeJS. However, I've hit a roadblock when trying to display the result of an SQL query in an HTML table. Right now, I'm ...

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

Combining an Editor and Dropdown Feature for a Single Attribute in Asp.Net MVC

How can I implement both an Editor and a Dropdown list for a single field? In the scenario where an agency is not already in the database, the user should be able to enter the agency name. Otherwise, the value should be selected from a dropdown list. I n ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

What causes an AJAX POST request to fail?

While working on a simple HTML page with a form, I encountered an issue with my POST request failing without any response from the server. Can someone please help me figure out what I'm doing wrong? function createRequest(url, body) { var respons ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Is there a way to decode/compile/interpret the data within nested HTML tags within my AngularJS directives?

How can I process/compile/resolve the contents of enclosed HTML in my directives. The specific directive being discussed is: angular.module('transclude', []) .directive('heading', function(){ return { restrict: 'E&apos ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

"Attempting to access $scope within the $http call results in an

Exploring my Angular code angular.module('MyApp'). controller('ProductController', function ($scope, DropDownService) { $scope.Product = {}; $scope.ProductCategoryList = null; DropDownService.GetCategory().then(function ( ...

Installing a node.js application on elastic beanstalk with express framework

I've been struggling with deploying my application to Elastic Beanstalk throughout the entire day. The project structure I have is as follows (a single page app built with React) dist/ index.html bundle.js package.json app.js I compress it into ...

Struggling to run two separate single page applications concurrently on a single server with nginx

UPDATE: I have made revisions to this post in order to provide a clearer explanation of the issue. The initial post has been replaced with this updated version. We are dealing with two single-page applications that must be accessible from the same domain ...

Trimming data from model fields in a Node.js application before saving to a PostgreSQL database

While working on my node.js project, I am utilizing the objection.js ORM. So far, everything has been running smoothly. However, I'm looking to implement a feature that will trim all the fields before saving the data in the PostGres database table. In ...

Sinon respects my intern functions during testing in ExpressJS

At the moment, I am working on incorporating sinon stubs into my express routes. However, I am facing an issue where my functions are not being replaced as expected. I would like my test to send a request to my login route and have it call a fake function ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...