Navigation Guards

Allow, Redirect, or Cancel — Before Routing

Navigation Guards

Guards run before navigation happens. Return true to allow, false to cancel, or a route target to redirect — globally, per-route, or per-component.

5 min read Level 3/5 #vue#router#guards
What you'll learn
  • Use beforeEach for global guards
  • Use per-route beforeEnter
  • Use onBeforeRouteLeave inside components

Guards let you gate navigation. They can run for the whole app, for a single route, or inside a component — and they can allow, cancel, or redirect.

Global Guards

router.beforeEach runs before every navigation.

import { router } from './router'
import { useAuthStore } from './stores/auth'

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

Return values:

  • true (or undefined) — allow
  • false — cancel
  • A route location ('/login' or { name: 'login' }) — redirect

Per-Route Guards

Use beforeEnter when only one route needs the check.

const adminGuard = (to) => isAdmin() ? true : '/forbidden'

{ path: '/admin', component: Admin, beforeEnter: adminGuard }

In-Component Guards

onBeforeRouteLeave is great for “unsaved changes” prompts.

import { onBeforeRouteLeave } from 'vue-router'

const unsaved = ref(false)

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

onBeforeRouteUpdate runs when the same component is reused with new params — perfect for guard logic tied to param changes.

Lazy-Loaded Routes →