| | |

Vue Router 08 🧭 Navigation Guards — Controlling access with beforeEach, beforeResolve, afterEach, and modern return-based guard syntax

⏱️ Estimated read: 11 min | |

Navigation guards are the lifecycle hooks of Vue Router. They allow developers to intercept the navigation process at various points—globally, per-route, or within a component—to decide whether to allow the user to proceed, redirect them elsewhere, or cancel the navigation entirely. These guards are essential for implementing authentication systems, role-based access control, and ensuring that data is pre-fetched or saved before a user leaves a page.

In modern Vue Router (version 4 and later), the navigation guard API has shifted towards a simpler, more robust “return-based” syntax. While the legacy next callback is still supported for backward compatibility, the recommended approach is now to return a value from the guard function. This return value can be a boolean to allow/block navigation or a route location object to perform an immediate redirect.

This chapter covers the full hierarchy of navigation guards. We will explore global guards that run on every navigation, per-route guards defined directly in the route configuration, and in-component guards that handle component-specific logic like “unsaved changes” prompts. We will also detail the specific execution order of these guards and how to use the modern return syntax to write cleaner, more predictable security logic.

Key point: Navigation guards are asynchronous hooks that intercept navigation to protect routes or handle side effects; in Vue Router 4, you should return false to cancel or a route object to redirect, rather than using the legacy next callback.


Why exists

The Authentication Problem. Public and private routes must be clearly separated. Navigation guards provide a centralized “checkpoint” where you can verify a user’s login status before they ever reach a sensitive component. Without guards, you would have to check auth status inside the created or mounted hook of every single protected component.

The Authorization Problem. Even if a user is logged in, they might not have the correct permissions (e.g., “Editor” vs. “Admin”). Guards allow you to inspect route metadata and user roles to ensure users only access what they are permitted to see, providing a robust layer of client-side security.

The Unsaved Changes Problem. Users often accidentally navigate away from forms while they are in the middle of typing. In-component guards like beforeRouteLeave allow the application to pause navigation and prompt the user with a confirmation dialog, preventing data loss.

The Data Pre-fetching Problem. Sometimes you want to ensure data is available before the component is even rendered to avoid “pop-in” effects or empty states. Guards like beforeResolve can wait for API calls to resolve, ensuring the user sees a fully populated page the moment the navigation finishes.

The Global Side-Effect Problem. Every time a user changes pages, certain global actions might need to occur, such as updating the browser title, sending analytics pings, or starting a progress bar. Global guards provide a single place to manage these cross-cutting concerns for the entire application.

The Infinite Loop Problem. Managing redirects manually can lead to loops where page A redirects to B, and B redirects back to A. The modern return-based syntax in Vue Router 4 helps prevent these common logic errors by providing a more structured way to handle redirection.


a. Global Guards: The Application Checkpoints

Global guards are defined on the router instance and run for every navigation triggered in the application. The most common is beforeEach, which is called before any other guard and is the primary place for authentication logic.

router.beforeEach(async (to, from) => {
  const isAuthenticated = await checkAuth();

  // If the route requires auth and user is not logged in
  if (to.meta.requiresAuth && !isAuthenticated) {
    // Redirect to login page
    return { name: 'Login' };
  }
  // Returning nothing (or undefined) allows navigation
});

beforeResolve is called right before the navigation is confirmed, after all in-component guards and async route components have been resolved. It is the ideal place for data fetching or any logic that needs the component to be ready but not yet mounted.

router.beforeResolve(to => {
  if (to.meta.requiresData) {
    return fetchDataFor(to.params.id); // Wait for data before finishing
  }
});

Finally, afterEach is called after the navigation has been completed. Unlike the other global hooks, it does not receive a way to affect the navigation (it has no return value that changes the route). It is used for side effects like closing a loading bar or updating tracking scripts.

router.afterEach((to, from) => {
  sendAnalytics(to.fullPath);
  document.title = to.meta.title || 'Default Title';
});

b. Per-Route and In-Component Guards

Per-route guards are defined directly within the route configuration using the beforeEnter property. This is useful when security logic only applies to a specific route or a group of routes, keeping the global beforeEach guard lean.

const routes = [
  {
    path: '/admin',
    component: AdminView,
    beforeEnter: (to, from) => {
      // Logic specific only to the admin route
      if (!isAdmin()) return false;
    }
  }
];

In-component guards are defined inside the Vue component itself. They provide the most granular control because they have access to the component’s state (this in Options API). There are three primary in-component guards: beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave.

export default {
  beforeRouteLeave(to, from) {
    if (this.hasUnsavedChanges) {
      const answer = window.confirm('Do you really want to leave?');
      if (!answer) return false; // Cancel navigation
    }
  },
  beforeRouteUpdate(to, from) {
    // Called when the route changes but the component is reused
    // (e.g., /user/1 -> /user/2)
    this.userId = to.params.id;
    this.fetchUserData();
  }
};

Note that beforeRouteEnter does NOT have access to this because the component hasn’t been created yet. If you need to access the instance, you must pass a callback to the legacy next function (the only place where next is still commonly used in a specific way).


