Dom
Dom

Reputation: 3444

Vue Router: infinite redirection

I am using Vue 3 and Vue Router4.0.

I want to build a routing system with authentication and authorizations. In my "router.js" file , I wrote:

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
  },
  {
    path: "/home",
    component: Home,
    meta: { requiresAuth: false }
  },
  {
    path: "/login",
    component: Login,
    meta: { requiresAuth: false }
  },
.....

and I added the "beforeEach" like the documentation explained :

router.beforeEach(async(to) => {
  //todo : get the store here 
  const user = JSON.parse(localStorage.getItem('user'));
  const loggedIn = localStorage.getItem('user') == null ? false : true;
  const roleId = user ? user.role_id : 'UNKNOWN';
  const authorizedRoles = to.meta.authorizedRoles ? Array.from(to.meta.authorizedRoles) : [];
  
  // no authentication required
  if (!to.meta.requireAuth) {
    console.log('no authorization required')
    return { path: to.fullPath}
  }
....

when I am going to the route "/login", I have the message:

[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/login".

I am learning Vue and Vue Router and I don't understand what is happening.

Upvotes: 1

Views: 953

Answers (2)

Daniel Klimek
Daniel Klimek

Reputation: 144

I like to use router guard like this:

router.beforeEach((to, from, next) => {
  
  if(to.matched.some(record => record.meta.requiresAuth) && !userIsAuthenticated)
     next({name: "Login"});
  else
     next()
    
});

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222309

return { path: to.fullPath} results in a redirect to the same route and causes infinite redirect.

It should be:

return true

Upvotes: 4

Related Questions