How to Use Route Guard in Vue: Simple Guide with Examples
In Vue, you use
route guards to control access to routes by adding functions like beforeEach on the router instance or beforeEnter on specific routes. These guards let you check conditions before navigation happens, such as user authentication, and decide to allow or block the route change.Syntax
Vue route guards are functions that run before a route changes. You can add them globally on the router, per route, or inside components.
- Global guard: Runs before every route change using
router.beforeEach((to, from, next) => {}). - Per-route guard: Added in route config as
beforeEnter: (to, from, next) => {}. - In-component guard: Use
beforeRouteEnterinside a component.
javascript
const router = createRouter({ history: createWebHistory(), routes: [ { path: '/dashboard', component: Dashboard, beforeEnter: (to, from, next) => { if (isLoggedIn()) { next(); } else { next('/login'); } } } ] }); router.beforeEach((to, from, next) => { console.log(`Navigating to ${to.path} from ${from.path}`); next(); });
Example
This example shows a global route guard that blocks access to the /dashboard route if the user is not logged in, redirecting them to /login. It demonstrates how to protect routes easily.
javascript
import { createRouter, createWebHistory } from 'vue-router'; import Home from './components/Home.vue'; import Dashboard from './components/Dashboard.vue'; import Login from './components/Login.vue'; function isLoggedIn() { return false; // Simulate user not logged in } const routes = [ { path: '/', component: Home }, { path: '/login', component: Login }, { path: '/dashboard', component: Dashboard } ]; const router = createRouter({ history: createWebHistory(), routes }); router.beforeEach((to, from, next) => { if (to.path === '/dashboard' && !isLoggedIn()) { next('/login'); } else { next(); } }); export default router;
Output
When navigating to '/dashboard', user is redirected to '/login' because isLoggedIn() returns false.
Common Pitfalls
Common mistakes when using route guards include:
- Not calling
next()inside the guard, which blocks navigation indefinitely. - Forgetting to handle asynchronous checks properly, causing unexpected behavior.
- Using guards on routes without proper route definitions or components.
- Redirect loops by sending users back and forth between routes.
javascript
/* Wrong: missing next() call blocks navigation */ router.beforeEach((to, from) => { if (to.path === '/dashboard') { // forgot next(), navigation will hang } }); /* Right: always call next() */ router.beforeEach((to, from, next) => { if (to.path === '/dashboard') { next(); } else { next(); } });
Quick Reference
| Guard Type | When It Runs | Usage Example |
|---|---|---|
| Global Guard | Before every route change | router.beforeEach((to, from, next) => { next(); }) |
| Per-Route Guard | Before entering a specific route | beforeEnter: (to, from, next) => { next(); } |
| In-Component Guard | Before entering a component route | beforeRouteEnter(to, from, next) { next(); } |
Key Takeaways
Always call next() in route guards to allow or block navigation.
Use global guards for app-wide checks like authentication.
Use per-route guards for specific route control.
Avoid redirect loops by carefully managing guard logic.
Test guards with different navigation scenarios to ensure correct behavior.