JAVASCRIPT
Programmatic Navigation and Route Guards with Vue Router 4
Learn to control navigation programmatically using `router.push()` and implement global `beforeEach` navigation guards in Vue Router 4 for authentication or page access control.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{ path: '/', name: 'Home', component: () => import('../views/HomeView.vue') },
{ path: '/dashboard', name: 'Dashboard', component: () => import('../views/DashboardView.vue'), meta: { requiresAuth: true } },
{ path: '/login', name: 'Login', component: () => import('../views/LoginView.vue') },
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFoundView.vue') },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Global Navigation Guard
router.beforeEach((to, from, next) => {
// Simulate authentication state
// In a real app, this would check a token in localStorage, a global store, etc.
const isAuthenticated = localStorage.getItem('userLoggedIn') === 'true';
if (to.meta.requiresAuth && !isAuthenticated) {
// If route requires auth and user is not logged in, redirect to login
next({ name: 'Login', query: { redirect: to.fullPath } });
} else if (to.name === 'Login' && isAuthenticated) {
// If user is logged in and tries to access login page, redirect to dashboard
next({ name: 'Dashboard' });
} else {
// Allow navigation
next();
}
});
export default router;
// Usage in a Vue component for programmatic navigation (e.g., in LoginView.vue or a header component)
/*
<template>
<div>
<h1>Login Page</h1>
<button @click="performLogin">Simulate Login</button>
<button @click="goToDashboard">Go to Dashboard (Programmatic)</button>
</div>
</template>
<script setup>
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const performLogin = () => {
// Simulate login success
localStorage.setItem('userLoggedIn', 'true');
const redirectPath = route.query.redirect || '/dashboard';
router.push(redirectPath); // Navigate to dashboard or original intended path
};
const goToDashboard = () => {
router.push({ name: 'Dashboard' }); // Programmatic navigation by name
};
</script>
*/
How it works: This snippet demonstrates programmatic navigation and global navigation guards in Vue Router 4. The `router.beforeEach` guard runs before every route change, allowing you to implement logic like authentication checks or redirects. If a route requires authentication (`meta: { requiresAuth: true }`) and the user isn't logged in, they are redirected to the login page. Programmatic navigation using `router.push()` allows you to imperatively change routes, useful for actions like post-login redirects or button clicks, offering fine-grained control over the user's journey.