Vue Router navigation guards are functions that run while the router moves from one page to another, and they can let the move happen, cancel it or send the user somewhere else. That makes them the place for sign-in checks, role checks, "you have unsaved changes" prompts and page titles. This post covers the three kinds of guards with working examples for each, the order they run in, and the mistakes that cause redirect loops. The code is TypeScript, checked against Vue Router 5.4 and the official guide; the guard API is the one Vue Router 4 has too.
Using Nuxt? It wraps these guards in route middleware, covered in Nuxt route middleware. Everything below is for a Vue app with its own router, including a Quasar CLI app.
| Kind | Where | Runs for | Good for |
|---|---|---|---|
| Global | router.beforeEach, beforeResolve, afterEach | Every navigation | Auth, roles, titles, analytics |
| Per-route | beforeEnter in a route record | Entering that route | Rules for one route or section |
| In-component | onBeforeRouteLeave, onBeforeRouteUpdate | The component on screen | Unsaved changes, reloading on param change |
Every guard except afterEach decides with its return value, and it can be async:
true: carry on.false: cancel. If the URL already changed (the back button), it's reset.'/login' or { name: 'login' }): cancel this navigation and start a new one there.router.onError() handler.You'll still see a third next argument in older code. It's supported for backward compatibility, but it must be called exactly once on every path, and forgetting it hangs the navigation. Return values avoid that whole class of bug, so the examples here don't use next.
Mark the routes that need a signed-in user with meta, and check it in one global guard. First, type the meta fields, so to.meta.requiresAuth isn't unknown:
// router/meta.ts
import 'vue-router'
export {}
declare module 'vue-router' {
interface RouteMeta {
requiresAuth?: boolean
roles?: string[]
title?: string
}
}Then the routes. meta on a parent applies to its children, because to.meta is a merge of every matched record's meta, parent first:
// router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/login', name: 'login', component: () => import('../pages/LoginPage.vue') },
{
path: '/app',
meta: { requiresAuth: true },
children: [
{ path: '', name: 'dashboard', component: () => import('../pages/DashboardPage.vue'), meta: { title: 'Dashboard' } },
{ path: 'billing', name: 'billing', component: () => import('../pages/BillingPage.vue'), meta: { roles: ['owner', 'admin'], title: 'Billing' } },
],
},
],
})And the guard:
router.beforeEach(async (to) => {
if (!to.meta.requiresAuth) return
await loadSession()
if (!currentUser.value) {
return { name: 'login', query: { redirect: to.fullPath } }
}
const roles = to.meta.roles
if (roles && !roles.some(role => currentUser.value!.roles.includes(role))) {
return { name: 'dashboard' }
}
})loadSession() asks the server who's signed in, once, and stores the answer in currentUser. Because the guard awaits it, the first navigation waits for the answer instead of flashing the login page at a signed-in user:
// auth/session.ts
import { ref } from 'vue'
interface User { id: string; name: string; roles: string[] }
export const currentUser = ref<User | null>(null)
let sessionChecked = false
export async function loadSession() {
if (sessionChecked) return
sessionChecked = true
const response = await fetch('/api/session')
currentUser.value = response.ok ? await response.json() : null
}A few things this guard gets right on purpose:
requiresAuth, so redirecting there can't trigger the guard again. Forgetting that is the classic infinite redirect.redirect keeps the full path, query and hash included, so the login page can send the user back. When the login page reads it, accept only paths that start with a single /, or an attacker can craft a login link that redirects to another site.If your session lives in a Pinia store, you can use the store inside beforeEach: since Vue 3.3, inject() works in global guards, which the Vue Router guide points out makes stores and other app.provide() values available there.
beforeEnter sits on one route record and takes a function or an array of functions, which makes small reusable guards easy:
import type { RouteLocationNormalized } from 'vue-router'
function removeQueryParams(to: RouteLocationNormalized) {
if (Object.keys(to.query).length) {
return { path: to.path, query: {}, hash: to.hash }
}
}
function removeHash(to: RouteLocationNormalized) {
if (to.hash) return { path: to.path, query: to.query, hash: '' }
}
const invoiceRoute = {
path: 'invoices/:id',
name: 'invoice',
component: () => import('../pages/InvoicePage.vue'),
beforeEnter: [removeQueryParams, removeHash],
}Know when it doesn't run: beforeEnter fires only when entering the route from a different route. Going from /app/invoices/1 to /app/invoices/2, or changing only the query or hash, doesn't trigger it. On a parent route it also doesn't fire when moving between its children. For checks that must run on every change, use beforeEach with a meta field, or onBeforeRouteUpdate in the component.
onBeforeRouteLeave runs when the user is about to leave the component's route. Return false and they stay. This version asks with Quasar's Dialog plugin instead of window.confirm, wrapping its callbacks in a promise the guard can await:
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
import { useQuasar } from 'quasar'
const $q = useQuasar()
const saved = ref({ customer: 'Ana Lima', notes: '' })
const form = reactive({ ...saved.value })
const isDirty = computed(() => JSON.stringify(form) !== JSON.stringify(saved.value))
function confirmDiscard() {
return new Promise<boolean>((resolve) => {
$q.dialog({
title: 'Discard changes?',
message: 'You have unsaved changes on this invoice.',
ok: { label: 'Discard', color: 'negative', flat: true },
cancel: { label: 'Keep editing', flat: true },
persistent: true,
})
.onOk(() => resolve(true))
.onCancel(() => resolve(false))
})
}
onBeforeRouteLeave(async () => {
if (isDirty.value && !(await confirmDiscard())) return false
})
onBeforeRouteUpdate(async (to, from) => {
if (to.params.id === from.params.id) return
if (isDirty.value && !(await confirmDiscard())) return false
await loadInvoice(String(to.params.id))
})
function warnBeforeUnload(event: BeforeUnloadEvent) {
if (isDirty.value) event.preventDefault()
}
onMounted(() => window.addEventListener('beforeunload', warnBeforeUnload))
onBeforeUnmount(() => window.removeEventListener('beforeunload', warnBeforeUnload))
async function loadInvoice(id: string) {
const invoice = await (await fetch(`/api/invoices/${id}`)).json()
saved.value = invoice
Object.assign(form, invoice)
}
</script>Three guards cover three exits:
onBeforeRouteLeave handles links and the back button inside the app. persistent keeps the dialog from being dismissed by a click outside, so the guard always gets an answer.onBeforeRouteUpdate handles the same component being reused for another invoice, /invoices/1 to /invoices/2. The component isn't left, so the leave guard doesn't fire.beforeunload handles closing the tab or reloading, which the router never sees. The browser shows its own generic message there; you can't customize it.Both composition-API guards work in any component rendered by <router-view>, not only in the route's page component, so a form component deep in the page can protect itself.
afterEach runs after the navigation is decided and can't change it. Its third argument is set when the navigation failed, for example because a guard returned false:
router.afterEach((to, _from, failure) => {
if (failure) return
document.title = to.meta.title ? `${to.meta.title} · Acme` : 'Acme'
})When a guard blocks a navigation, router.push() resolves to the same failure instead of throwing (a redirect counts as a success). isNavigationFailure(failure, NavigationFailureType.aborted) tells you a guard blocked the move, so the caller can, say, keep a menu open.
beforeRouteLeave / onBeforeRouteLeave in the components being leftbeforeEachbeforeRouteUpdate / onBeforeRouteUpdate in reused componentsbeforeEnter in route recordsbeforeRouteEnter in the components being enteredbeforeResolveafterEach, then the DOM updatesThe leave guard runs before beforeEach. So when a signed-out user with unsaved changes clicks a protected link, they're asked about their changes first, and redirected to login only after they agree to leave.
Do navigation guards protect my data? No. They run in the browser and anyone can skip them. Check the session in every API route as well; the guard only decides what the user sees.
Why does my guard redirect forever? It redirects to a route that the same guard redirects again. Return early for the target route, as the requiresAuth check above does.
Should I use beforeEach or beforeResolve to load data? beforeResolve runs after the component guards and lazy components, right before the page changes, so data loaded there is never fetched for a page the user can't enter.
The guards decide who gets into the app. If what's behind them is an admin panel, the QuasarUI Templates are four complete Quasar admin dashboards with light and dark screens, including reports, task management and kanban pages, each delivered as a private GitHub repo. Open the live previews to see the pages before you write your own.