M1kkelZUUU
M1kkelZUUU

Reputation: 41

'Maximum call stack size exceeded' VueJS routing

Basically the router.beforeEach() method is doing something I don't understand.

I get the jist of the issue being that when my route is re-directing to /login it will do it around 960 times or so until the error occurs.

my code is like so:

Router:

let router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path:'/login',
      name: 'login',
      component: Login,
      meta: {
        requiresAuth: 'false'
      }
    },
    {
      path:'/register',
      name: 'register',
      component: Register,
      meta: {
        requiresAuth: 'false'
      }
    },
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: 'True'
      }
    }
  ]
})

the beforeEach() method

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {

    console.log(to.matched.some(record => record.meta.requiresAuth))
    if (localStorage.getItem('jwt') == null) {
      next({
       path: '/login',
        params: { nextUrl: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    if (localStorage.getItem('jwt') != null) {
      next({
        path: '/',
        params: { nextUrl: '/' }
      })
    } else {
      next()
    }
  }
})

I've looked through countless threads and other places and none have the same issue as me (or I'm overlooking things). Anyone got an idea on how to fix, and what is actually happening to make the error occur in this? from what I can tell I have nothing named twice or any other function/component fire off when it shouldn't.

Upvotes: 2

Views: 8111

Answers (2)

Jousi
Jousi

Reputation: 476

For anyone who gets this error without any obvious mistake, try deleting node_modules and running npm install again. I got this error when switching git branches and the only thing that changes were the packages, so I tried the above and it got rid of the problem :)

Upvotes: 0

M1kkelZUUU
M1kkelZUUU

Reputation: 41

Fixed it. I'm a bit special in the head. For anyone with the same issue just change the routes to

routes: [
    {
        path: '/login',
        name: 'login',
        component: Login,
        meta: {
          requiresAuth: false
        }
    },
    {
      path:'/register',
      name: 'register',
      component: Register,
      meta: {
        requiresAuth: false
      }
    },
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: true
      }
    }
  ]

Upvotes: 2

Related Questions