Vue 3 Intermediate
What are Vue Router navigation guards?
What are Route Guards?
Route guards are Vue Router's navigation interception mechanism, allowing us to run logic before or after route changes — e.g., authentication checks, setting page titles, logging visits.
Three Types
1. Global Guards
Apply to all routes.
const router = createRouter({ /* ... */ })
// Global before guard (most commonly used)
router.beforeEach((to, from, next) => {
const isAuthenticated = !!localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next({ name: 'Login' }) // redirect to login
} else {
next() // proceed with navigation
}
})
// Global after hook (runs after navigation; no next)
router.afterEach((to, from) => {
document.title = to.meta.title || 'My Site'
})
2. Per-Route Guards
Defined in the route config; applies only to that route.
const routes = [
{
path: '/admin',
component: AdminPage,
beforeEnter: (to, from, next) => {
if (!isAdmin()) {
next({ name: 'Home' })
} else {
next()
}
}
}
]
3. In-Component Guards
Defined inside a component; applies only to that component.
// Options API
export default {
beforeRouteEnter(to, from, next) {
// Component not yet created; cannot access this
next(vm => { /* vm is the component instance */ })
},
beforeRouteUpdate(to, from, next) {
// Route params changed but component is reused (e.g. /user/1 → /user/2)
next()
},
beforeRouteLeave(to, from, next) {
// Leaving the page — useful for unsaved changes warnings
if (this.hasUnsavedChanges) {
if (!confirm('You have unsaved changes. Leave anyway?')) return
}
next()
}
}
Execution Order
beforeEach(global)beforeEnter(per-route)beforeRouteEnter(in-component)- Resolve async route components
afterEach(global, after navigation completes)
Common Use Cases
| Scenario | Recommended guard |
|---|---|
| Login authentication | router.beforeEach |
| Set page title | router.afterEach |
| Page permission control | beforeEnter + meta |
| Unsaved changes warning | beforeRouteLeave |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