c. The Modern Return-Based Syntax

Vue Router 4 introduced a significant change: guards now prefer return values over the next callback. This makes guards easier to read and prevents the common mistake of calling next() multiple times or forgetting to call it entirely, which hangs the navigation.

// ✅ MODERN: Returning a value
router.beforeEach((to) => {
  if (shouldBlock) return false;        // Cancels
  if (shouldRedirect) return '/login'; // Redirects
  return true;                         // Allows (default)
});

// ❌ LEGACY: Using next()
router.beforeEach((to, from, next) => {
  if (shouldBlock) next(false);
  else if (shouldRedirect) next('/login');
  else next();
});

When you return a string or an object from a guard, it is treated as a redirect. This redirect creates a new navigation, meaning the current navigation is aborted and all guards will run again for the new target. This ensures that the security logic for the “Login” page is also respected.

The return-based syntax also handles asynchronous logic naturally. If the guard function is async, Vue Router will wait for the promise to resolve before moving to the next guard in the sequence. If the promise rejects, the navigation is cancelled and an error is triggered.


Complete Example Session

// ============================================
// PART 1: THE ROUTER INSTANCE
// ============================================
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { 
      path: '/dashboard', 
      component: Dashboard, 
      meta: { requiresAuth: true } 
    },
    {
      path: '/admin',
      component: Admin,
      beforeEnter: [checkAdminRole, logAdminAccess] // Array of guards
    }
  ]
});

// ============================================
// PART 2: GLOBAL AUTH GUARD (MODERN SYNTAX)
// ============================================
router.beforeEach(async (to) => {
  const store = useUserStore();

  if (to.meta.requiresAuth && !store.isLoggedIn) {
    // Redirect to login with the original destination as a query param
    return { 
      name: 'Login', 
      query: { redirect: to.fullPath } 
    };
  }
});

// ============================================
// PART 3: IN-COMPONENT GUARD (UNSAVED CHANGES)
// ============================================
// Inside EditorComponent.vue
const beforeRouteLeave = (to, from) => {
  if (isDirty.value) {
    const confirm = window.confirm("Discard changes?");
    if (!confirm) return false;
  }
};

// ============================================
// PART 4: DATA PRE-FETCHING WITH RESOLVE
// ============================================
router.beforeResolve(async (to) => {
  if (to.params.id) {
    try {
      await fetchResource(to.params.id);
    } catch (e) {
      return { name: 'Error', params: { msg: 'Not Found' } };
    }
  }
});

// ============================================
// PART 5: PROGRESS BAR COMPLETION
// ============================================
router.afterEach(() => {
  NProgress.done();
});

This sequence covers global authentication redirection, per-route role checking, in-component data protection, and global side-effect management.


Quick Reference

Guard Execution Order

  1. Leave: beforeRouteLeave (In-component)
  2. Global Before: beforeEach (Global)
  3. Update: beforeRouteUpdate (In-component – if reused)
  4. Route Before: beforeEnter (Route config)
  5. Enter: beforeRouteEnter (In-component)
  6. Global Resolve: beforeResolve (Global)
  7. Complete: afterEach (Global side effects)

Guard Return Values (Modern)

Return ValueAction
true / undefinedConfirm navigation
falseCancel navigation (stay on current page)
'/path'Redirect to string path
{ name: 'X' }Redirect to named route
ErrorCancel and trigger router.onError

Comparison of Global Guards

GuardAccess to to/fromCan Cancel/Redirect?Typical Use
beforeEachYesYesAuthentication, Roles
beforeResolveYesYesAsync data fetching
afterEachYesNoAnalytics, Page Titles

Best Practices

✅ Do This:

// Use return values instead of next()
router.beforeEach(to => { return true; });                   // ✅
// Use async/await for cleaner async guards
router.beforeEach(async to => { await auth(); });            // ✅
// Handle multiple guards in an array for per-route
beforeEnter: [guardOne, guardTwo]                             // ✅
// Use meta fields to categorize routes for guards
if (to.meta.public) return;                                  // ✅

❌ Don’t Do This:

// Call next() multiple times in one guard
if (a) next(); if (b) next('/login');                        // ❌
// Forget to return a value in a conditional (leads to hangs)
if (auth) return true; /* missing else */                    // ❌
// Perform heavy API calls in beforeEach (slows every click)
router.beforeEach(async () => { await fetchGiantList(); });  // ❌
// Rely on 'this' in beforeRouteEnter
beforeRouteEnter() { console.log(this.name); }               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Infinite Redirect LoopRedirecting to a route that triggers the same guardCheck to.name !== 'Login' before redirecting
Guard Not FiringUsing afterEach to try and stop navigationUse beforeEach or beforeResolve instead
Component StuckAsync guard promise never resolves/rejectsEnsure all code paths return or the promise finishes
Params MissingNavigating via beforeRouteUpdate without paramsEnsure to.params is used to update state
next vs Returnmixing both styles in the same appStandardize on the return-based syntax

Real-World Examples

1. Basic Auth Guard

router.beforeEach(to => (to.meta.requiresAuth && !isLoggedIn() ? '/login' : true));

2. Dynamic Title Update

router.afterEach(to => { document.title = to.meta.title || 'App'; });

3. Role Check Guard

const isAdmin = (to) => to.meta.role === 'admin' && user.role !== 'admin' ? false : true;

4. Progress Bar Start

router.beforeEach(() => { NProgress.start(); });

5. Unsaved Changes Prompt

beforeRouteLeave() { return window.confirm('Discard changes?'); }

6. Redirecting Guest Users

if (to.meta.guestOnly && isLoggedIn()) return '/dashboard';

7. Handling 404 in Guards

if (!exists(to.params.id)) return { name: 'NotFound' };

8. Analytics Tracking

router.afterEach(to => { gtag('config', 'ID', { page_path: to.path }); });

9. Language Switcher Guard

if (!supportedLangs.includes(to.params.lang)) return `/en${to.path}`;

10. Scroll to Top

router.afterEach(() => { window.scrollTo(0, 0); });

Visual

The Navigation Lifecycle

      START NAVIGATION
             │
    ┌────────▼────────┐
    │ beforeRouteLeave│ (Old Component)
    └────────┬────────┘
             │
    ┌────────▼────────┐
    │   beforeEach    │ (Global Checkpoint)
    └────────┬────────┘
             │
    ┌────────▼────────┐
    │beforeRouteUpdate│ (Reused Component)
    └────────┬────────┘
             │
    ┌────────▼────────┐
    │   beforeEnter   │ (Route Level)
    └────────┬────────┘
             │
    ┌────────▼────────┐
    │  beforeResolve  │ (Final Global Check)
    └────────┬────────┘
             │
      CONFIRM / RENDER
             │
    ┌────────▼────────┐
    │   afterEach     │ (Side Effects)
    └─────────────────┘

The Modern Guard Logic

┌───────────────────────────────────────────────────────────┐
│ GUARD FUNCTION                                            │
│                                                           │
│ RETURN VALUE? ───► false   ───► ABORT (Stay Put)          │
│                │                                          │
│                ───► object ───► REDIRECT (New Nav)        │
│                │                                          │
│                ───► true   ───► CONTINUE (Next Guard)     │
└───────────────────────────────────────────────────────────┘

Auth Flow Sequence

┌──────────┐      ┌──────────┐      ┌──────────────┐
│  USER    │ ───► │ PROTECTED│ ───► │ beforeEach   │
│  CLICKS  │      │ ROUTE    │      │ (Check Meta) │
└──────────┘      └──────────┘      └──────┬───────┘
                                           │
                    ┌──────────────────────┴───────┐
                    │                              │
             LOGGED IN? (YES)               LOGGED IN? (NO)
                    │                              │
             ┌──────▼──────┐               ┌───────▼──────┐
             │ ALLOW NAV   │               │ REDIRECT TO  │
             │ (Return true)│               │ /LOGIN       │
             └─────────────┘               └──────────────┘

Summary

ItemValue
Primary GuardbeforeEach
Final ConfirmbeforeResolve
Side EffectsafterEach
Component ContextbeforeRouteLeave, beforeRouteUpdate
Abort Navreturn false
Redirect Navreturn { name: 'Path' }
Async SupportNative async/await
Legacy APInext() (Discouraged)

Key takeaways:

  • Navigation guards are essential for security. They ensure that users are authenticated and authorized before components are ever instantiated, saving resources and protecting data .
  • Global guards handle cross-cutting concerns. Use beforeEach for authentication and afterEach for non-blocking tasks like analytics or UI updates .
  • Modern syntax is return-based. Avoid the next callback to prevent infinite hangs and logical errors; return a boolean to allow/block or a route object to redirect .
  • Guards are asynchronous. You can perform API calls or database checks within a guard by using async/await, and the router will wait for the result .
  • In-component guards protect state. Use beforeRouteLeave to prevent data loss in forms and beforeRouteUpdate to react to parameter changes when a component is reused .
  • Order matters. Understanding the sequence from beforeRouteLeave to afterEach is crucial for debugging complex navigation flows and data-fetching dependencies .

Remember: Navigation guards are the “bouncers” of your application. Use them to verify identity at the door (beforeEach), check tickets at the section (beforeEnter), and make sure no one leaves with the silver (beforeRouteLeave).

Vue Router Navigation Guards, beforeEach, beforeResolve, beforeRouteLeave, Vue Router Authentication Logic, Navigation Lifecycle Hooks, Vue Router Redirect Syntax, In-Component Guards, Per-Route Guards, Route Meta Fields Security, Global Navigation Guards, beforeRouteUpdate, Async Route Guards, Vue 3 Router Guards, Navigation Guard Execution Order, Protecting Routes Vue Router, Client-Side Security Vue, Router Navigation Interception, Unsaved Changes Guard Vue, Next Callback vs Return Value.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!