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();
})
7
  • if (authRequired && !loggedIn) { next('/login');} else { next(); } Commented May 8, 2019 at 8:47
  • if (!loggedIn && to.path !== '/login') { return next('/login') } Commented May 8, 2019 at 8:53
  • @User28 there will be more that one public path. And path as to redirect to its own public path. Commented May 8, 2019 at 8:57
  • What do you mean And path as to redirect to its own public path? Because from your code you only redirect to /login. Commented May 8, 2019 at 9:01
  • @User28 thats why i said. whatever public path it comes from, redirect to the same public path. Commented May 8, 2019 at 9:03

1 Answer 1

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
    }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.