Colmena now has all its screens, but anyone can go anywhere: a visitor without a session opens /dashboard or /book/nectar, a member sees the whole centre's invoices, and anyone who has filled in half a booking form loses it without warning when they click a menu link. Navigation guards are functions that Vue Router runs at specific moments of each navigation and that can allow it, cancel it or divert it to another route. In this lesson you will get to know the complete journey of a navigation and the place of each guard within it, the global guards (beforeEach, beforeResolve, afterEach), the per-route guards (beforeEnter) and the in-component guards (onBeforeRouteLeave, onBeforeRouteUpdate), and the meta fields used to mark the routes that need protection. In Colmena you will implement sign-in with a LoginView that returns users to the page they asked for, protect the dashboard and the form, restrict the invoices to managers, warn about unsaved changes and give each page a title. And, above all, you will understand why none of this is security.

Contents

  1. The journey of a navigation
  2. Global guards: beforeEach
  3. beforeResolve
  4. afterEach: after navigating
  5. Per-route guards: beforeEnter
  6. In-component guards
  7. meta fields and their inheritance
  8. The sign-in flow
  9. A warning: guards are not security
  10. Case study: protecting Colmena

  1. The journey of a navigation

Every time a navigation happens (a click on a RouterLink, a router.push, the Back button), Vue Router follows a fixed journey. Guards are the points on that journey where your code can intervene:

flowchart TD
    A["1. The navigation starts"] --> B["2. onBeforeRouteLeave<br/>in the components about to be unmounted"]
    B --> C["3. beforeEach<br/>global guards"]
    C --> D["4. onBeforeRouteUpdate<br/>in the components being reused"]
    D --> E["5. beforeEnter<br/>of the routes being entered"]
    E --> F["6. Lazy views are downloaded"]
    F --> G["7. beforeRouteEnter<br/>in the components about to be mounted (Options API only)"]
    G --> H["8. beforeResolve<br/>global guards"]
    H --> I["9. Navigation confirmed: the URL changes"]
    I --> J["10. afterEach<br/>global hooks"]
    J --> K["11. The DOM is updated"]
    K --> L["12. beforeRouteEnter's next() callbacks"]
    B & C & D & E & G & H -.->|"returns false"| X["Navigation cancelled<br/>(aborted failure)"]
    B & C & D & E & G & H -.->|"returns another route"| Y["Navigation redirected:<br/>a new one starts from step 1"]

Key points of the journey:

  • Guards run in order and one at a time. If one is asynchronous, the following ones wait.
  • Until step 9, the navigation has not happened: the URL and the screen are still those of the origin. Any guard from steps 2 to 8 can cancel or divert it.
  • afterEach (step 10) can no longer change anything: the navigation is done. It is used for subsequent effects (titles, analytics).
  • Lazy views are downloaded in step 6, after the global and per-route guards. If a guard cancels the navigation before then, the view's code is not even downloaded.
  • beforeRouteEnter (step 7) only exists in the Options API: it runs before the component is created, so it has no access to this. With <script setup> there is no equivalent; its work is done in beforeEnter or in the view itself.

  1. Global guards: beforeEach

router.beforeEach registers a function that runs before every navigation, whatever its destination. It is the place for rules that affect the whole application, such as requiring a session:

router.beforeEach((to, from) => {
  // to: the destination route; from: the origin route
  if (to.name === 'dashboard-invoices' && !isManager()) {
    return { name: 'dashboard-profile' } // divert
  }
  // return nothing: let it through
})

Both parameters are complete route objects (the same as useRoute()): to.name, to.params, to.query, to.fullPath, to.matched, to.meta... What the guard returns decides what happens:

Returned value Effect
Nothing, undefined or true The navigation continues to the next guard
false It is cancelled. The URL goes back to the origin's and router.push resolves with an aborted failure (04-05)
A location ('/login' or { name: 'login', query: {...} }) It is redirected: the current navigation is abandoned and another one starts towards that location, which goes through all the guards again
Throwing an error (throw) It is cancelled, and the error reaches router.onError and the router.push promise
A promise (an async function) The router waits for it to resolve and uses its value

Guards can be asynchronous, for example to check something with the server:

router.beforeEach(async (to) => {
  if (to.meta.requiresSession) {
    const valid = await checkSessionOnServer()
    if (!valid) return { name: 'login' }
  }
})

While the promise is pending, the origin screen is still visible: if the check is slow, it is a good idea to show some kind of indicator (exercise 1).

Two warnings:

  • Beware of redirect loops. If a guard sends anyone without a session to login, and login also required a session, the redirect would divert to login again indefinitely. Make sure the destination of a redirect does not meet the condition that triggers it.
  • The third parameter, next. In old code (and in Vue Router 3) you will see guards of the form (to, from, next) => { ... next() }. They still work, but you have to call next exactly once on every possible path, and it is easy to get wrong. Return values instead, as in this lesson.

