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

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

Node.js captures the Promise and provides detailed feedback

As I embark on my journey with Node.js + Express, currently in the process of structuring my HTTP APIs, I have a controller that utilizes a specific pattern: my_controller.js 'use strict'; var AppApiFactory = function (express, appService) { ...

Looking for suggestions on AngularJS and Rails integration!

I'm currently in the process of creating a website using rails, but I want to integrate AngularJS for several reasons: Efficient sorting between 2 different types of data (such as selecting various restaurants from a list and then different food cate ...

Convert HTML to PDF and ensure that the table fits perfectly on an A4

I am currently utilizing html-pdf to convert my table data into a PDF format. The issue I am facing is that the table content exceeds the specified A4 paper size in such a way that two columns are completely missing in the generated PDF. However, when I c ...

javascript accessing all data in firebase real-time database using JavaScript the right way

Working with node.js, I am retrieving data from the firebase real-time database. However, the data is being returned in the following format: Data Retrieval Code import firebaseApp from '../config.js'; import { getDatabase, ref, onValue } from & ...

Determining the character encoding of a JavaScript source code file

For my German users, I want to display a status message with umlauts (ä/ü/ö) directly in the source file instead of requiring an extra download for messages. However, I'm having trouble defining the encoding for a JS source file. Is there a way si ...

Exploring the functionalities of the componentDidUpdate() method in React JS

In my project, I am trying to dynamically change an API parameter using a click function and render new data accordingly. The issue I encountered is that when I trigger the componentDidUpdate method with an onclick event listener, the first click works fin ...

The reason behind my unsuccessful attempt to utilize AJAX with the Google GeoChart API

Learning about JavaScript is exciting! I recently tried incorporating a Google Geochart to generate visual reports. The sample code looked like this: function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

What is the best way to display a progress bar as a percentage?

Is there a way to visually represent the progress of an upload on the screen using percentages? I want to display a bar that starts at 0% and updates with the percentage from the percentComplete variable. Once the upload is finished, I'd like to show ...

Unable to retrieve image

I want to save a Discord user's profile picture on Replit, but even though it downloads successfully, the image is not displaying. Here is the code I am using: const request = require('request') const fs = require('fs') app.get(&qu ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

The Art of Capturing Sound: Unleashing

Currently, I am attempting to capture video via html5 .getUserMedia and play it back without needing to upload it to a server. Despite following numerous tutorials, I have only been successful on Chrome by utilizing canvas to draw the webp image and then c ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Ways to show text on a donut chart when hovering with the mouse

I have been attempting to make adjustments to this sample. My goal is to display a word in the center of the donut chart upon mouseover, similar to this: Although I have included code for mouseover, it seems to not be functioning properly. Code const ev ...

Using jQuery to control mouseenter and mouseleave events to block child elements and magnify images

My objective is to create a hover effect for images within specific div elements. The images should enlarge when the user hovers their mouse over the respective div element. I plan to achieve this by adding a child element inside each div element. When the ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...