JAVASCRIPT
Vue 3 Router Navigation Guards for Authentication
Implement Vue Router navigation guards in Vue 3 to protect routes and control access. This snippet shows how to create a global `beforeEach` guard for authentication.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
const isAuthenticated = () => {
// Replace with actual authentication logic (e.g., check token in localStorage)
return localStorage.getItem('user_token') === 'my_secret_token';
};
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue')
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('../views/Dashboard.vue'),
meta: { requiresAuth: true } // Custom meta field
},
{
path: '/login',
name: 'Login',
component: () => import('../views/Login.vue')
}
]
});
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
// If route requires auth and user is not authenticated, redirect to login
next({ name: 'Login' });
} else if (to.name === 'Login' && isAuthenticated()) {
// If user is authenticated and tries to go to login, redirect to dashboard
next({ name: 'Dashboard' });
} else {
// Continue to the route
next();
}
});
export default router;
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
How it works: This snippet demonstrates how to implement global navigation guards in Vue Router 4 for authentication. The `beforeEach` guard checks if a route requires authentication (via `meta.requiresAuth`). If required and the user is not authenticated, it redirects to the login page. It also prevents authenticated users from revisiting the login page, enhancing the user experience and application security.