JAVASCRIPT
Implementing Global Route Guards in Vue Router 4
Secure your Vue 3 application by implementing global route guards with Vue Router 4's `beforeEach` method, preventing unauthorized access to specific routes.
// router/index.js (or wherever your router instance is created)
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/', component: () => import('../views/Home.vue') },
{ path: '/dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } },
{ path: '/login', component: () => import('../views/Login.vue') },
{ path: '/admin', component: () => import('../views/Admin.vue'), meta: { requiresAuth: true, requiresAdmin: true } }
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Global before guard
router.beforeEach((to, from, next) => {
// Simulate a user authentication state
const isAuthenticated = localStorage.getItem('userToken') === 'true';
// Simulate admin role
const isAdmin = localStorage.getItem('userRole') === 'admin';
if (to.meta.requiresAuth && !isAuthenticated) {
// If the route requires auth and the user is not authenticated, redirect to login
console.log('Redirecting to login: Requires authentication.');
next('/login');
} else if (to.meta.requiresAdmin && !isAdmin) {
// If the route requires admin and the user is not an admin, redirect to dashboard or home
console.log('Redirecting: Requires admin role.');
next('/dashboard'); // Or any other fallback route
} else if (to.path === '/login' && isAuthenticated) {
// If user is authenticated and tries to go to login, redirect to dashboard
console.log('Redirecting from login: Already authenticated.');
next('/dashboard');
} else {
// All good, proceed to the route
next();
}
});
export default router;
// Example usage in main.js
// import { createApp } from 'vue';
// import App from './App.vue';
// import router from './router';
// const app = createApp(App);
// app.use(router);
// app.mount('#app');
How it works: This snippet demonstrates how to implement global route guards in Vue Router 4 using `router.beforeEach`. This guard runs before every navigation and allows you to control access to routes based on conditions like user authentication or roles. It uses `to.meta` properties, defined in the route configuration, to specify requirements for each route. The `next()` function is crucial for resolving the navigation: `next('/')` redirects, `next(false)` cancels, and `next()` allows the navigation to proceed.