I've been looking to use Nuxt middleware in layout. But I'm not sure if it is possible, but, since I used it inNuxt 2, it might be possible inNuxt 3.
The project has 2 different layouts:Public.vueandAdmin.vue. I only want to use the middleware in pages usingManage 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
Middleware | adminAuth.ts
export default defineNuxtRouteMiddleware((to, from) => { console.log(to); console.log("Acessando o admin auth middleware"); })
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
.globalsuffix after the middleware file name, such asauth.global.ts.In the
auth.global.tsfile, 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
you can not. Middleware only works on pages.
Instead, create a parent Page component using the auth middleware and the
NuxtPagecomponent inside the template. For more information onNested Routing, see the Nuxt 3 documentation.Example:
/pages/admin.vue(Route =>/admin)
// you can add auth based components as well
sssccc/pages/admin(folder)
admin/order.vue routing =>/admin/orders
admin/page.vue route =>/admin/some-route