Vue Router - Unauthorized access guard error

I'm facing a problem with my navigation guard where the IDE is showing an error stating that requiresAuth is an unresolved variable.

router.beforeEach(async (to, from, next)=>{
    if(to.matched.some((record)=> record.meta.requiresAuth)){
        const currentUser = await getCurrentUser();
        if(await currentUser){
            next()
        }
        else{
            next("/about")
        }
    }
});

This issue arises in my router setup, particularly in the second route which has the meta object containing the requiresAuth property that is unresolved.

const router = createRouter({
    history:createWebHistory(),
    routes:[
        {
            path:"/",
            name:"Home",
            component:Home,
        },
        {
            path:"/dashboard",
            component: Dashboard,
            meta:{
                requiresAuth:true,
            }
        }

    ]
})

Upon starting up the app, I encounter the following console error:

Error: Invalid navigation guard at vue-router.mjs:2008:47

The code fails to proceed beyond the first if statement in the beforeEach hook due to the unresolved requiresAuth variable.

Answer №1

It seems that the issue lies in the fact that not all paths of your navigation guard are calling the next() function

All your code is contained within a single if statement. If this initial if condition is not met, vue-router will not know how to proceed.

router.beforeEach(...) {
  if (to.matched...) {
    if(user) {
      next()
    } else {
      next('/about')
    }
  }
  // Error occurs here
}

Mistakes like these highlight why using the next function is not strongly recommended and is only optionally supported in vue-router 4.

The solution, however, is straightforward. Simply ensure that outside of the initial if statement, the very last line of code includes another call to 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

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Enhancing Images in Next JS

Is there a way to incorporate the NextJS Image element into raw HTML response from the server, such as the following example: HTML = "<div> <p> Some Random text</p> <img src="image1.jpg" /> <img src="image2. ...

Is your Laravel 9 and Inertia app experiencing a CSRF issue resulting in a 419 error message indicating that the page has expired

Whenever I attempt to utilize a delete route after deploying, an error message is displayed: 419 | PAGE EXPIRED Failed to load resource: the server responded with a status of 419 () The function within the Vue component responsible for triggering the rout ...

Combining lodash flow with multiple arguments

In my code, I have two functions that will be added in a lodash flow: function normalizeFields(fields) { return _.mapValues( fields, function(value) { return { 'content': value }; }); } function mergeModelAndFields(model, normal ...

Issue arises of an unspecified string being passed into the controller function

Here is the HTML code snippet I am working with: <!doctype html> <html ng-app='myApp'> <head> <title>My Angular App</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

The React class component is throwing an unexpected error with the keyword 'this'

I encountered an error stating "Unexpected keyword 'this'" while attempting to update the React state using Redux saga. Could someone shed light on what's wrong with the code below and how I can fix it? class Welcome extends React.Component ...

Is the material input label malfunctioning?

When I input data into the model, it appears like this. https://i.sstatic.net/WG12e.png After clicking on the input field, it displays like this. https://i.sstatic.net/3ZVIv.png This is in Blade (model-edit-users). <div class="md-form col-md"> ...

Integrate a Progress Bar showing the upload progress of files

I'm currently revamping an app and I want to replace the generic "please wait" gif with a Bootstrap progress bar that displays the upload progress percentage. However, I'm not well-versed in JavaScript/JQuery and I think I need to incorporate an ...

Extract elements from jQuery response to fill in input fields and dropdown menus

There is a jQuery request that I send to a php file with a business_id parameter. The goal is to retrieve values from the database and use them to populate fields and selects in my form that correspond to this id. However, I am wondering how I can retrieve ...

Determine if I'm actively typing in the input field and alter the loader icon accordingly with AngularJS

Just delving into the world of AngularJS and attempting to tweak an icon as I type in an input box. Currently, I can detect when the box is focused using the following code: $scope.loading = false; $scope.focused = function() { console.log("got ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Creating personalized guidelines in the Kendo UI for Vue Validator

Recently, I have started exploring Kendo UI for Vue. I am interested in using the Kendo Validator Wrapper as it seems quite straightforward for basic validation purposes. In the provided sample code: <div id="vueapp" class="vue-app"> <form id=" ...

Having trouble locating the correct JSON array syntax for Highcharts

Hey there! I'm currently facing a bit of a challenge while trying to set up a JSON array using PHP and integrate it into Highcharts. Currently, I am creating the array in this manner: $stack[] = array($commname => $countit); $stack = json_encode( ...

Transmit an array of JavaScript objects using Email

Within the code layout provided with this post, I have executed various operations in JavaScript which resulted in an array of objects named MyObjects. Each object within MyObjects contains properties for Name and Phone, structured as follows: MyObject ...

Discord.js encountered an error: Invalid Form Body embed.fields[0].value: Please make sure to fill in this required field

My attempts to create an order command for my discord.js bot have been unsuccessful. Whenever someone uses the command, it doesn't respond and instead presents the following error in the console: "This error originated either by throwing inside of an ...

Modifying a nested array found in select documents

One of my JSON entries stored in MongoDB looks like this: { _id: "fe50fdee-4ea3-4824-94af-f369633c0c7a", _class: "com.tracking.daoservice.model.TrackingData", modified: ISODate("2014-09-10T23:38:48.407Z"), eventtype: "William-Test", eventdata: { Query ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...