Check out a free preview of the full Vuex for Intermediate Vue.js Developers course:
The "Global Guards" Lesson is part of the full, Vuex for Intermediate Vue.js Developers course featured in this preview video. Here's what you'd learn in this lesson:

Divya shows how to create a global guard to run on all routes. Guards are primarily used to guard navigations either by redirecting it or canceling it.

Get Unlimited Access Now

Transcript from the "Global Guards" Lesson

>> What I wanna do, and move away from, I wanna move away from parent navigation guides, and look at global navigation guards instead, so it's similar, but different. The thing about global navigation guards is that it checks your routes globally, so regardless of whether a route is protected, or not, it checks it.

[00:00:18] So it's useful as a way of just doing a cursory pass to check if a user should be allowed into an app or not. So the other thing to note with this is that the way in which this is useful specifically for protecting your routes is with metadata.

[00:00:37] And again, this is very specific to Vue Router, even though this is a Vuex course but this is super useful when to use in your applications, so it's worth talking about. In my routes array and specifically in my route object within my routes array, I can pass in metadata to my routes.

[00:00:56] Which means that I can specify the routes that I want authentication to be required. So let's assume that I looked at the route, so the admin screen as well as the inventory screen. And I want those two pages specifically and maybe there are more to have requirement that a user is authenticated.

[00:01:17] So I can add that metadata into those routes. And then in my global navigation guards, I can do this check. There's a to.match.sum which checks any metadata, it allows you to match the metadata associated on a route. So here I get access to the route. I'm grabbing metadata to check whether or not auth is required.

[00:01:38] And auth is required is a true or false Boolean, so I can just essentially check is auth required or not. So that's really nice. And then I can also do one other thing, which is, if auth is required, which is the check of the metadata, I can then return next.

[00:01:55] And so this is sort of an extra step. It's not Vuex specific, but it's an extra layer you can add on to your application. So let's say you want to check whether auth is required first, before checking for the islogthengetter. You could write the code for this so it's checks the metadata first before actually calling the getter.

[00:02:17] So you're saving yourself an extra execution without having to automatically call getter everywhere. So here, as I said, you would import the store and then you could do store.getters.["isLoggedIn"], and then pass the user to wherever they need to go appropriately.