1

I have below beforeEach code in my vue js. I need to only check for loggedIn and not authRequired. If I remove the authRequired from the if condition, this function looks. Is there any other way I can just check localstorage value and not check authRequired.

router.beforeEach((to, from, next) => {
  const publicPages = ['/login', '/register'];
  const authRequired = !publicPages.includes(to.path);
  const loggedIn = localStorage.getItem('user');

  if (authRequired && !loggedIn) {
    return next('/login');
  }

  next();
})

I have tried before code. Which gets stuck in continuous loop.

router.beforeEach((to, from, next) => {
  const publicPages = ['/login', '/register'];
  const loggedIn = localStorage.getItem('user');

  if (!loggedIn) {
    return next('/login');
  }

  next();
})
test
  • 305
  • 1
  • 4
  • 12

1 Answers1

1

I can't see any way If you want to keep using the global guards (the router.beforeEach). If you are willing to stop using the global route guards you can use the beforeEnter and apply it to every route manually. In this solution will be able to use the second function on every route except the 'login' route.

const authGuard = (to,from,next) => {
  const loggedIn = localStorage.getItem('user');

  if (!loggedIn) {
      return next('/login');
    }

    next();
}

const routes = [
    {
        path: '/login',
        component: Login
    },
    {
        path: '/someProtectedRoute',
        component: Bar,
        beforeEnter: authGuard
    },
    {
        path: '/anotherProtcted',
        component: Bar,
        beforeEnter: authGuard
    }
]
elad frizi
  • 655
  • 4
  • 9