Skip to content

Navigation Guards

Guards run before/during/after navigation for auth and confirmations. This lesson covers practical patterns, syntax, and mistakes to avoid.

Protecting Navigation

Guards run before/during/after navigation for auth and confirmations.

Global beforeEach is common for auth redirects.

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

Redirect guests away from private meta routes.

Types

global, per-route, in-component
  • Prefer Composition API + script setup.
  • Use computed for derived UI.
  • Keep side effects intentional.
  • Practice in a small Vite app.

Navigation Guards Cheatsheet

Quick reference for patterns covered in this lesson.

Item Example Purpose
beforeEach global Auth
meta flags Config
return false cancel Guard
return route redirect Guard
afterEach analytics Hook
onBeforeRouteLeave dirty forms Component

Common Mistakes

  • Infinite redirect loops.
  • Heavy async work in every navigation without caching auth.

Key Takeaways

  • Navigation Guards is important in Vue apps.
  • Practice in SFCs.
  • Prefer clear naming.
  • Check Vue docs for details.

Pro Tip

Store intended URL in query to return after login.