Home  >  Q&A  >  body text

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

I've been looking to use Nuxt middleware in layout. But I'm not sure if it is possible, but, since I used it in Nuxt 2, it might 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 using Manage Layout. Because the page using it can only be accessed by logged in users and the check is done inside the middleware.

I tried this (doesn't work):

Manage layout|Manage.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");
})


P粉619896145P粉619896145328 days ago675

reply all(2)I'll reply

  • P粉609866533

    P粉6098665332023-10-27 11:44:26

    Middleware cannot be used in layout because middleware can only be used in pages, but you can try this method.

    Create global middleware by declaring the .global suffix after the middleware file name, such as auth.global.ts.

    In the auth.global.ts file, you can use layout metas as logic to simulate as if the middleware was in your layout settings.

    The example logic is like this

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

    Hope this helps

    reply
    0
  • P粉478445671

    P粉4784456712023-10-27 00:20:45

    you can not. Middleware only works on pages.

    Instead, create a parent Page component using the auth middleware and the NuxtPage component inside the template. For more information on Nested Routing, see the Nuxt 3 documentation.

    Example:

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

    
    
    sssccc

    /pages/admin(folder)

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

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

    reply
    0
  • Cancelreply