π‘οΈ Vue Navigation Guards β Control Access and Transitions in Your Vue Apps (2025 Guide)
π§² Introduction β What Are Vue Navigation Guards?
Navigation Guards in Vue Router are lifecycle hooks that let you control access to routes during navigation. These guards let you authenticate users, restrict access, run validations, or log activity before or after route transitions.
π― In this guide, youβll learn:
- What types of navigation guards exist
- Syntax for global, per-route, and in-component guards
- Real-world use cases (auth, roles, confirmations)
- Best practices and examples
π What Is a Navigation Guard?
A navigation guard is a function that intercepts a route change before it completes. It can:
- Allow or block navigation
- Redirect to another route
- Run async operations (like API validation)
π Types of Navigation Guards
Type | When It Runs | Scope |
---|---|---|
Global Guards | On every route change | App-wide |
Per-Route Guards | On specific route definition | Route-level |
In-Component Guards | When entering/leaving a component | Component |
π Global Navigation Guards
β
router.beforeEach
Runs before every navigation. Use it to protect all routes.
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login');
} else {
next();
}
});
π§ next()
proceeds, next(false)
cancels, next('/path')
redirects.
β
router.afterEach
Runs after navigation is confirmed.
router.afterEach((to, from) => {
console.log(`Navigated from ${from.path} to ${to.path}`);
});
π¦ Per-Route Navigation Guards
β Route Definition Example:
{
path: '/admin',
component: AdminPage,
beforeEnter: (to, from, next) => {
if (!isAdmin()) {
next('/unauthorized');
} else {
next();
}
}
}
π§ Good for securing specific routes like /admin
or /dashboard
.
𧬠In-Component Navigation Guards
These hooks are placed inside the component’s <script>
block.
β
beforeRouteEnter
Runs before the route is entered. No access to this
, but next()
can be passed a callback.
beforeRouteEnter(to, from, next) {
next(vm => {
console.log('Entered with access to', vm);
});
}
β
beforeRouteUpdate
Runs when params or query changes but the component is reused.
beforeRouteUpdate(to, from, next) {
// Called when /user/:id changes but same component
this.fetchData(to.params.id);
next();
}
β
beforeRouteLeave
Runs when leaving the component. Useful for confirmations.
beforeRouteLeave(to, from, next) {
if (this.unsavedChanges) {
const answer = window.confirm('Discard changes?');
answer ? next() : next(false);
} else {
next();
}
}
π§° Real-World Use Case β Auth Guard
β
router.js
router.beforeEach((to, from, next) => {
const isAuth = localStorage.getItem('auth');
if (to.meta.requiresAuth && !isAuth) {
next('/login');
} else {
next();
}
});
β Route Meta Tag:
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
β οΈ Best Practices
Best Practice | Why? |
---|---|
Use meta fields | Keep auth logic clean and reusable |
Avoid async inside next() | Always return next() only once |
Use next(false) to block navigation | Prevent user from leaving a route |
Call next() in all branches | Prevent hanging transitions |
π Summary β Recap & Next Steps
Vue Navigation Guards are essential for adding logic and control to your routes. Whether youβre protecting admin pages, validating data, or confirming navigation, guards keep your app secure and user-friendly.
π Key Takeaways:
- Use global guards for universal auth logic
- Use per-route guards for fine-grained control
- Use in-component guards for lifecycle-based transitions
- Always handle
next()
properly
βοΈ Real-World Relevance:
Used in apps with authentication, role-based access, form validation, and dynamic route conditions.
β FAQ Section
β What is a navigation guard in Vue?
β It’s a hook that runs during route transitions to control access or behavior.
β How do I protect routes in Vue Router?
β
Use router.beforeEach()
and check to.meta.requiresAuth
.
β What does next()
do in navigation guards?
β It continues the navigation. You can pass false to cancel or a path to redirect.
β What is the difference between global and component guards?
β Global guards apply app-wide, component guards run inside specific components.
β Can I cancel navigation with guards?
β
Yes, use next(false)
to stop navigation.
Share Now :