Go Back To Blogs

Nuxt 4 Middleware and Route Guards: Patterns and Pitfalls

nuxtmiddlewareroute guardsvue
Bright Amoah
Bright Amoah
Frontend Developer

Friday 1st August, 2025

10 minutes mins to read

Share this blog

Nuxt 4 Middleware and Route Guards: Patterns and Pitfalls

Nuxt 4 introduces a new, more flexible middleware and route guard system, but many developers struggle with advanced patterns, especially when using TypeScript. This guide covers everything you need to know to secure and control navigation in your Nuxt 4 apps.

Types of Middleware in Nuxt 4

  • Global Middleware: Runs on every route change.
  • Named Middleware: Can be applied to specific pages or layouts.
  • Per-Page Middleware: Defined directly in a page's <script setup>.

Creating Typed Middleware

Create a middleware in middleware/auth.global.ts:

import { defineNuxtRouteMiddleware, useRuntimeConfig, navigateTo } from "#app";

export default defineNuxtRouteMiddleware((to, from) => {
   const config = useRuntimeConfig();
   const isAuthenticated = Boolean(config.public.auth);
   if (!isAuthenticated && to.path !== "/login") {
      return navigateTo("/login");
   }
});

Using Named Middleware

Apply named middleware in a page:

<script setup lang="ts">
definePageMeta({ middleware: ["auth"] });
</script>

Per-Page Route Guards

You can define guards directly in your page:

<script setup lang="ts">
import { defineNuxtRouteMiddleware, navigateTo } from "#app";

defineNuxtRouteMiddleware((to, from) => {
   if (to.query.preview !== "true") {
      return navigateTo("/not-allowed");
   }
});
</script>

Best Practices

  • Always use TypeScript for middleware and guards.
  • Keep middleware logic simple and composable.
  • Use named middleware for reusability.
  • Avoid side effects in global middleware.
  • Document all guards and their expected behavior.

Wrap-Up

Nuxt 4's middleware and route guard system is powerful but requires discipline for maintainability and security. Use TypeScript and best practices to keep your navigation logic robust. For more, see the Nuxt docs on middleware.