← Articles

Redirecting logged-out users with a Nuxt route middleware

How do you redirect logged-out users before they reach a Nuxt page?

With a route middleware.

A route middleware is a function called before each navigation. It lets you redirect the user before they reach the page. It's the equivalent of a navigation guard in Vue Router.

What a middleware receives and returns

The route middleware receives the destination route (to) and the origin route (from):

A middleware defined with defineNuxtRouteMiddleware that redirects to /login when the "token" cookie is missing

What it returns decides what happens next:

  • nothing: navigation continues;
  • navigateTo('/login'): a redirect, which becomes a real HTTP redirect when it happens server-side;
  • abortNavigation(): navigation is stopped, optionally with an error.

The three kinds of middleware

There are three kinds of middleware, depending on where you declare them:

  • inline: directly in definePageMeta, applied to a single page;
  • named: a file in middleware/ (for example auth.ts), enabled page by page with definePageMeta({ middleware: ['auth'] }) from the page itself;
  • global: a file with the .global suffix (for example middleware/analytics.global.ts), run on every route change. Useful for analytics, for example.

In what order do they run?

When there are several middleware:

  1. Global middleware run first, in alphabetical order of their file names, which is why prefixes like 01., 02. are useful.
  2. Then named middleware, in the order of the array.
  3. Finally, inline middleware.