I understand you're having issues with nested routing and middleware in Nuxt, specifically with protecting routes based on user roles.
The issue you're facing is that middleware applied to the parent index.vue file doesn't automatically apply to all child routes in the folder. Let's solve this problem.
Solution: Global Middleware for Role-Based Access
You have a few options to protect all routes in a folder:
Option 1: Create a global middleware
Create a global middleware file that checks user roles and restricts access accordingly:
export default defineNuxtRouteMiddleware((to) => {
const userRole = getUserRole()
if (to.path.startsWith('/Investor') && userRole === 'guest') {
return navigateTo('/login')
}
if (to.path.startsWith('/admin') && userRole !== 'admin') {
return navigateTo('/')
}
})
Global middleware runs on every route change, so this will protect all your routes Docs > Guide > Directory Structure > Middleware.
Option 2: Apply middleware to each page
You can add the middleware to each page using definePageMeta:
<script setup>
definePageMeta({
middleware: ["auth"]
})
</script>
However, this would be repetitive as you'd need to add it to every page.
Option 3: Set middleware at build time
A more elegant solution is to use the pages:extend hook in your nuxt.config.ts to apply middleware to all pages in specific directories: