Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 32 ยท Pages and routing

Navigation and route middleware

Move between pages with NuxtLink, navigateTo and useRouter, then guard routes with named, inline and global middleware, auth redirects and abortNavigation.

A site is more than a set of pages: people move between them, and some pages should only open under certain conditions. A visitor who is not signed in should not see the account page. A draft should not be reachable before it is published. Nuxt gives you two tools for this. Navigation helpers (<NuxtLink>, navigateTo() and useRouter()) move the visitor. Route middleware runs a small function before a navigation finishes and decides whether to let it through, redirect it or stop it.

The real Nuxt code in this lesson is read-only, because the sandbox on this site has no Nuxt build and no server. To see how the idea works inside, the examples include runnable stand-ins: a tiny middleware runner written in plain JavaScript that follows the same rules. Each time, the lesson says which part is real Nuxt and which part is the stand-in.

Three ways to navigate

NuxtLink In templates. Renders a real anchor.
navigateTo In scripts and middleware.
useRouter Low-level push, replace, back.

Prefer NuxtLink in markup and navigateTo in code.

1 / 2

Moving the visitor

In a template, use <NuxtLink>. It renders a normal <a href>, so search engines and middle-click work, and it performs client-side navigation without a full page reload. See File-based routing for how it prefetches linked pages.

VUE
<template>
  <NuxtLink to="/blog">Blog</NuxtLink>
  <NuxtLink :to="{ name: 'blog-slug', params: { slug: 'hello' } }">First post</NuxtLink>
</template>

In a script, call navigateTo(). It is a Nuxt function (auto-imported, see Auto-imports) that works on the server and in the browser:

TypeScript
// real Nuxt code, read-only
await navigateTo('/pricing')
await navigateTo('/login', { replace: true })        // replaces the history entry
await navigateTo('/old', { redirectCode: 301 })      // permanent redirect on the server
await navigateTo('https://example.com', { external: true })

The two environments behave differently, and that is the main thing to understand. On the server, during the first request, navigateTo makes Nuxt answer with an HTTP redirect (302 by default), so the browser never receives the original page. In the browser, it asks the router to change the route. When you call it in a plain function, await it or return it, so that the next step does not run before the navigation has been set up.

useRouter() gives you the underlying Vue Router instance. You need it less often, mostly for history control:

TypeScript
const router = useRouter()
router.back()                 // one step back in history
router.push('/search?q=nuxt') // like navigateTo, but client-only semantics
router.replace('/home')

A rule of thumb: use navigateTo by default, because it does the right thing in middleware and during server rendering. Reach for useRouter() when you need back(), go(), or hooks like router.beforeEach.

What route middleware is

Route middleware is a function that Nuxt calls before it completes a navigation to a page. It receives the destination (to) and the route you are leaving (from). It decides what happens by what it returns:

Return value Effect
nothing (undefined) Continue to the next middleware, then to the page.
navigateTo('/login') Redirect the navigation.
abortNavigation() Stop the navigation; the visitor stays where they were.
abortNavigation(error) Stop and show an error page (for example, a 403).

You create middleware with defineNuxtRouteMiddleware. It lives in the app/middleware/ folder (see Project structure).

TypeScript
// app/middleware/auth.ts  (real Nuxt code, read-only)
export default defineNuxtRouteMiddleware((to, from) => {
  const user = useState('user')
  if (!user.value) {
    return navigateTo('/login?next=' + encodeURIComponent(to.fullPath))
  }
})

The file name is the middleware name: this one is called auth. A page opts in with definePageMeta:

VUE
<script setup lang="ts">
definePageMeta({ middleware: 'auth' })
// several: middleware: ['auth', 'admin']
</script>

Three flavors

Named middleware is a file in app/middleware/ that pages list by name, as above. It is the best choice when several pages share a rule.

Inline middleware is an anonymous function inside definePageMeta. Use it for a rule that belongs to a single page:

VUE
<script setup lang="ts">
definePageMeta({
  middleware: [
    function (to, from) {
      if (to.query.preview !== 'yes') {
        return abortNavigation('Preview links only')
      }
    },
  ],
})
</script>

Global middleware is a file whose name ends in .global, such as app/middleware/analytics.global.ts. It runs on every navigation, before any page-specific middleware. Global files run in alphabetical order, so some teams prefix the name with numbers (01.auth.global.ts) when order matters. Keep global middleware cheap, because it runs on every single navigation.

The order of execution

For a navigation to /admin, with a global log.global.ts and a page that lists ['auth', 'admin'], the order is: global middleware (alphabetical), then the page's array from left to right. The first middleware that returns a redirect or an abort ends the chain. Later ones do not run for that navigation, and a redirect starts a brand-new navigation to the new target, which runs its own chain from the beginning.

flowchart TD
  A["Navigate to /admin"] --> G["Global middleware<br/>(alphabetical)"]
  G --> N1["Page middleware: auth"]
  N1 --> N2["Page middleware: admin"]
  N2 --> P["Render the page"]
  N1 -- "navigateTo('/login')" --> R["New navigation to /login"]
  N2 -- "abortNavigation()" --> S["Stay on the current page"]

A middleware can let the chain continue, redirect to a new navigation, or stop it.

A runnable stand-in for the chain

Below is a plain JavaScript model of this process. The real parts are the rules: to and from, returning nothing to continue, navigateTo to redirect, abortNavigation to stop, and global-before-page ordering. The stand-in parts are the runner itself (Nuxt's real one lives inside Vue Router) and the session object, which stands in for useState('user').

Run it and read the trace. Notice that /account redirects to the login page while signed out, and that a member who reaches /admin is aborted by the second guard.

JS A middleware chain with redirect and abort

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Redirect loops and the first request

The most common middleware bug is a redirect loop. A guard that sends every signed-out visitor to /login also guards /login itself if it is global, so the visitor is sent to /login, which is sent to /login, forever. The router stops after a number of redirects and you see an error instead of a page. The fix is to exempt the target:

TypeScript
// app/middleware/auth.global.ts (real Nuxt code, read-only)
export default defineNuxtRouteMiddleware((to) => {
  const user = useState('user')
  if (to.path === '/login') {
    return
  }
  if (!user.value) {
    return navigateTo('/login')
  }
})

The stand-in below reproduces the bug and the fix with a hop limit, so you can see the trace of a loop without freezing a browser.

JS A redirect loop, and the fix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Client or server?

Middleware runs in two places. On the first request to your site, it runs on the server, as part of rendering the page. After the page has loaded and hydrated, every later navigation happens in the browser, and middleware runs there instead. The same function must therefore work in both. Three consequences follow:

  • Do not touch window or localStorage in middleware that runs on the server. If you need to branch, use import.meta.server and import.meta.client.
  • Read the sign-in state from something both sides can see, such as a cookie with useCookie (see State with useState and Pinia) or a server session, not from browser-only storage.
  • A server-side redirect is a real HTTP redirect, which is what search engines and non-JavaScript clients need.

Also remember that client-side checks are not security. Anyone can edit code that runs in their own browser. Middleware decides what the interface shows; your API routes must check permissions again (see Forms, validation and auth flows).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a route middleware do when it returns nothing?

    Returning undefined means the middleware has no objection. Nuxt runs the next middleware in the chain and finally renders the page.
  2. 2. In which order does Nuxt run middleware for one navigation?

    Global files run first, in alphabetical order, then the middleware listed in definePageMeta from left to right. The first redirect or abort stops the chain.
  3. 3. Why is await navigateTo('/login') inside a plain function a good habit?

    navigateTo returns a value or promise that Nuxt acts on. Awaiting or returning it makes sure nothing continues as if the navigation had not happened.
  4. 4. A global guard sends every signed-out visitor to /login, and visitors now see a 'too many redirects' error. What is the likely cause?

    The guard runs for the login page too, redirects to the login page again, and loops. Return early when to.path is the login route.
  5. 5. Why must an admin API still check permissions even when route middleware guards the admin page?

    Middleware shapes what the interface shows. Requests can be sent without using your pages at all, so server routes must verify the user.

Summary

  • Use <NuxtLink> in templates and navigateTo() in code; useRouter() covers history control such as back().
  • On the server, navigateTo produces an HTTP redirect; in the browser it changes the route.
  • Route middleware receives to and from; returning nothing continues, navigateTo redirects, abortNavigation stops.
  • Named middleware is opted into with definePageMeta, inline middleware lives in the page, and .global files run on every navigation, before page middleware.
  • Exempt the redirect target from your guard to avoid loops, and never rely on client-side guards for security.

Next: Data fetching with useFetch and useAsyncData