What is a navigation guard?
A navigation guard is a Vue Router mechanism that lets you intercept transitions between routes and run logic before, during, or after navigation.
In simpler terms:
A navigation guard is a "gatekeeper" that decides whether navigation to a route is allowed, whether it needs to redirect, or whether to cancel the transition.
It's used for:
- authorization
- permission checks
- loading data
- confirmations ("Are you sure you want to leave?")
- logging
- redirects
Types of navigation guards
Vue Router has 3 levels of guards.
1. Global Guards
Trigger on every navigation.
router.beforeEach
The main guard for checks:
router.beforeEach((to, from, next) => {
if (!isLoggedIn && to.meta.requiresAuth) {
next('/login')
} else {
next()
}
})router.beforeResolve
Triggers after beforeEach, right before the navigation is resolved.
router.afterEach
Triggers after navigation (side effects: analytics, logging):
router.afterEach((to, from) => {
console.log('Navigated to', to.fullPath)
})2. Route-level Guards
Added directly on the route object:
const routes = [
{
path: '/admin',
component: AdminPage,
beforeEnter(to, from, next) {
if (!isAdmin) next('/not-authorized')
else next()
}
}
]Used for logic that relates to a specific route.
3. In-component Guards
beforeRouteEnter
beforeRouteEnter(to, from, next) {
next(vm => {
// access to vm, the component instance
})
}beforeRouteUpdate
Triggers when the route is updated but the component is reused
(for example /users/1 → /users/2):
beforeRouteUpdate(to, from, next) {
this.fetchUser()
next()
}beforeRouteLeave
Triggers when leaving the page:
beforeRouteLeave(to, from, next) {
if (this.isDirty) {
const answer = confirm("Leave without saving?")
answer ? next() : next(false)
} else {
next()
}
}When should you use navigation guards?
Checking authorization:
if (!isLoggedIn) next('/login')Checking access rights:
if (!user.isAdmin) next('/403')Preloading data (SSR or large pages)
Preventing leaving a page:
For example, unsaved changes.
Redirecting:
next({ name: 'home' })What's important to know for an interview
1) Guards must call next() (except afterEach)
Otherwise the navigation hangs.
2) In Vue Router 4 (Vue 3), next() often does not need to be used
You can return:
true- allowfalse- cancel{ name: 'route' }- redirectundefined- also allow
Example:
router.beforeEach((to) => {
if (to.meta.requiresAuth && !isLoggedIn) {
return { name: 'login' }
}
})3) Global guards apply to all routes
Component guards apply only to one.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.