Vue Tip: Use Vuex in Vue Router Navigation Guards

Michael Hoffmann
Mar 4, 2022
| 1 min read
| 117 views
Michael Hoffmann
Mar 4, 2022
1 min read
| 117 views
Vuex

Vue Router allows us to define Navigation Guards.
For example, we can register them globally:
const router = createRouter({ ... })/*** to: the target route location in a normalized format being navigated to.* from: the current route location in a normalized format being navigated away from.*/router.beforeEach((to, from) => { // ... // explicitly return false to cancel the navigation return false})
A common scenario is to redirect an unauthenticated user to the login page if he tries to visit a protected route:
router.beforeEach(async (to, from) => { if ( // make sure the user is authenticated !isAuthenticated && // ❗️ Avoid an infinite redirect to.name !== 'Login' ) { // redirect the user to the login page return { name: 'Login' } }})
If you are using Vuex you probably store the authenticated state in the Vuex store.
You can easily access that store in your guard navigation:
import store from '@/store'router.beforeEach(async (to, from) => { const authenticated = store.getters['auth/authenticated'] // redirect the user to login page if he is not authenticated if (!authenticated && to.name !== 'Login') { return { name: 'Login' } }})
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.
Show comments