vue.jsnuxt.jsnuxt3.js

NUXT 3: How to use route middleware in a layout? (Can I?)


I've been looking to use Nuxt middleware in a layout. But I am not sure if I even can, however, since I used it in Nuxt 2, it may be possible in Nuxt 3.

The project has 2 different layouts: Public.vue and Admin.vue. I only want to use the middleware in pages that consume the Admin layout. Because the pages that use it should be accessed only by logged-in users, and it will be checked inside the middleware.

I tried this (doesn't work):

Admin layout | Admin.vue

<template>
  <div>
    <client-only>
      <admin-header />
    </client-only>
    <main>
      <slot />
    </main>
    <client-only>
      <admin-footer />
    </client-only>
  </div>
</template>

<script lang="ts">
import AdminHeader from "~~/components/admin/Header.vue"
import AdminFooter from "~~/components/admin/Footer.vue"

definePageMeta({
  middleware: "admin-auth"
});
</script>

Middleware | adminAuth.ts

export default defineNuxtRouteMiddleware((to, from) => {
    console.log(to);
    console.log("Acessando o admin auth middleware");
})

Solution

  • You cant. Middleware only works for pages.

    Instead, make a parent Page component with the auth middleware and NuxtPage component inside the template. See the Nuxt 3 docs for more information on nested routes.

    Example:

    /pages/admin.vue (route => /admin)

    <template>
      // you can add auth based components as well
      <NuxtPage />
    </template>
    
    <script setup lang="ts">
      definePageMeta({
         middleware: "admin-auth"
      });
    </script>
    

    /pages/admin (folder)

    All other components inside admin folder will use your auth middleware

    admin/order.vue route => /admin/orders

    admin/page.vue route => /admin/some-route