--- name: routing description: File-based routing, dynamic routes, navigation, and middleware in Nuxt --- # Routing Nuxt uses file-system routing based on vue-router. Files in `app/pages/` automatically create routes. ## Basic Routing ``` pages/ ├── index.vue → / ├── about.vue → /about └── posts/ ├── index.vue → /posts └── [id].vue → /posts/:id ``` ## Dynamic Routes Use brackets for dynamic segments: ``` pages/ ├── users/ │ └── [id].vue → /users/:id ├── posts/ │ └── [...slug].vue → /posts/* (catch-all) └── [[optional]].vue → /:optional? (optional param) ``` Access route parameters: ```vue ``` ## Navigation ### NuxtLink Component ```vue ``` NuxtLink automatically prefetches linked pages when they enter the viewport. ### Programmatic Navigation ```vue ``` ## Route Middleware ### Named Middleware ```ts // middleware/auth.ts export default defineNuxtRouteMiddleware((to, from) => { const isAuthenticated = false // Your auth logic if (!isAuthenticated) { return navigateTo('/login') } }) ``` Apply to pages: ```vue ``` ### Global Middleware Name files with `.global` suffix: ```ts // middleware/logging.global.ts export default defineNuxtRouteMiddleware((to, from) => { console.log('Navigating to:', to.path) }) ``` ### Inline Middleware ```vue ``` ## Page Meta Configure page-level options: ```vue ``` ## Route Validation ```vue ``` ## Layouts Define layouts in `app/layouts/`: ```vue ``` ```vue ``` Use in pages: ```vue ``` Dynamic layout: ```vue ``` ### Passing Props to Layouts (Nuxt 4.4+) Use the object syntax for `layout` to pass typed props to the layout component: ```vue ``` ```vue ``` Props are fully typed from the layout's `defineProps`. Also works dynamically: `setPageLayout('panel', { sidebar: true })`. ## Named Views A route can render into multiple `` outlets. Add named view files with the `name@view.vue` convention next to the default route file: ``` pages/ ├── parent.vue └── parent/ ├── child.vue → default └── child@sidebar.vue → ``` ```vue ``` `definePageMeta` is read from the default route file only. ## Navigation Hooks ```vue ```