After implementing global navigation guards in Vue-router, an unexpected error message stating "Uncaught TypeError: Cannot read property 'matched' of undefined" is being thrown

After successfully navigating the login process and implementing user-role-based routing, I proceeded to set up authentication guards for different URLs.

Though it initially seemed straightforward, I encountered an error that I haven't been able to troubleshoot due to a lack of similar use case examples. Most instances of this error that I've come across involved misnaming the router instance something other than "router," which isn't the case here, as far as I can tell. Just so you know, I'm using the vue-cli template with webpack.

This is from my index.js:

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/trucker',
      component: Trucker,
      meta: { requiresAuth: true, truckerAuth : true, dispatchAuth: false },
      children: [
                {
                  path: '/loads',
                  component: Loads
                }
            ]
    },
    {
      path: '/dispatch',
      component: Dispatch,
      meta: { requiresAuth: true, truckerAuth : false, dispatchAuth: true },
      children: [
                {
                  path: '/drivers',
                  component: Drivers
                }
                ]
    },

  ]
})

router.beforeEach((to, from, next) => {
  if(to.meta.requiresAuth) {
    const employeeId = window.localStorage.getItem('employee_id')
    if(!employeeId) {
      next('/login')
    }
    else if(to.meta.truckerAuth) {
    const employeeId = window.localStorage.getItem('employee_id')
    if(employeeId === 3) {
      next()
    }else {
      next('/login')
    }
  } else if(to.meta.dispatchAuth) {
    const employeeId = window.localStorage.getItem('employee_id')
    if(employeeId === 2) {
      next()
    }else {
      next('/login')
    }
  }
  }else {
  next()
  }
})

And from my main.js:

import router from './router'

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Can anyone provide insight into what might be causing this issue?

Update: After some trial and error, I discovered the root of the problem - changing my previous export default new Router syntax to const router = new Router, along with adjusting "Router" to VueRouter to match example conventions, seems to have triggered the error. Still unsure why that alteration resulted in the issue though.

Answer №1

After some reflection, I realized that relocating my navigation guard from index.js to main.js was the solution.

The revised files now appear as follows:

index.js:

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/trucker',
      component: Trucker,
      meta: { requiresAuth: true, truckerAuth : true, dispatchAuth: false },
      children: [
        {
          path: '/loads',
          component: Loads
         }
      ]
    },
    {
      path: '/dispatch',
      component: Dispatch,
      meta: { requiresAuth: true, truckerAuth : false, dispatchAuth: true },
      children: [
        {
          path: '/drivers',
          component: Drivers,
          children: [
            {
              path: 'calendar',
              component: Calendar
            }
          ]
        }
      ]
    },

  ]
})

main.js:

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
router.beforeEach((to, from, next) => {
  if(to.meta.requiresAuth) {
    const employeeId = window.localStorage.getItem('employee_id')
    if(employeeId == null) {
      next('/login')
    } else if(to.meta.truckerAuth) {
      const employeeId = window.localStorage.getItem('employee_id')
      console.log(employeeId)
      if(employeeId === 3) {
        next('/trucker')
      } else {
        next('/')
        console.log(employeeId)
      }
    } else if(to.meta.dispatchAuth) {
      const employeeId = window.localStorage.getItem('employee_id')
      if(employeeId === 2) {
        next()
      } else {
        next('/')
      }
    }
  } else {
    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

Vuex is throwing a mysterious ReferenceError that is leaving developers

Currently, I am developing a Single Page Application (SPA) using Vue.js and Vuex. Within this project, I have set up some data in the store and displayed it in a child component. This child component includes radio buttons that trigger a function called ge ...

Checking the status of a checkbox after submitting using AngularJs

For my first application, I am utilizing AngularJs and JavaScript to display information from an API as checkboxes. Currently, the functionality is working well, but I am unsure how to validate if any checkbox options are checked with a submit button. Aft ...

Get the value of a function that was previously assigned to an onclick event using JavaScript

Here is the code snippet I am currently working with: document.getElementById(myid).onclick = function() { HandleGPIO(val1, val2); }; if (console) { console.log(document.getElementById(myid).getAttribute('onclick')); } My goal is to de ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

What could be the reason for not seeing any console.log output while executing findOne using Mongoose?

My goal is to query my MongoDB database using Mongoose. I am searching for the string 13 in the field eClassSegment within the collection eclasses. When I run the code, something gets printed in the console. Why is that? Here is the code I am using: var ...

Attempting to create distinct match matchups for every team in a manner reminiscent of the Swiss system format used in the 2024/25 UEFA Champion League

I've been working on devising a tournament pairing system modeled after the updated UEFA Champion League structure. The league phase involves 36 teams, categorized into 4 different pots. Each team is scheduled to play a total of 8 matches against 2 op ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

In Inertia.js, a mysterious blank page appeared without any errors showing up in the console

For the past 8 hours, I have been struggling to make Inertia.js work seamlessly with Laravel and VueJS. Despite my efforts, all I see is a blank page without any error messages in either the front-end or back-end consoles. The only thing that indicates act ...

Having trouble with the Refresh or Direct Url not functioning properly after bundling with webpack in a React JS project

I encountered an error where the react js app with browser history was only functioning normally. However, after building with webpack, I faced issues with refreshing or pasting relative URLs. Switching to hash history resolved the problem. Despite trying ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

Adding Gridster to a WordPress theme

I am having an issue with implementing Gridster into my WordPress plugin. Despite correctly loading the necessary files from the folder, it does not seem to work. function add_my_stylesheet() { wp_enqueue_style( 'myCSS', plugins_url( ' ...

The Google API is experiencing issues when using input that has been added on

Situation: In my attempt to integrate a Google address search feature into an online shopping website, I encountered a challenge. I don't have direct access to the website's HTML code, but I can insert code snippets in the header, footer, and in ...

Ways to retrieve a specific object property from an array of objects within a click event listener?

I have instantiated multiple object constructors and stored them in an array which I loop over to display as a list. Now, I am trying to extract the name property from that list to use in an onclick event handler (not included in this code). I am unsure of ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...

Exploring React and NextJS Select: Leveraging fetch to iterate over an object and retrieve existing values exclusively

My goal is to access player stats for a specific season using the NHL api. I have a utility function that includes various season options: export const seasonOptions = [ { value: "19861987", label: "1986/1987" }, { value: "1987 ...

Exclusively utilize optgroup multiple functionality within bootstrap-select

I'm currently utilizing https://github.com/snapappointments/bootstrap-select/ version 1.13.18 and I am in need of a solution where only optgroup options can have multiple selections. This means that if a non-optgroup option is selected, all other opti ...

Using Vue3 to create a dynamic reference in a computed status, allowing for the repetition of a player multiple times in a table along with a play/pause

On the Vue3 page below, I have successfully integrated a player that displays a "play" icon when the player is stopped and a "pause" icon when it's playing. Now, my goal is to allow the player to repeat n times by placing it in a table. The challeng ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...