You can register several beforeEach guards; they run in the order in which they were registered. Each registration returns a function for removing it: const remove = router.beforeEach(...); remove().

  1. beforeResolve

router.beforeResolve is registered just like beforeEach and accepts the same return values, but it runs at the end (step 8): after the per-route and in-component guards, and after the lazy views have been downloaded. It is the last moment to cancel, when you already know that everything else has given permission:

router.beforeResolve(async (to) => {
  // Only if the route needs it and all the other guards have let it through
  if (to.meta.requiresCamera) {
    try {
      await navigator.mediaDevices.getUserMedia({ video: true })
    } catch {
      return false // no permission, no entry
    }
  }
})

The example is a typical one: requesting a browser permission or loading essential data only when the navigation is certain to happen, and not before another guard could cancel it. We will not need it in Colmena.

  1. afterEach: after navigating

router.afterEach runs once the navigation has been confirmed (step 10). It cannot change it, so it does not return anything. As well as to and from, it receives a third parameter with the failure, if there was one:

router.afterEach((to, from, failure) => {
  if (failure) return // the navigation never actually happened
  document.title = `${to.meta.title} · Colmena Bookings`
})

It is the place for effects that depend on the final screen: the tab's title, logging page views for analytics, moving the focus to the main content or announcing the page change to screen readers.

  1. Per-route guards: beforeEnter

A guard can be associated with a specific route through the beforeEnter property of its record. It runs only when entering that route from a different one:

{
  path: '/login',
  name: 'login',
  component: LoginView,
  beforeEnter: (to, from) => {
    if (hasSession()) return { name: 'dashboard' } // already signed in: the login makes no sense
  }
}

It also accepts an array of functions, which run in order. It is a clean way of reusing checks across routes:

function checkA(to) { /* ... */ }
function checkB(to) { /* ... */ }

{ path: '/book/:roomId', component: BookingView, beforeEnter: [checkA, checkB] }

An important detail: beforeEnter does not run when only the params, query or hash of the same route change (from /book/panal to /book/polen), because in that case you are not "entering": you were already inside. If the check depends on the params and that case is possible, repeat it in onBeforeRouteUpdate or move it to beforeEach.

  1. In-component guards

A view can register guards that are only active while it is mounted:

Function (vue-router) When it runs Typical use
onBeforeRouteLeave(guard) When leaving the route that renders this component Warning about unsaved changes
onBeforeRouteUpdate(guard) When the route changes but the component is reused (a different param) Loading the new data before showing the change (04-03)

Both receive (to, from), accept the same return values as beforeEach and must be called at the top level of <script setup>. They are removed automatically when the component is unmounted.

import { onBeforeRouteLeave } from 'vue-router'

onBeforeRouteLeave(() => {
  if (hasUnsavedChanges.value) {
    return window.confirm('You have unsaved changes. Do you want to leave?')
    // true: leaves; false: the navigation is cancelled and the user stays
  }
})

In the Options API, the equivalents are the beforeRouteLeave and beforeRouteUpdate options and the beforeRouteEnter option already mentioned.

The router's guards only intervene in navigations within the application. If the user reloads the page, closes the tab or types another address, the browser leaves the SPA without going through Vue Router. For those cases there is the browser's beforeunload event, which we will see in the case study.

  1. meta fields and their inheritance

In 04-04 you used meta for the breadcrumb titles. Its most important use is to mark routes so that a global guard can decide what to do with them, without listing route names in the guard:

{ path: '/book/:roomId', name: 'book', component: BookingView, meta: { requiresSession: true } },
{
  path: '/dashboard',
  component: DashboardView,
  meta: { requiresSession: true }, // on the parent: protects all the children
  children: [
    { path: 'invoices', name: 'dashboard-invoices', component: DashboardInvoicesView, meta: { role: 'manager' } }
  ]
}

In Colmena we will use three fields:

Field Value Meaning
title Text The page title (tab and breadcrumbs)
requiresSession true Only accessible when signed in
role 'manager' Only accessible to that role

How does a child "inherit" its parent's meta? There are two ways of checking it in a guard:

// On /dashboard/invoices
to.matched.map((record) => record.meta)
// → [ { title: 'My dashboard', requiresSession: true }, { title: 'Invoices', role: 'manager' } ]

to.meta
// → { title: 'Invoices', requiresSession: true, role: 'manager' } (merged; the child wins)
  • to.matched.some((record) => record.meta.requiresSession) is the explicit, classic way: "if any level of the chain requires a session". A child cannot override its parent's requirement.
  • to.meta.requiresSession uses the merge, in which a child could override it (meta: { requiresSession: false }).

For protection, we prefer the first: it is safer against an oversight and it makes the intention clear.

  1. The sign-in flow

The usual pattern combines a global guard, a query and a programmatic navigation:

sequenceDiagram
    participant U as User
    participant G as beforeEach
    participant L as LoginView
    participant S as Session module
    U->>G: Navigates to /dashboard/bookings (no session)
    G-->>U: Redirects to /login?redirect=/dashboard/bookings
    U->>L: Types email and password
    L->>S: signIn(email, password)
    S-->>L: Signed in
    L->>G: router.replace('/dashboard/bookings')
    G-->>U: There is a session now: lets it through
  1. The guard detects that the destination requires a session and there is none, and it redirects to the login page, storing the original destination in the query: { name: 'login', query: { redirect: to.fullPath } }.
  2. LoginView signs the user in and navigates to route.query.redirect with replace, so that Back does not return to the login form.
  3. The navigation goes through the guard again, which now lets it through.

One precaution: the value of redirect comes from the URL, and anyone can craft a link with ?redirect= pointing wherever they like. Accept only internal paths (ones that start with / but not with //, which the browser would interpret as another domain).

And its opposite, signing out: clearing the session and, if the current screen requires one, taking the user to a public screen.

  1. A warning: guards are not security

This is the most important idea in the lesson. Guards run in the user's browser, with code that the user has downloaded and can read, modify or bypass with the developer tools. Hiding a screen does not hide its data:

  • The code of DashboardInvoicesView, with its fictitious invoices, is in a .js file that anyone can download from the Network tab, whether or not they have permission to see the screen.
  • With DevTools, anyone can change session.role to 'manager' in memory.
  • API calls can be made without the application, with any HTTP client.

That is why:

Client-side guards are for... Real security lies in...
Guiding the user: not showing screens they cannot use, taking them to the login page The server, which checks identity and permissions on every request
Avoiding errors: not opening a form that the server would reject 401 (no session) and 403 (no permission) responses from the API, which the application must know how to handle
A good experience Never sending the client data that the user must not see

In a real application, the invoicing API would respond 403 to a member, and the invoices screen would have no data to show even if someone bypassed the guard. Never put secrets (passwords, private API keys) in client code. The test accounts we will use in Colmena are in the code only because this is a simulation without a server.

  1. Case study: protecting Colmena

10.1 The session, in a module

Until now, the session lived in App.vue and reached the components through provide/inject. But router.beforeEach is not a component: it is registered in src/router/index.js, outside the tree, and it cannot use inject. We need the session in a place that can be imported from any JavaScript module: the shared state in a module that we introduced (and advised against for large applications) in 03-07.

Create src/session.js:

// src/session.js
// The member's session. TEMPORARY: in module 5 it will move to a store.
import { reactive, readonly } from 'vue'

const STORAGE_KEY = 'colmena-session'

// Fictitious accounts for practising. In a real application, the SERVER does the checking.
const DEMO_MEMBERS = [
  { name: 'Laura Gómez', email: '[email protected]', plan: 'flexible', role: 'member' },
  { name: 'Marta Vidal', email: '[email protected]', plan: 'business', role: 'manager' }
]
const DEMO_PASSWORD = 'colmena'

function createEmptySession() {
  return { active: false, name: '', email: '', plan: 'flexible', role: 'member' }
}

// If the tab already had a session (on reload), it is recovered
function readSavedSession() {
  try {
    const saved = JSON.parse(sessionStorage.getItem(STORAGE_KEY))
    return saved ? { ...createEmptySession(), ...saved, active: true } : createEmptySession()
  } catch {
    return createEmptySession()
  }
}

const state = reactive(readSavedSession())

// To the outside world, read-only: changes go through the functions
export const session = readonly(state)

export async function signIn(email, password) {
  await new Promise((resolve) => setTimeout(resolve, 600)) // simulates the request
  const member = DEMO_MEMBERS.find((m) => m.email === email.trim().toLowerCase())
  if (!member || password !== DEMO_PASSWORD) {
    throw new Error('Incorrect email or password')
  }
  Object.assign(state, member, { active: true })
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(member))
}

export function signOut() {
  Object.assign(state, createEmptySession())
  sessionStorage.removeItem(STORAGE_KEY)
}
  • The session model does not change (name, email, plan, role); active is added. That way, AppHeader, BookingForm, DashboardView and DashboardProfileView keep working without their reads being touched.
  • readonly + functions: the same pattern as in 03-07, now at module level.
  • sessionStorage keeps the session while the tab is open, so that reloading does not end it. We store only the member's details, never the password. (In a real application you would store a token issued by the server or, better still, a cookie that JavaScript cannot read.)
  • signIn is asynchronous and throws an error if the credentials are not valid, as an API call would.

In App.vue, delete the reactive session and toggleRole, and provide what the module exports:

// App.vue
import { session, signOut } from './session.js'

// Replaces the session block: components keep using inject(SESSION_KEY)
provide(SESSION_KEY, { session, signOut })

Why not have the components import session.js directly? They could, but keeping the injection means that no component changes, and that BookingForm can still be used in isolation with its inject default value. The price is that the session now arrives by two paths: imported (in the router) and injected (in the components).

10.2 The meta marks on the routes

In src/router/index.js, add meta to the existing routes (the complete listing is in section 10.9):

Route meta
home { title: 'Home' }
rooms { title: 'Rooms' }
room-detail { title: 'Room details' }
book { title: 'New booking', requiresSession: true }
/dashboard (parent) { title: 'My dashboard', requiresSession: true }
dashboard-invoices { title: 'Invoices', role: 'manager' }
login (new) { title: 'Sign in' }
not-found { title: 'Page not found' }

The dashboard's children do not repeat requiresSession: their parent requires it.

10.3 The global guard

At the end of src/router/index.js, before export default router:

import { session } from '@/session.js' // with the other imports, at the top of the file

router.beforeEach((to) => {
  // 1. Does any level of the route require a session?
  const requiresSession = to.matched.some((record) => record.meta.requiresSession)
  if (requiresSession && !session.active) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }

  // 2. Does it require a specific role?
  const requiredRole = to.meta.role
  if (requiredRole && session.role !== requiredRole) {
    return { name: 'dashboard-profile' }
  }
})
  • to.fullPath includes the query: if someone without a session opens /book/nectar?attendees=4, after signing in they will return to exactly that address.
  • The role is read from to.meta, the merged one: it is enough for the child to declare it.
  • A member who tries to open the invoices goes to their profile. Other reasonable options would be a "no permission" page or the 404 page (which does not reveal that the page exists).
  • There is no risk of a loop: login does not require a session, and dashboard-profile does not require a role.

10.4 LoginView.vue and its per-route guard

Create src/views/LoginView.vue:

<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import TextField from '@/components/base/TextField.vue'
import BaseButton from '@/components/base/BaseButton.vue'
import { signIn } from '@/session.js'

const route = useRoute()
const router = useRouter()

const email = ref('')
const password = ref('')
const error = ref('')
const submitting = ref(false)

// Only internal paths are accepted as a destination
function destinationAfterLogin() {
  const destination = route.query.redirect
  if (typeof destination === 'string' && destination.startsWith('/') && !destination.startsWith('//')) {
    return destination
  }
  return { name: 'dashboard' }
}

async function submit() {
  error.value = ''
  submitting.value = true
  try {
    await signIn(email.value, password.value)
    await router.replace(destinationAfterLogin()) // replace: Back does not return to the login page
  } catch (e) {
    error.value = e.message
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="login">
    <h2>Sign in</h2>
    <p v-if="route.query.redirect" class="note">Sign in to continue.</p>

    <form novalidate @submit.prevent="submit">
      <TextField
        v-model.trim="email"
        type="email"
        label="Email address"
        autocomplete="username"
      />
      <TextField
        v-model="password"
        type="password"
        label="Password"
        autocomplete="current-password"
      />
      <p v-if="error" class="error" role="alert">{{ error }}</p>
      <BaseButton type="submit" :disabled="submitting">
        {{ submitting ? 'Signing in…' : 'Sign in' }}
      </BaseButton>
    </form>

    <p class="hint">
      Test accounts (password "colmena"): [email protected] (member) and
      [email protected] (manager).
    </p>
  </section>
</template>

<style scoped>
.login {
  max-width: 26rem;
  margin: 0 auto;
}

.error {
  color: #b00020;
}

.hint {
  color: #666;
  font-size: 0.9rem;
}
</style>
  • TextField is reused as it is: type and autocomplete reach the <input> thanks to inheritAttrs: false and v-bind="$attrs" (03-05). The values username and current-password allow the browser's password manager to work.
  • role="alert" makes the screen reader announce the error as soon as it appears.
  • submitting disables the button while waiting, to prevent double submissions.

Register the route, with a beforeEnter guard that keeps anyone who is already signed in away from the login page:

{
  path: '/login',
  name: 'login',
  component: () => import('@/views/LoginView.vue'),
  meta: { title: 'Sign in' },
  beforeEnter: () => (session.active ? { name: 'dashboard' } : true)
},

10.5 The header: signing in and out

In AppHeader.vue, the temporary "View as manager/member" button disappears (the role now depends on who signs in). In the script:

import { useRoute, useRouter, isNavigationFailure } from 'vue-router'

const { session, signOut } = inject(SESSION_KEY) // before: { session, toggleRole }
const route = useRoute()
const router = useRouter()

async function onSignOut() {
  // If the current screen requires a session, we leave it first...
  if (route.matched.some((record) => record.meta.requiresSession)) {
    const failure = await router.push({ name: 'home' })
    if (isNavigationFailure(failure)) return // ...and if the user decides to stay, we do not sign out
  }
  signOut()
}
<!-- Replaces the session paragraph and the "View as..." button -->
<template v-if="session.active">
  <p class="header__session">
    {{ session.name }} · {{ session.plan }} plan
    <span v-if="session.role === 'manager'" class="header__role">manager</span>
  </p>
  <BaseButton variant="secondary" @click="onSignOut">Sign out</BaseButton>
</template>
<RouterLink
  v-else-if="route.name !== 'login'"
  :to="{ name: 'login', query: { redirect: route.fullPath } }"
>
  Sign in
</RouterLink>
  • The order in onSignOut matters. If you are on the form with unsaved changes (section 10.7), the navigation may be cancelled; by checking the failure, the session is only ended if you really have left. It is a real use of the navigation failures from 04-05.
  • "Sign in" carries the current page as redirect: after signing in, the user returns to where they were.

In DashboardView.vue, show the invoices link only to managers:

<RouterLink v-if="session.role === 'manager'" :to="{ name: 'dashboard-invoices' }">Invoices</RouterLink>

Hiding the link and protecting the route are different things, and you need both: the hidden link removes the temptation; the guard covers anyone who types the URL by hand.

10.6 beforeEnter on the form: a non-existent room or one under maintenance

The book route has two cases that are not handled today: /book/basement (no such room exists) and /book/enjambre (under maintenance, not accepting bookings). We will deal with them before entering, with an array of per-route guards. In src/router/index.js:

import { rooms } from '@/data/rooms.js'

// The room does not exist: show the 404 while keeping the URL
function checkRoomExists(to) {
  if (!rooms.some((room) => room.id === to.params.roomId)) {
    return {
      name: 'not-found',
      params: { pathMatch: to.path.substring(1).split('/') },
      query: to.query,
      hash: to.hash
    }
  }
}

// The room is not accepting bookings: go to its spec sheet, which explains why
function checkRoomAvailable(to) {
  const room = rooms.find((r) => r.id === to.params.roomId)
  if (!room.available) {
    return { name: 'room-detail', params: { id: room.id } }
  }
}
{
  path: '/book/:roomId([a-z-]+)',
  name: 'book',
  component: () => import('@/views/BookingView.vue'),
  props: bookingProps,
  meta: { title: 'New booking', requiresSession: true },
  beforeEnter: [checkRoomExists, checkRoomAvailable]
},
  • The redirect to not-found with pathMatch is the technique announced in 04-03 for showing the 404 while keeping the URL: by splitting the path into segments and passing them as the catch-all route's repeatable param, the resulting URL is the same one the user asked for (/book/basement), with its query and its anchor, but NotFoundView is rendered.
  • The order of the array matters: checkRoomAvailable can take it for granted that the room exists, because checkRoomExists has already diverted the other cases.
  • The local data is used, because it is synchronous. If the check needed the API, the guard would be async.
  • Remember the limitation from section 5: if the view were reused when moving to another room, these guards would not run again. In Colmena there is no link that leads from one form to another, so it is not a problem.

10.7 Unsaved changes in the form

To warn before leaving, BookingView needs to know whether the form has changes. The form's state is internal to BookingForm, so it will expose it, alongside reset. In BookingForm.vue:

// The fields the user fills in (roomId and status do not count)
const EDITABLE_FIELDS = ['date', 'startTime', 'endTime', 'member', 'attendees', 'extraEquipment', 'notes', 'acceptsRules']

// Does the form differ from a freshly created one?
const hasChanges = computed(() => {
  const empty = createEmptyForm()
  return EDITABLE_FIELDS.some(
    (field) => JSON.stringify(form[field]) !== JSON.stringify(empty[field])
  )
})

// Replaces the previous defineExpose
defineExpose({ reset: resetForm, hasChanges })
  • Comparing with createEmptyForm() respects legitimate initial values: if the user arrived with ?attendees=4, having 4 attendees is not a change.
  • JSON.stringify makes it possible to compare strings, numbers and the extraEquipment array in a single line.
  • When an exposed computed is accessed through a template ref, Vue unwraps it: from outside, hasChanges is simply true or false.

In BookingView.vue:

import { onMounted, onUnmounted } from 'vue' // add them to the existing import
import { useRouter, onBeforeRouteLeave } from 'vue-router'

function hasUnsavedChanges() {
  return bookingForm.value?.hasChanges ?? false
}

// Navigations within the application
onBeforeRouteLeave(() => {
  if (hasUnsavedChanges()) {
    return window.confirm('You have a half-finished booking. If you leave, you will lose the details. Do you want to leave?')
  }
})

// Reloading, closing the tab or leaving for another website: the browser shows its own warning
function warnBeforeUnload(event) {
  if (hasUnsavedChanges()) event.preventDefault()
}
onMounted(() => window.addEventListener('beforeunload', warnBeforeUnload))
onUnmounted(() => window.removeEventListener('beforeunload', warnBeforeUnload))

And when the booking is created, when createBooking navigates to "My bookings"? The guard runs too, but createBooking calls bookingForm.value.reset() before router.push (04-05), so hasChanges is already false and no question is asked. If you reversed the order, the user would see the warning just after booking.

10.8 Each page's title

In src/router/index.js, after the beforeEach guard:

router.afterEach((to, from, failure) => {
  if (failure) return
  document.title = to.meta.title ? `${to.meta.title} · Colmena Bookings` : 'Colmena Bookings'
})

For a room's spec sheet, the generic title "Room details" can be improved once the data arrives. In RoomDetailView.vue:

// Dynamic title: it overwrites afterEach's once the room has been loaded
watch(room, (loadedRoom) => {
  if (loadedRoom) document.title = `${loadedRoom.name} · Colmena Bookings`
})

The order is the right one: afterEach sets the generic title when the navigation is confirmed and, when the request finishes, the view makes it specific. This replaces the watchEffect we deleted from App.vue in 04-02.

10.9 The complete router

This is the final state of src/router/index.js at the end of the module:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import NotFoundView from '@/views/NotFoundView.vue'
import { rooms } from '@/data/rooms.js'
import { session } from '@/session.js'

function bookingProps(route) {
  const attendees = Number(route.query.attendees)
  return {
    roomId: route.params.roomId,
    attendees: Number.isInteger(attendees) && attendees > 0 ? attendees : 1
  }
}

function checkRoomExists(to) { /* section 10.6 */ }
function checkRoomAvailable(to) { /* section 10.6 */ }

const routes = [
  { path: '/', name: 'home', component: HomeView, meta: { title: 'Home' } },
  { path: '/home', redirect: { name: 'home' } },
  {
    path: '/rooms',
    name: 'rooms',
    component: () => import('@/views/RoomsView.vue'),
    alias: '/catalog',
    meta: { title: 'Rooms' }
  },
  {
    path: '/rooms/:id([a-z-]+)',
    name: 'room-detail',
    component: () => import('@/views/RoomDetailView.vue'),
    props: true,
    meta: { title: 'Room details' }
  },
  {
    path: '/book/:roomId([a-z-]+)',
    name: 'book',
    component: () => import('@/views/BookingView.vue'),
    props: bookingProps,
    meta: { title: 'New booking', requiresSession: true },
    beforeEnter: [checkRoomExists, checkRoomAvailable]
  },
  {
    path: '/dashboard',
    component: () => import('@/views/DashboardView.vue'),
    meta: { title: 'My dashboard', requiresSession: true },
    children: [
      { path: '', name: 'dashboard', redirect: { name: 'dashboard-profile' } },
      {
        path: 'profile',
        name: 'dashboard-profile',
        component: () => import('@/views/dashboard/DashboardProfileView.vue'),
        meta: { title: 'Profile' }
      },
      {
        path: 'bookings',
        name: 'dashboard-bookings',
        component: () => import('@/views/dashboard/DashboardBookingsView.vue'),
        meta: { title: 'My bookings' }
      },
      {
        path: 'invoices',
        name: 'dashboard-invoices',
        component: () => import('@/views/dashboard/DashboardInvoicesView.vue'),
        meta: { title: 'Invoices', role: 'manager' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
    meta: { title: 'Sign in' },
    beforeEnter: () => (session.active ? { name: 'dashboard' } : true)
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: NotFoundView,
    meta: { title: 'Page not found' }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition
    if (to.hash) return { el: to.hash, top: 16, behavior: 'smooth' }
    return { top: 0 }
  }
})

router.beforeEach((to) => {
  const requiresSession = to.matched.some((record) => record.meta.requiresSession)
  if (requiresSession && !session.active) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
  const requiredRole = to.meta.role
  if (requiredRole && session.role !== requiredRole) {
    return { name: 'dashboard-profile' }
  }
})

router.afterEach((to, from, failure) => {
  if (failure) return
  document.title = to.meta.title ? `${to.meta.title} · Colmena Bookings` : 'Colmena Bookings'
})

export default router

10.10 Try it

  1. Without a session. Open a new tab on / (with no saved session): the header shows "Sign in". Click "My dashboard": you reach the login page with redirect=/dashboard/profile in the query (the empty child's redirect is applied before the guards) and the notice "Sign in to continue." The browser tab says "Sign in · Colmena Bookings".
  2. Returning to the requested page. Sign in with [email protected] and a wrong password: the error appears. With colmena: you go to /dashboard/profile. Click Back: you do not return to the login page (it was a replace).
  3. With a query. Sign out. From the catalogue, click "Book" with 3 attendees in the Polen Room: you go to the login page; after signing in, you arrive at /book/polen?attendees=3 with everything intact.
  4. Managers only. As Laura (a member), you do not see "Invoices" in the side menu. Type /dashboard/invoices: you end up on the profile. Sign out and sign in as Marta Vidal: the link appears and the screen opens.
  5. Already signed in. Type /login: it takes you to the dashboard.
  6. A non-existent room or one under maintenance. Type /book/basement: you see the 404 and the URL is still /book/basement. Type /book/enjambre: it takes you to the Enjambre Auditorium's spec sheet, which explains that it is under maintenance.
  7. Unsaved changes. In the form, type a note and click "Rooms" in the menu: the confirmation appears. Click "Cancel": you stay on the form with your details (and the URL has not changed). Click "Sign out": it asks too, and if you cancel, the session is not ended. Now reload the page: the browser shows its own warning.
  8. No warning when booking. Complete and submit the booking: you arrive at "My bookings" without any confirmation.
  9. Titles. Navigate around the screens and watch the tab: "Rooms · Colmena Bookings", "My bookings · Colmena Bookings"... On Néctar's spec sheet, the title changes from "Room details" to "Néctar Room" when it loads.
  10. Reloading with a session. While signed in, reload on /dashboard/bookings: you are still inside (the session is in sessionStorage), although the list of bookings is empty (it lives in memory). Open the application in another tab: there is no session there.
  11. What the guard does not protect. As Laura, try to open the invoices and check in the Network tab that DashboardInvoicesView is not downloaded: the guard redirects before step 6. Now run npm run build and open dist/assets/DashboardInvoicesView-[hash].js in an editor: the fictitious invoices are there, readable, and that file is published along with the rest of the application, within reach of anyone who knows its address. This is the demonstration of section 9.

Common Mistakes and Tips

  • Treating guards as security. They are user experience. Permissions are checked on the server, on every request, and data that a user must not see is not sent to them.
  • Creating a redirect loop: the guard sends the user to a route that meets the condition again. Check that the destination of each redirect falls outside the rule.
  • Using next and calling it twice, or not at all. Return values instead.
  • Protecting only the parent with to.meta and having a child override it by mistake. For requirements, use to.matched.some(...).
  • Expecting beforeEnter to run again when the param changes within the same route. It does not; use onBeforeRouteUpdate or beforeEach.
  • Reading the session with inject in a global guard. Global guards are not components: they need an importable module (today, src/session.js; in module 5, a store).
  • Trusting ?redirect= without validating it. Accept only internal paths.
  • Forgetting beforeunload. onBeforeRouteLeave does not cover reloads or closing the tab.
  • Hiding the link without protecting the route, or protecting the route while leaving the link visible. You need both: one for clarity and the other for consistency.
  • Tip: keep guards fast. A slow global guard delays every navigation in the application. If you need data, load it once and keep it.

Exercises

Exercise 1. Add a navigation indicator to Colmena: a thin honey-coloured bar at the top of the page that appears while a navigation is in progress (for example, while a lazy view is downloading on a slow network). Use a ref exported from a src/navigation.js module, the global guards and router.onError, and render the bar in App.vue.

Exercise 2. Replace the login route's beforeEnter with a meta: { guestsOnly: true } field checked in the global guard, and apply it to a new /register route too. What advantage does this approach have over repeating the beforeEnter on every route?

Exercise 3. Laura (a member, signed in) is on /book/nectar with the form half filled in and types router.push('/dashboard/invoices') into the console. List, in order, which of Colmena's guards run, what each one returns (assume she accepts the confirmation) and at which URL she ends up. And what if she cancels the confirmation?

Solutions

Solution 1.

// src/navigation.js
import { ref } from 'vue'

export const navigating = ref(false)
// src/router/index.js
import { navigating } from '@/navigation.js'

// Register it BEFORE the session guard: that way it is activated as soon as any navigation starts
router.beforeEach(() => {
  navigating.value = true
})

// ... session guard ...

router.afterEach(() => {
  navigating.value = false // it also runs on failures (cancellations, duplicates)
})

router.onError(() => {
  navigating.value = false // for example, if downloading a view fails
})
<!-- App.vue -->
<script setup>
import { navigating } from './navigation.js'
// ... the rest unchanged ...
</script>

<template>
  <div v-if="navigating" class="navigation-bar" role="progressbar" aria-label="Loading the page"></div>
  <AppHeader />
  <main class="content"><RouterView /></main>
</template>

<style scoped>
.navigation-bar {
  position: fixed;
  inset: 0 0 auto 0;
  height: 3px;
  background: var(--color-honey-dark);
}
</style>

afterEach also runs when the navigation fails (that is why it receives the failure as its third parameter), so the bar is not left hanging if a guard cancels. If a guard redirects, the original navigation is abandoned, the new one activates the bar again and its afterEach deactivates it. To stop the bar flickering on instant navigations, you could show it only if navigating is still active after 150 ms. Notice that navigating is yet another piece of shared state in a module.

Solution 2.

// In the routes
{ path: '/login', name: 'login', component: () => import('@/views/LoginView.vue'), meta: { title: 'Sign in', guestsOnly: true } },
{ path: '/register', name: 'register', component: () => import('@/views/RegisterView.vue'), meta: { title: 'Create account', guestsOnly: true } },
// In the global guard, as the first check
router.beforeEach((to) => {
  if (to.meta.guestsOnly && session.active) {
    return { name: 'dashboard' }
  }
  // ... requiresSession and role, unchanged ...
})

The rule is written once, and each route only declares what it is (guestsOnly), not how it is checked. Adding a third guest route (password recovery) means adding a mark. Per-route guards are still useful for checks specific to one route, such as the room checks on book.

Solution 3. With the confirmation accepted:

  1. onBeforeRouteLeave in BookingView (it is about to be unmounted): there are changes, so it shows the confirmation; it returns true.
  2. beforeEach: requiresSession (required by /dashboard) is satisfied; to.meta.role is 'manager' and Laura is a member: it returns { name: 'dashboard-profile' }. Redirect: a new navigation towards /dashboard/profile starts.
  3. In the new navigation, onBeforeRouteLeave runs again, because BookingView is still mounted: it asks again. If she accepts, it returns true.
  4. beforeEach: session and role are correct; it returns nothing.
  5. There is no onBeforeRouteUpdate (no component is reused) and no beforeEnter on the dashboard routes. DashboardView and DashboardProfileView are downloaded if they had not been already.
  6. Navigation confirmed: afterEach sets the title "Profile · Colmena Bookings".

She ends up on /dashboard/profile, and the user has seen the confirmation twice: a curious effect of a redirect starting a complete navigation. If she cancels at the first step, the navigation is aborted, Laura stays on /book/nectar with her details and router.push resolves with an aborted failure. (To avoid the double question, the leave guard could remember that the user had already confirmed; or the role guard could run earlier, in an application where it matters.)

Conclusion

Navigation guards let you intervene in the journey of each navigation: onBeforeRouteLeave in the components that are leaving, beforeEach for global rules, onBeforeRouteUpdate in reused components, beforeEnter (a function or an array) for checks specific to a route, beforeResolve as the last checkpoint and afterEach for subsequent effects, such as the title. Each guard lets the navigation through (by returning nothing or true), cancels it (false) or redirects it (by returning another location), and it can be asynchronous. meta fields mark the routes (requiresSession, role, title) and are inherited: with to.matched.some(...), a requirement on the parent protects all its children. You have built the complete sign-in flow with LoginView and ?redirect=, signing out, the protection of /dashboard and /book/:roomId, the managers-only dashboard-invoices route, the warning about unsaved changes and a title for each page. And, above all, you know that all this improves the experience, but real security lies on the server.

With this lesson you complete the Vue Router module, and Colmena Bookings is now a multi-screen application: a home page, a catalogue with its filters in the URL, a spec sheet for each room, a booking form with the room in the route, a personal area with nested routes, sign-in and a 404 page, all with protected navigation. But if you review where the state shared by those screens lives, the picture is worrying: the session is in a module with reactive (src/session.js) that the router imports and that App.vue provides to the components again; the bookings, in a provide from App.vue that is lost on reload; the catalogue is requested from the API again in each view (HomeView, RoomsView, RoomDetailView) because none of them can reuse what another loaded; and formatPrice is still copied into several files. They are temporary solutions, each with its own style, hard to debug (Vue DevTools does not show who changed the session or when a booking was recorded) and they will not scale when the bookings have to be sent to the API or when several screens need to know that a room has just filled up. It is time to centralise that state in a store with a clear structure, debugging tools and rules about how it is modified, starting with the library that popularised the idea in the Vue ecosystem: Introduction to Vuex.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved