← Back to all snippets
JAVASCRIPT

Implementing Vue Router Navigation Guards

Control route access and behavior in your Vue 3 application using global, per-route, and in-component navigation guards for authentication, data fetching, or redirects.

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

const isAuthenticated = () => {
  // In a real app, check auth token, user session, etc.
  return localStorage.getItem('userToken') === 'someValidToken';
};

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../views/HomeView.vue')
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: () => import('../views/DashboardView.vue'),
      meta: { requiresAuth: true } // Custom meta field
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/LoginView.vue')
    }
  ]
});

// Global navigation guard
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    console.log('Access denied. Redirecting to login.');
    next({ name: 'Login' }); // Redirect to login page
  } else if (to.name === 'Login' && isAuthenticated()) {
    console.log('Already logged in. Redirecting to dashboard.');
    next({ name: 'Dashboard' }); // Already logged in, go to dashboard
  } else {
    next(); // Allow navigation
  }
});

export default router;

// In src/views/DashboardView.vue (Example of per-component guard)
<script setup>
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';

onBeforeRouteLeave((to, from) => {
  const answer = window.confirm('Do you really want to leave? You have unsaved changes!');
  if (!answer) return false; // Prevent navigation
});

onBeforeRouteUpdate((to, from) => {
  // React to route params changes without re-creating component
  console.log('Route params updated:', to.params);
});
</script>
How it works: Vue Router's navigation guards allow you to intercept navigation and perform actions like authentication checks, redirects, or data fetching. This snippet demonstrates a global `beforeEach` guard that checks for authentication based on a `meta` field in the route definition. It also shows `onBeforeRouteLeave` and `onBeforeRouteUpdate` as in-component guards, useful for prompting users before leaving a page with unsaved changes or reacting to dynamic route parameter changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs