Instead of usage sanctum:auth and sanctum:guest on each page,
you can enable global middleware that checks every route and restricts unauthenticated access.
The behavior of this middleware is the same as global middleware in Nuxt applications.
sanctum:auth and sanctum:guest on your pages.To enable middleware, use the following configuration in your nuxt.config.ts
export default defineNuxtConfig({
modules: [
'nuxt-auth-sanctum'
],
sanctum: {
baseUrl: 'http://localhost:80',
redirect: {
onAuthOnly: '/login',
onGuestOnly: '/profile',
},
globalMiddleware: {
enabled: true,
},
}
})
Keep in mind, you must define onAuthOnly and onGuestOnly routes to help the plugin understand
which page should be excluded from the middleware.
onAuthOnly - this route is used to redirect unauthenticated users to let them log in, similar to sanctum:auth middlewareonGuestOnly - this route is used to redirect already authenticated users, similar to sanctum:guest middlewareglobalMiddleware.prepend to true to load it before any other middleware.If you want to exclude an additional page besides onAuthOnly route,
then you can define page metadata like in the example below:
definePageMeta({
sanctum: {
excluded: true,
}
})
This page will not be checked by global middleware regardless of user authentication status.
Sometimes, you may have more than one page which are available only for unauthenticated users, for instance:
In these situations, you can use sanctum.guestOnly property of the page meta:
definePageMeta({
sanctum: {
guestOnly: true,
}
})
sanctum.excluded to speed up the loading process.By default, when a user requests a non-existing route an error page will be thrown with 404 status,
but you can also enable redirect to onAuthOnly instead by setting allow404WithoutAuth to false.
export default defineNuxtConfig({
modules: [
'nuxt-auth-sanctum',
],
sanctum: {
baseUrl: 'http://localhost:80',
redirect: {
onAuthOnly: '/login',
onGuestOnly: '/profile',
},
globalMiddleware: {
enabled: true,
allow404WithoutAuth: false,
},
}
})