Endless cycle in Vue-Router when redirecting routes

I need advice on how to properly redirect non-authenticated users to the login page when using JWT tokens for authentication. My current approach involves using the router.beforeEach() method in my route configuration, but I'm encountering an issue with an infinite loop:

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requiresAuth)) {
    alert('needs auth!'); // just for testing
    if (localStorage.getItem('jwt') === null) {
      next('/login'); // causes the infinite loop
    } else {
      next();
    }
  } else {
    next();
  }
});

Whenever I try to access a route that requires authentication, the next('/login') call gets stuck in an infinite loop. One workaround is to check for the login route specifically:

if (to.path !== '/login') {
    next('/login');
} else {
    next();
}

However, this solution triggers the alert twice and feels inefficient. Is there a more elegant way to handle these route conditions? Any advice or suggestions would be greatly appreciated. Thank you!

Answer №1

This method doesn't seem like a hack.

if (to.path !== '/login') {
    next('/login');
}

When you change the route, it will automatically trigger the router.beforeEach function again.

To avoid unnecessary checks, you can move this code above

if (to.matched.some(r => r.meta.requiresAuth)) {

if (to.path === '/login') {
    next();
}

Another option is to redirect out of the Single Page Application using window.location, but I don't believe that is a better solution.

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

What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, ...

Empowering Vue with dynamic roles and permissions

Hey everyone, I am completely new to Vue and I'm struggling with a particular task. Let me explain it further. Imagine I have 2 types of users, an admin and a regular user. I also have a sidebar menu with options like profile, purchase, add new role, ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

What steps should be taken to create a two-column table from a given list of items?

I am trying to display a list of words in two columns, one word after another from left to right. Here is the desired table structure: <table id="wordTable"> <tr> <td>ac </td> <td>bd </td> </tr> ...

Challenges with Websocket connectivity following AKS upgrade to version 1.25/1.26

We currently have a Vue.js application running on AKS with no issues on version 1.23, although some webpack/websocket errors are showing up in the console. However, after upgrading our AKS Cluster to either version 1.25 or 1.26, even though the pods are a ...

Combine the PHP table with the Javascript table

I am facing a challenge where I have a table in PHP and another table in Javascript. My goal is to combine the elements of the PHP table with the elements of the Javascript table. I attempted to achieve this using the push method: <?php $tabPHP=[&apos ...

Incorporating mootools scripts into a gwt application

My issue involves creating an animation on a Composite that should start when data is loading. To test this, I created animations on regular divs using HTML: <div class="LoadDataWidget"> <div id="arrow" class="greenArrow"></div> < ...

Modifications performed on the Xhtml generated from xml and XSLT should be mirrored back into the original XML document

After transforming an XML file with xsl and loading it into a browser as html, I am making the html editable using the content editable attribute of html5. How can I transform their edits back to the original xml document, even if they add new nodes to e ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

Checking the validity of a JSON file extension using regular expressions

Using EXTJS, I have created a file upload component for uploading files from computer. I need to restrict the uploads to JSON files only and want to display an error for any other file types. Currently, I am able to capture the filename of the imported fil ...

Trigger an Event Handler only after ensuring the completion of the previous event handling

When attaching an event handler to a callback, it is important to consider the timing of the actions. For example: $("someSelector").on('click',callBackHandler); function callBackHandler(){ //Some code $.ajax({ //Ajax call with succe ...

The sequencing of AJAX calls on the server side may not necessarily match the order in which they were initiated on the client side

I am working on an ASP.NET MVC application that includes a JavaScript function within a view. Here is the code snippet: function OnAmountChanged(s, fieldName, keyValue, url) { console.log("Get Number: " + s.GetNumber()); console.log(" "); ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

The script in Vue.js Build.js keeps running indefinitely

'use strict' require('./check-versions')() process.env.NODE_ENV = 'production' const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('ch ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

Utilize the $(#id).html(content) method to populate the following column with desired content

Here is a snippet of my HTML code: <div class="row margin-top-3"> <div class="col-sm-7"> <h2>NFTs</h2> <div class="table-responsive"> <table class="table table-bordered&qu ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

Issues with Bootstrap Toggle Button functionality

I encountered a navbar error while working on my Django Project. After adding a few script tags, the navbar started to move down but did not return back to its original position. It worked fine before. By commenting out some script tags, it began to work a ...