Javascript is required
·
1 min read

Vue Tip: Use Vuex in Vue Router Navigation Guards

Vue Tip: Use Vuex in Vue Router Navigation Guards Image

Vue Router allows us to define Navigation Guards.

For example, we can register them globally:

1const router = createRouter({ ... })
2
3/**
4* to: the target route location in a normalized format being navigated to.
5* from: the current route location in a normalized format being navigated away from.
6*/
7router.beforeEach((to, from) => {
8  // ...
9  // explicitly return false to cancel the navigation
10  return false
11})

A common scenario is to redirect an unauthenticated user to the login page if he tries to visit a protected route:

1router.beforeEach(async (to, from) => {
2  if (
3    // make sure the user is authenticated
4    !isAuthenticated &&
5    // ❗️ Avoid an infinite redirect
6    to.name !== 'Login'
7  ) {
8    // redirect the user to the login page
9    return { name: 'Login' }
10  }
11})

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:

1import store from '@/store'
2
3router.beforeEach(async (to, from) => {
4  const authenticated = store.getters['auth/authenticated']
5
6  // redirect the user to login page if he is not authenticated
7  if (!authenticated && to.name !== 'Login') {
8    return { name: 'Login' }
9  }
10})

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.