The perpetual cycle of redirection through middleware

Implementing straightforward middleware logic and encountering

Encountered an infinite redirection in a navigation guard when transitioning from "/" to "/login". Halting to prevent a Stack Overflow. This issue will cause problems in production if not resolved.

Acknowledged that my code is causing multiple redirects, but struggling to locate the source.

Presenting the router:

import { createWebHistory, createRouter } from 'vue-router'
import store from '@/store'

/* Guest Component */
const Login = () => import('@/components/Login.vue')
const Register = () => import('@/components/Register.vue')
/* Guest Component */

/* Layouts */
const DahboardLayout = () => import('@/components/layouts/Default.vue')
/* Layouts */

/* Authenticated Component */
const Dashboard = () => import('@/components/Dashboard.vue')
/* Authenticated Component */


const routes = [
    {
        name: "login",
        path: "/login",
        component: Login,
        meta: {
            middleware: "guest",
            title: `Login`
        }
    },
    {
        name: "register",
        path: "/register",
        component: Register,
        meta: {
            middleware: "guest",
            title: `Register`
        }
    },
    {
        path: "/",
        component: DahboardLayout,
        meta: {
            middleware: ["all"]
        },
        children: [
            {
                name: "dashboard",
                path: '/',
                component: Dashboard,
                meta: {
                    title: `Dashboard`
                }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes, // short for `routes: routes`
})

router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    if (to.meta.middleware == "all") {
        return next();
    } else if (to.meta.middleware == "guest") {
        if (store.state.auth.authenticated) {
            return next({ name: "login" })
        } else {
            return next()
        }
    } else if (to.meta.middleware == "auth") {
        if (store.state.auth.authenticated) {
            return next()
        } else {
            return next({ name: "login" })
        }
    }
})

export default router

In the Default.vue component:

<router-link :to="{name:'login'}">Login</router-link>

Answer №1

After receiving input from @DaveNewton, I made the following changes and the solution now works smoothly:

router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    if (to.meta.middleware == "all") {
        return next();
    } else if (to.meta.middleware == "guest") {
        if (!store.state.auth.authenticated) {
            return next()
        }
    } else if (to.meta.middleware == "auth") {
        if (store.state.auth.authenticated) {
            return next()
        } else {
            return next({ name: "login" })
        }
    }
})

Answer №2

Whenever a redirection is triggered in the beforeEach navigation guard, the new route will continue to be processed by the navigation guard. The problem arises when attempting to redirect to the login route, causing an infinite loop due to the following code snippet:

else if (to.meta.middleware == "guest") {
        if (store.state.auth.authenticated) {
            return next({ name: "login" })

As a result, you end up redirecting to the login route, only to be redirected to it again, creating a cycle. To break this cycle, you should include an additional condition to simply return next() when navigating to the login route in this scenario, such as:

router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  if (to.meta.middleware == 'all' || to.name === 'login') {
    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

Enhancing x-axis presentation in D3.js-generated charts

I created a bar chart using D3.js, but I have encountered an issue with one of the values on the x-axis being too long. I attempted to use CSS properties like text-overflow: ellipsis, width: 10px, and overflow: hidden to abbreviate values that exceed a cer ...

Populate an array of objects with various key-value pairs

In my @change method, I receive the following values: changeAttr(id, key, value) { const selections = []; }, id can be any number, key could be: color, size, sex, etc..., and value could be: red, 8, female, etc. Initially, the values might look like ...

The EJS is throwing an error because it cannot define the property "round" on an undefined object

I'm currently delving into the realm of Node.js, using the "Secrets of Ninja" book as my guide. I've come across an EJS program in the book that I copied verbatim to run, but I encountered an error despite not making any modifications to the code ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

The redirection did not occur as no authorization token was detected

I have two Nodejs applications, one for the front-end and the other for the back-end. The back-end app is secured with token access using express-jwt and jsonwebtoken middlewares. My issue is as follows: when I make a request from the front-end to the bac ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

"Exploring the world of JavaScript, Ajax, PHP parser errors, and the process of obtaining post data

Having an issue with the AJAX functionality in my game.php file. Despite my efforts to refresh .refre, I keep encountering a "parsererror" message. The jsonString variable is created using JSON.stringify(object). <div class="refre"></div> < ...

Directly transfer image to Cloudinary without creating a local file

I have integrated jdenticon to create user avatars upon signup in a node/express app. When working locally, I follow these steps: Create identicon using jdenticon Save the file on my local machine Upload the local file to cloudinary Here is a snippet o ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Using a loop to chain jQuery's .when().then() method and ensuring a fixed final call at the end of the

The solution that closely matches my issue can be found at One common use case for .then is chaining ajax requests: $.ajax({...}).then(function(){ return $.ajax({...}); }).then(function(){ return $.ajax({...}); }).then(function(){ retu ...

Various tasks to be executed on a shared element

Struggling with implementing actions on a grid component without using a router in Next.js. Here is the current code snippet: const handleActions = (btnPress, row) => { if (btnPress === "Add") {/* implementation */} else if (btnPr ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

Steps for signing up for an event using addEventSource in fullCalendar

Whenever I click on the dayClick event, my goal is to add an event to the date that was clicked. This is the JavaScript code I currently have: $('#calendar').fullCalendar({ header: { center: "title", // The title appears in the center ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...