Vue3 Fundamentals ยท Nuxt & Server-Side Rendering

Route middleware

route middleware

Route middleware

Some pages should not render for every visitor. An admin page needs a signed-in user; a settings page may need a feature flag. Nuxt lets you run code before a route is entered with route middleware.

A middleware is a file in the middleware/ directory that exports a function using defineNuxtRouteMiddleware. It receives the route being entered (to) and the route being left (from):

// middleware/auth.js
export default defineNuxtRouteMiddleware((to) => {
  if (!isLoggedIn()) {
    return navigateTo('/login');
  }
});

Returning navigateTo('/login') redirects before the page renders, so the protected component never mounts.

Attach a named middleware to a page with definePageMeta:

<script setup>
definePageMeta({ middleware: 'auth' });
</script>

A file whose name ends in .global runs on every route with no per-page registration. Middleware runs on the server for the first request and in the browser for later client-side navigation, so the same guard protects both.

You are about to answer a short quiz on route middleware.

  1. Route middleware runs before the target route is entered.
  2. A middleware file exports a function wrapped in ___.
  3. Returning `navigateTo('/login')` from middleware redirects before the page renders.
  4. Attach a named middleware to a page with ___.
  5. A middleware file whose name ends in `.global` runs on every route.
  6. Middleware runs on the server for the first request and in the ___ for later navigation.