Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
})
like image 324
Angelo Schuler Piletti Avatar asked Jun 04 '26 21:06

Angelo Schuler Piletti


2 Answers

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

like image 53
Mirahmad Mirzajonov Avatar answered Jun 07 '26 23:06

Mirahmad Mirzajonov


It is not possible to use middleware in layout because middleware only can be use in pages, but you can try to use this method.

Create a global middleware by declaring .global suffix after your middleware file name for example auth.global.ts.

In auth.global.ts file you can use layout meta as your logic to simulate as if the middleware is in your layout setup.

Sample logic is like this

export default defineNuxtRouteMiddleware((to, from) => {
    const user = useUserStore();
    
    if (!user && to.meta.layout === auth) {
        return navigateTo("/login");
    }
});

Hope this helps

like image 20
AbuAdam Avatar answered Jun 07 '26 23:06

AbuAdam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!