N
Nuxt2mo ago
JuanMCe

use global middleware except in some routes

I want to create a global middleware to redirect users to a certain page if they didn't agree with the terms of service. This is my approach so far:
// terms.global.ts
export default defineNuxtRouteMiddleware((to) => {
const { data: user } = useAuth();
if (
user.value &&
!user.value.accepted_terms_of_service &&
to.name !== 'terms-of-service'
) {
return navigateTo({ name: 'terms-of-service' });
}
return;
});
// terms.global.ts
export default defineNuxtRouteMiddleware((to) => {
const { data: user } = useAuth();
if (
user.value &&
!user.value.accepted_terms_of_service &&
to.name !== 'terms-of-service'
) {
return navigateTo({ name: 'terms-of-service' });
}
return;
});
Is there a way to avoid having to specify the route I don't want to be affected by this middleware?
2 Replies
kapa.ai
kapa.ai2mo ago
Hi @JuanMCe. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- There is no built-in way in Nuxt to automatically exclude specific routes from a global middleware without checking the route inside the middleware itself. The recommended approach is exactly what you are doing: add a condition in your global middleware to skip execution for certain routes (e.g., the terms of service page). The knowledge sources do not mention any configuration or API that allows you to declare route exclusions for global middleware outside of the middleware logic itself. You must handle exclusions by checking the route in your middleware function, as in your example:
export default defineNuxtRouteMiddleware((to) => {
const { data: user } = useAuth();
if (
user.value &&
!user.value.accepted_terms_of_service &&
to.name !== 'terms-of-service'
) {
return navigateTo({ name: 'terms-of-service' });
}
return;
});
export default defineNuxtRouteMiddleware((to) => {
const { data: user } = useAuth();
if (
user.value &&
!user.value.accepted_terms_of_service &&
to.name !== 'terms-of-service'
) {
return navigateTo({ name: 'terms-of-service' });
}
return;
});
This is the standard and recommended way to conditionally apply global middleware in Nuxt Ordering Global Middleware defineNuxtRouteMiddleware. If you want more granular control, you could consider using named middleware and applying it only to the routes you want, but that would not be "global" anymore. For global middleware, route checks inside the middleware are necessary. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@281911171919904778> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?