NUXT 3: How to use routing middleware in layout? (Can I?)
P粉619896145
P粉619896145 2023-10-26 12:57:37
0
2
665

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粉619896145
P粉619896145

reply all(2)
P粉609866533

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

P粉478445671

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!