JAVASCRIPT

Securing Routes with Global Navigation Guards in Vue Router

Implement global `beforeEach` navigation guards in Vue 3 Router to protect specific routes based on user authentication status, ensuring only authorized users access certain paths.

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

const isAuthenticated = () => {
  // Replace with your actual authentication check (e.g., checking a token in localStorage)
  return localStorage.getItem('userToken') !== null;
};

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/DashboardView.vue'),
    meta: { requiresAuth: true } // Meta field to mark protected routes
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  }
];

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

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 {
    // Proceed to route
    next();
  }
});

export default router;
How it works: This snippet demonstrates how to use `router.beforeEach` as a global navigation guard in Vue Router to protect routes. It checks if a route requires authentication using a `meta` field. If a protected route is accessed by an unauthenticated user, they are redirected to the login page. Conversely, an authenticated user trying to access the login page is redirected to the dashboard, providing a seamless user experience for authentication flows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs