Navigation guards

Intermediate · 15 min

Allowing, cancelling, or redirecting navigations with Vue Router's global, per-route, and in-component guards, route meta, and the full resolution order.

Before thisVue Router fundamentalsAsync components and Suspense

DotNetMastery · 57 min · from 41:18

Navigation guards

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DotNetMasteryReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A navigation guard is a function the router calls with `(to, from)` before committing a navigation; what it returns decides the outcome: nothing or `true` continues, `false` cancels, a route location redirects.
  • Guards can be `async`, and the navigation stays pending until every guard's Promise settles, so it is safe to `await` an auth check before deciding.
  • The third `next` argument is deprecated since Vue Router 5.0.3: replace `next()` with no return, `next(false)` with `return false`, and `next('/login')` with `return '/login'`.
  • Put flags like `requiresAuth` in route `meta` and check `to.meta` in one global `router.beforeEach`; `to.meta` merges the meta of every matched record, parent to child, so a flag on a parent covers its children.
  • `beforeEnter` on a route record runs only when entering that route from a different one, not on param, query, or hash changes; in `<script setup>`, `onBeforeRouteLeave` and `onBeforeRouteUpdate` are the in-component guards.
  • Guards are UX, not security: anything they hide can still be requested from the API directly, so the server must enforce the same rules.

The checkpoint between click and render

So far every navigation has gone through unconditionally: click a link, the URL changes, the new component renders. Real apps need a say in that. A logged-out visitor shouldn’t land on /account. A half-finished form shouldn’t vanish because someone brushed the Back button. An analytics event should fire once the new page is actually on screen, not before.

Vue Router models each navigation as a short pipeline and lets you hook functions into it. These are navigation guards. Think of airport security between check-in and the gate. Every passenger passes through, most go straight on, some get sent back, and some get redirected to a different desk. The guard doesn’t fly the plane. It decides who gets on.

Global guards and what they return

The most common guard is global, registered on the router:

// src/router/index.js
router.beforeEach((to, from) => {
  // to:   the route being entered
  // from: the route being left
})

Every guard receives two normalized route locations, to and from, with the same path, params, query, name, and meta fields you read from useRoute(). Its return value decides what happens:

  • Nothing, undefined, or true — the navigation is allowed, and the next guard runs.
  • false — the navigation is cancelled. If the browser URL already changed (the user pressed Back), it is reset to from.
  • A route location — a string like '/login' or an object like { name: 'login', query: { redirect: to.fullPath } }. The current navigation is dropped and a new one starts there, exactly as if you had called router.push with it.
  • A thrown error — cancels the navigation and reaches any handler registered with router.onError().

Guards can be async. The navigation stays pending until every guard’s Promise has settled:

router.beforeEach(async (to) => {
  if (to.meta.requiresAuth) {
    const ok = await session.verify() // e.g. refresh a token
    if (!ok) return { name: 'login', query: { redirect: to.fullPath } }
  }
})

Global beforeEach guards run in the order they were registered. router.beforeEach also returns a function that removes the guard, useful in tests.

The next argument you will still see

Older code, including many Vue 3 tutorials, writes guards with a third parameter:

// legacy style
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) next('/login')
  else next()
})

It works, but it was error-prone. You had to call next exactly once on every code path. Call it twice and you get errors; forget it and the navigation hangs forever. Vue Router 4 introduced return values to replace it, and since Vue Router 5.0.3, using next logs a deprecation warning in development. It’s slated for removal in the next major.

The translation is mechanical:

legacy current
next() return (or return nothing)
next(false) return false
next('/login') / next({ name: 'login' }) return '/login' / return { name: 'login' }

Delete the next parameter itself as well. As long as a guard declares a third parameter, the router waits for it to be called, even if the guard returns a value.

Route meta: describe the rule once

Hard-coding paths in a guard (if (to.path.startsWith('/admin'))) doesn’t scale. Instead, attach data to route records with meta, and write one guard that reads it:

const routes = [
  { path: '/login', name: 'login', component: LoginView },
  {
    path: '/account',
    component: AccountLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'account', component: AccountOverview },
      { path: 'billing', name: 'billing', component: BillingView, meta: { title: 'Billing' } },
    ],
  },
]
import { useAuthStore } from '@/stores/auth'

router.beforeEach((to) => {
  const auth = useAuthStore()
  if (to.meta.requiresAuth && !auth.isLoggedIn) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
})

to.meta merges the meta of every matched record, parent first. So /account/billing sees both requiresAuth: true from the parent and title: 'Billing' from the child — one flag on the parent protects the whole section. The requiresAuth check also keeps the guard from redirecting /login to itself. Without it, an unauthenticated user would bounce between login and login forever.

Calling a Pinia store inside a guard works because guards run after app.use(pinia). Since Vue 3.3, inject() works inside global guards too, so anything you app.provide() is reachable there.

After hooks and resolve guards

Two more global hooks sit at the ends of the pipeline:

// runs after every in-component guard and async route component has resolved,
// right before the navigation is confirmed
router.beforeResolve(async (to) => {
  if (to.meta.requiresCamera) {
    try {
      await askForCameraPermission()
    } catch {
      return false
    }
  }
})

// runs after the navigation is confirmed; cannot change it
router.afterEach((to, from, failure) => {
  if (!failure) {
    document.title = to.meta.title ? `${to.meta.title} · Acme` : 'Acme'
    analytics.page(to.fullPath)
  }
})

beforeResolve is the last moment to say no, so it suits work you’d rather not do unless the user is definitely getting in. afterEach is for side effects: page titles, analytics, focus management for screen readers. Its third argument is a navigation failure if the navigation was blocked or redirected. router.push() resolves to that same failure value, so code that awaits a push can detect it with isNavigationFailure(result).

Per-route guards

A guard can live on a single route record:

{
  path: '/projects/:id/settings',
  component: ProjectSettings,
  beforeEnter: [requireLogin, requireProjectOwner], // one function or an array
}

beforeEnter only runs when entering the route from a different one. Moving from /projects/1/settings to /projects/2/settings changes only a param, so beforeEnter is skipped. On a parent route, it doesn’t run when moving between that parent’s children. That’s correct for “may you enter this section at all” and wrong for per-id permission checks — use a global guard or onBeforeRouteUpdate for those. The component-less parent from nested routes is a tidy place to hang one beforeEnter over a whole section.

In-component guards

Some rules belong to a component rather than a route. In <script setup> there are two composables:

<!-- EditPost.vue -->
<script setup>
import { ref } from 'vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

const dirty = ref(false)

onBeforeRouteLeave(() => {
  if (dirty.value && !window.confirm('Discard unsaved changes?')) {
    return false
  }
})

onBeforeRouteUpdate(async (to, from) => {
  if (to.params.id !== from.params.id) {
    post.value = await fetchPost(to.params.id)
  }
})
</script>

onBeforeRouteLeave runs when the route that rendered this component is about to be left. That’s the standard home for unsaved-changes prompts. onBeforeRouteUpdate runs when the route changes but this instance is reused, the param-change case from dynamic routes, and unlike a watch it can cancel the change. Both accept the same return values as global guards.

There’s no Composition API version of the Options API’s beforeRouteEnter. It runs before the component exists, so there’s no setup context to register it from. To load data before a page shows, use a global or per-route guard, or the router’s experimental data loaders.

The full order

Every navigation runs its guards in a fixed sequence:

  1. Navigation triggered.
  2. beforeRouteLeave / onBeforeRouteLeave in components being deactivated.
  3. Global beforeEach.
  4. beforeRouteUpdate / onBeforeRouteUpdate in reused components.
  5. beforeEnter on route records being entered.
  6. Lazy route components (() => import(...)) are resolved.
  7. beforeRouteEnter in components being activated.
  8. Global beforeResolve.
  9. Navigation confirmed.
  10. Global afterEach.
  11. DOM updates.

Step 6 is where the async component knowledge pays off. Route-level code splitting is resolved inside the navigation, so a slow chunk download keeps the navigation pending rather than flashing an empty page. It also means a guard in step 3 can reject a user before their browser downloads the page’s code at all.

One rule outranks all of this: guards are not security. They run in the user’s browser and can be bypassed by anyone who opens the devtools or calls your API directly. Use them to give honest users a smooth experience, and enforce access on the server. The frontend roadmap’s authentication patterns lesson covers where tokens live.

What the video covers

The embed is the “Navigation guards” chapter (41:18 to 55:49) of DotNetMastery’s 2025 Vue 3 routing course. The course’s published code uses the current return-value style throughout: a global beforeEach that returns true or { name: 'login' }, and a per-route beforeEnter given an array of small guard functions, one of which redirects to a “no access” page by returning a route location. There is no third next argument to translate. Route meta, beforeResolve, navigation failures, and the full resolution order are this lesson’s own material. For a minimal, current-style example, the first “go deeper” video protects a /profile route by returning '/login' from beforeEach.

Check yourself

  1. 01A global guard redirects unauthenticated users with `if (!auth.isLoggedIn) return { name: 'login' }`, and the navigation never lands while the console warns about a possibly infinite redirection. Why, and how do you fix it?

    The guard runs for every navigation, including the redirect to `login` itself. Because the user is still not logged in, it redirects to `login` again, forever. Only redirect when the target actually needs auth — check `to.meta.requiresAuth`, or at least `to.name !== 'login'` — so the login route is allowed through.

  2. 02How would you rewrite `router.beforeEach((to, from, next) => { if (to.meta.admin && !isAdmin()) next('/'); else next() })` without `next`?

    `router.beforeEach((to) => { if (to.meta.admin && !isAdmin()) return '/' })`. Returning a location redirects, returning nothing lets the navigation continue. The `next` parameter must be removed entirely, because a guard that declares it is expected to call it.

  3. 03You put `beforeEnter` on `/users/:id` to check access, but going from `/users/1` to `/users/2` skips the check. Is that a bug?

    No. `beforeEnter` only runs when entering the route from a different route; a change of params, query, or hash on the same route reuses it without calling `beforeEnter`. To check every param change, use a global `beforeEach` (checking `to.params`) or `onBeforeRouteUpdate` inside the component.

  4. 04Which guard hook would you use to warn a user about unsaved form changes, and what does it return to keep them on the page?

    `onBeforeRouteLeave` inside the form component. It runs when the route that rendered the component is about to be left; if `window.confirm` (or your own dialog) says the user wants to stay, return `false` to cancel the navigation.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark