Vue and Nuxt Navigation Guards

Jul 14, 2024

Vue and Nuxt Navigation Guards

Overview

  • Navigation/Route Guards: Used to guard navigations by redirecting or canceling the route navigation based on certain conditions.
  • Goal: Ensure users meet conditions (e.g., authentication) before allowing navigation.

Vue Router

  • Global Guard: Registered using beforeEach method.
    • Arguments: to (target route) and from (current route).
    • Example logic: Check if user is authenticated to allow continuing to the route or cancel navigation by returning false.

Nuxt Route Middleware

  • Difference: Uses route middleware instead of beforeEach.

Types of Route Middleware in Nuxt

  1. Inline Middleware
  • Defined directly on the page within the definePageMeta macro and middleware property.
  • Property accepts an array with functions to execute specific logic for particular pages.
  • Example: Check if route has param 123 and use abortNavigation utility if condition is met.
  1. Named Route Middleware
  • Files created in middleware directory, added to pages in the application.
  • Use defineNuxtRouteMiddleware utility to create middleware.
  • Example: Check if user is authenticated using useSupabaseUser composable.
  • Middleware applied to a page using the middleware property in definePageMeta macro (noting normalization to kebab case).
  1. Global Middleware
  • Runs on every route change.
  • File placed in middleware directory with global suffix in the filename.
  • Example: Log route information (to and from params) to the console on every route change.

Middleware Execution Order

  • Order: Global middleware -> Named middleware -> Inline middleware (as defined in the array).
  • Control Execution Order: Prefix global middleware files with alphabetical numbering (e.g., 01, 02).

Server-Side Rendering (SSR)

  • Middleware for the initial page executed on both server and client.
  • Control execution using import.meta.server and import.meta.client to skip running on server or client.

Conclusion

  • Summary: Different types of middleware in Nuxt provide flexibility in guarding routes based on various conditions.
  • Actions: Leave a like and subscribe if found helpful.