Vue.jsApril 2, 2026

Vue Router Navigation Guards Explained

Master Vue Router navigation guards for authentication and route protection.

Vue Router Navigation Guards Explained

Navigation guards allow you to control navigation in your Vue application. Let’s explore all types of guards.

Global Guards

js
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return { name: 'login' }
  }
})

router.afterEach((to, from) => {
  sendAnalytics(to.fullPath)
})

Per-Route Guards

js
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    beforeEnter: (to, from) => {
      if (!hasPermission()) {
        return '/unauthorized'
      }
    }
  }
]

In-Component Guards

vue
<script setup>
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

onBeforeRouteLeave((to, from) => {
  if (hasUnsavedChanges.value) {
    return confirm('Discard changes?')
  }
})

onBeforeRouteUpdate((to, from) => {
  // Fetch new data when route params change
  fetchData(to.params.id)
})
</script>

Route Meta Fields

js
{
  path: '/admin',
  meta: { requiresAuth: true, roles: ['admin'] },
  component: AdminPanel
}

Navigation Resolution Flow

  1. beforeRouteLeave (component)
  2. beforeEach (global)
  3. beforeEnter (route)
  4. beforeRouteEnter (component)
  5. afterEach (global)