7
7
700Hp2022-01-27 11:07:55
JavaScript
700Hp, 2022-01-27 11:07:55

How to check if the accessToken is valid before going through the route?

I have a default isAuth variable false which I store in the store.
After login, access is stored in local storage and isAuth = true.
Everything works fine for unauthorized users.

The error is that after reloading the page, the main file checks the current token for validity. And the router is loaded before the answer arrives and immediately redirects as unauthorized.
app.vue

onBeforeMount( async () => {
       const accessToken = localStorage.getItem('auth-token')
        if (accessToken) {
        await store.dispatch('auth/checkAuth')
      }
     })


router.beforeEach
if (requireAuth && store.getters['auth/isAuth']) {
    next()
  } else if (requireAuth && !store.getters['auth/isAuth']) {
    next({name: 'login'})
  } else if (!requireAuth && store.getters['auth/isAuth']) {
    next({name: 'admin'})
  } else {
    next()
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Kadyrov, 2022-01-31
@Ahmad66617

Perhaps I won’t tell you exactly about Vue, but in angular there is a resolver for this - maybe Vue also has it, also if state management is organized, for example NgRx - then the states also have a routing side effect where you can actually track before, after and the moment of transition etc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question