Answer the question
In order to leave comments, you need to log in
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')
}
})
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
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 questionAsk a Question
731 491 924 answers to any question