Skip to content

Vue Router Navigation Guards Explained — Route Protection

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Vue Router Navigation Guards Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Vue Router navigation guards are middleware functions that run before, during, or after route changes, enabling authentication checks, data fetching, and route validation.

What You'll Learn

  • Global guards (beforeEach, beforeResolve, afterEach)
  • Per-route guards (beforeEnter)
  • In-component guards
  • Meta fields for route metadata
  • Async guard patterns

Why It Matters

Navigation guards are essential for protecting routes, redirecting unauthenticated users, loading data before navigation, and preventing accidental data loss on unsaved forms.

import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/dashboard",
      component: () => import("./pages/Dashboard.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/login",
      component: () => import("./pages/Login.vue"),
      meta: { guest: true },
    },
    {
      path: "/settings",
      component: () => import("./pages/Settings.vue"),
      meta: { requiresAuth: true },
    },
  ],
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("auth_token");

  if (to.meta.requiresAuth && !token) {
    next({ path: "/login", query: { redirect: to.fullPath } });
  } else if (to.meta.guest && token) {
    next("/dashboard");
  } else {
    next();
  }
});

Expected output: Unauthenticated users navigating to /dashboard are redirected to /login with the original URL as a query parameter.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro