Vue Router Navigation Guards

Vue Router Navigation Guards

Navigation guards allow you to redirect or cancel navigation — perfect for authentication checks and unsaved-changes warnings.

Global Guard — beforeEach

// src/router/index.js
router.beforeEach((to, from) => {
  const isAuthenticated = !!localStorage.getItem('token')

  if (to.meta.requiresAuth && !isAuthenticated) {
    return { name: 'login' } // redirect
  }
})

Route-Level Guard

const routes = [
  {
    path: '/dashboard',
    component: DashboardView,
    meta: { requiresAuth: true },
    beforeEnter: (to, from) => {
      if (!hasPermission(to.meta.permission)) {
        return { name: 'forbidden' }
      }
    },
  },
]

In-Component Guard with onBeforeRouteLeave

import { onBeforeRouteLeave } from 'vue-router'

const isDirty = ref(false)

onBeforeRouteLeave((to, from) => {
  if (isDirty.value) {
    const ok = window.confirm('You have unsaved changes. Leave anyway?')
    if (!ok) return false // cancel navigation
  }
})