app/pages/ directory creates a corresponding URL (or route) that displays the contents of the file.
How File-Based Routing Works
Nuxt routing is based on vue-router and generates routes from every component created in theapp/pages/ directory, based on their filename. By using dynamic imports for each page, Nuxt leverages code-splitting to ship the minimum amount of JavaScript for the requested route.
This file system routing uses naming conventions to create dynamic and nested routes:
Navigation
The<NuxtLink> component links pages between them. It renders an <a> tag with the href attribute set to the route of the page. Once the application is hydrated, page transitions are performed in JavaScript by updating the browser URL, preventing full-page refreshes.
When a <NuxtLink> enters the viewport on the client side, Nuxt automatically prefetches components and payload of the linked pages ahead of time, resulting in faster navigation.
app/pages/index.vue
Route Parameters
You can use theuseRoute() composable in a <script setup> block or a setup() method to access the current route details.
pages/posts/[id].vue
useRoute() composable provides access to route parameters, query strings, and other route metadata.
Route Middleware
Nuxt provides a customizable route middleware framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route.Route middleware runs within the Vue part of your Nuxt app. Despite the similar name, they are completely different from server middleware, which run in the Nitro server part of your app.
- Anonymous (or inline) route middleware - Defined directly in the pages where they are used
- Named route middleware - Placed in the
app/middleware/directory and automatically loaded via asynchronous import when used on a page - Global route middleware - Placed in the
app/middleware/directory with a.globalsuffix and automatically run on every route change
auth middleware protecting the /dashboard page:
Route Validation
Nuxt offers route validation via thevalidate property in definePageMeta() in each page you wish to validate.
The validate property accepts the route as an argument. You can return a boolean value to determine whether this is a valid route to be rendered with this page. If you return false, this will cause a 404 error.
pages/posts/[id].vue
status/statusText to customize the error returned. For more complex use cases, you can use anonymous route middleware instead.