Vue Router does not enforce redirects

I am currently facing an issue where the requireAuth() function is being called repeatedly, causing a loop. I only want to display pages when the user is logged in.

This is the code snippet I am using:

// Routes
const routes = [
    {
        path: '/',
        component: Dashboard,
        beforeEnter: (to, from, next) => {
            requireAuth(to, from, next);
        },
        children: [
            {
                path: '',
                name: 'dashboard',
                component: DashboardIndex
            }, {
                path: '*',
                name: '404',
                component: NotFound
            }
        ]
    },  {
        path: '/login',
        component: Login,
        name: 'login',
    },
];

function requireAuth (to, from, next) {
    if (!localStorage.token) {
        console.log('testing');
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    } else {
        next()
    }
}

// Routing logic
let router = new VueRouter({
    routes: routes,
    mode: 'hash'
});

The message testing is printed approximately 1000 times before triggering this error:

[vue-router] uncaught error during route navigation: warn @ app.js

app.js RangeError: Maximum call stack size exceeded

How can I ensure that the path /login is redirected to when !localStorage.token condition is met?

Answer №1

The issue I encountered was related to the next() function, which is essential for navigating to a path indicated by to.path. Using router.push or router.replace could result in endless recursive calls and trigger a call stack max error. It's better to stick with just using next() and letting the router API handle the heavy lifting.

In my case, I approached this differently by managing all the logic in the main.js file. The routes.js file simply defined the routes:

var routes = [{
  path:'/login', 
  component: Login
 },
 { 
  path:'/',
  component: dashboard
 }]

All validation checks were handled within the main.js file utilizing the vue-router API. More information on this can be found here - https://router.vuejs.org/en/api/route-object.html

This setup allowed me to centralize control in the main.js, leaving route.js purely for defining routes.

Answer №2

If a user does not have a token stored in their localStorage, they will be redirected to the "/login" page.

Since this is a Vue route, the requireAuth logic will continuously run for every route. This creates an infinite loop where the user will keep getting redirected to the "/login" page, even if they are already on that page.

To prevent this from happening, simply avoid redirecting to "/login" when the user is already on the "/login" page.

I'll leave it up to you to implement this solution, but it shouldn't be too difficult once you understand what's happening.

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

Retrieve items from the parent row of selected checkboxes

Within my table, I have the following row. <tr class="data_rows" ng-repeat='d in t2'> <td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td> &l ...

The VueJS event remains unattended and unheard

I'm having trouble figuring out why my event is not being listened to properly. In the code below, I've created a component with an emit event triggered by the @click button event. Then I set up my 'v-on:my-event' to capture it. However ...

After the update, Material UI is causing a TypeError by throwing an error stating that it cannot read the property 'muiName' of an

After updating from "material-ui": "^1.0.0-beta.38" to "@material-ui/core": "^1.3.0", I made changes to imports, ran npm install, removed node_modules and even deleted package-lock.json. However, I continue to encounter the cryptic error message TypeError: ...

Capture the item selected from the dropdown using ng-model to retrieve the name instead of the

I need help getting the name/text/html of the selected option in a dropdown using angular.js, rather than just its value. Currently, I have this setup which retrieves the value: Here is my HTML code snippet <select class="SelectCar" ng-model="Selected ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Refresh selected items after inserting data via ajax in CodeIgniter

I have a select list on my view that allows users to add new items using a plus button. However, when a new item is added, the list does not refresh. I don't want to refresh the entire page with an ajax query. Instead, I am trying to implement a metho ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

Learn how to create a disappearing dropdown menu in React that closes automatically when you select a specific category

I'm encountering an issue with a dropdown menu that remains visible on the screen even after selecting a specific category. The selected category is displayed in a box upon selection, but the dropdown menu doesn't disappear as intended. I am look ...

What is the correct method for retrieving values from a JSON array?

To extract information from a JSON file, I have created a function as shown below: function getarray(){ $http.get('http://localhost/prebuilt/countries.json') .success(function(data) { $scope.countries = data; }); return data; } Howe ...

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

What is the best way to extract information from my MYSQL database and represent it as an array?

Currently, I am working on a backend API that utilizes a MySQL database. My goal is to extract data from this database and utilize it to plot latitude and longitude points on a map using the Google Maps API. To achieve this, I have integrated the Gmaps API ...

Utilizing Jquery on the client side in conjunction with a Node.js server

I am using nodejs within a docker-compose container to create a local web app. My goal is to use jquery on the client-side to load an HTML file into a div, but I'm encountering issues with it not working properly. Both the initial index.html and the n ...

A guide to implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...