JAVASCRIPT

Vue Router Programmatic Navigation and Global Route Guards

Master Vue 3 Router's programmatic navigation and implement global navigation guards to control access and enforce authorization before routes are resolved.

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', component: () => import('@/views/HomeView.vue'), name: 'home' },
  { path: '/dashboard', component: () => import('@/views/DashboardView.vue'), name: 'dashboard', meta: { requiresAuth: true } },
  { path: '/login', component: () => import('@/views/LoginView.vue'), name: 'login' },
  { path: '/profile/:id', component: () => import('@/views/ProfileView.vue'), name: 'profile', props: true },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/views/NotFound.vue') },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// Global Navigation Guard
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('userToken'); // Simulate auth state
  if (to.meta.requiresAuth && !isAuthenticated) {
    // Redirect to login page if authentication is required and user is not authenticated
    next({ name: 'login', query: { redirect: to.fullPath } });
  } else if (to.name === 'login' && isAuthenticated) {
    // Prevent authenticated users from going to login page
    next({ name: 'dashboard' });
  }
  else {
    next(); // Proceed to the route
  }
});

export default router;

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // Import the router instance

const app = createApp(App);
app.use(router); // Use the router plugin
app.mount('#app');

// src/views/HomeView.vue (Example)
<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome to the application!</p>
    <button @click="goToDashboard">Go to Dashboard (Programmatic)</button>
    <router-link :to="{ name: 'profile', params: { id: 123 } }">View Profile 123</router-link>
    <button @click="logout">Logout (Simulated)</button>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const goToDashboard = () => {
  router.push({ name: 'dashboard' });
};

const logout = () => {
  localStorage.removeItem('userToken');
  alert('Logged out!');
  router.push({ name: 'login' });
};
</script>
How it works: This snippet covers two critical Vue Router features: programmatic navigation and global navigation guards. `createRouter` configures the routes, including `meta` fields for authentication requirements. `router.beforeEach` implements a global guard that checks if a route requires authentication (`to.meta.requiresAuth`) and redirects unauthenticated users to the login page. It also prevents authenticated users from revisiting the login page. In `HomeView.vue`, `useRouter` provides access to the router instance, allowing programmatic navigation using `router.push()` to change routes based on user actions (e.g., clicking a button). Simulated `localStorage` is used for authentication state.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs