What are Vue Router navigation guards in detail?
Answer
Vue Router navigation guards hook into the navigation process to allow, redirect, or cancel navigation. Global guards (on the router object): router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !store.isLoggedIn) { return "/login"; // redirect } return true; // allow }). Can return false (cancel), a route location object (redirect), or true/undefined (allow). next() legacy API still works but returning is cleaner. router.afterEach((to, from, failure) => { sendAnalytics(to.path); }). router.beforeResolve — called after all in-component guards and async route components are resolved. Per-route guards: defined on the route object: { path: "/admin", component: AdminView, beforeEnter(to, from) { if (!isAdmin) return "/403"; } }. Array of guards: beforeEnter: [checkAuth, checkPermission]. In-component guards (Options API): beforeRouteEnter(to, from, next) { next(vm => { vm.doSomething(); }); } — only guard that can access the component instance via callback; beforeRouteUpdate — when navigating to the same component with different params (/user/1 → /user/2); beforeRouteLeave — before leaving, use for unsaved changes warning. Composition API (setup): onBeforeRouteLeave((to, from) => { if (unsavedChanges) return false; });. Route meta: custom data on routes: meta: { requiresAuth: true, roles: ["admin"] } — use in guards for permission checking.
Previous
What is Vue's component communication patterns?
Next
What is Vue's server-side rendering (SSR) with Nuxt?
More Vue.js Questions
View all →- Intermediate What is the Composition API and how do composables work?
- Intermediate What is Vue's reactivity in depth — ref vs reactive?
- Intermediate What are Vue 3 Teleport and Suspense?
- Intermediate What is Vue's virtual DOM and how does the diffing algorithm work?
- Intermediate What is Vue's reactivity with watchEffect and its nuances?