Vue3 Fundamentals ยท Nuxt & Server-Side Rendering

File-based routing

file-based routing

File-based routing

A Nuxt app does not declare its routes in a config file. It reads them from the filesystem: every file in the pages/ directory becomes a route.

A file's path maps to its URL. pages/index.vue serves /, and pages/about.vue serves /about. A nested folder adds a URL segment, so pages/blog/index.vue serves /blog. Rename a file and the route moves with it.

<!-- pages/about.vue -->
<template>
  <h1>About</h1>
</template>

Dynamic segments use square brackets. pages/users/[id].vue matches /users/1 and /users/2, and the matched value is available through useRoute().params:

<script setup>
const route = useRoute();
const id = route.params.id;
</script>

Nuxt renders the matched page where you place the <NuxtPage /> component, usually in app.vue. Navigate between pages with <NuxtLink to="/about">, which performs a client-side transition instead of a full page load.

Because the route is the file's path, you can read the structure of the site by reading the pages/ directory. Adding a page is adding a file; there is no route table to keep in sync.

You are about to answer a short quiz on file-based routing.

  1. In Nuxt, every file in the `pages/` directory becomes a route.
  2. `pages/index.vue` serves the ___ route.
  3. A nested folder inside `pages/` adds a URL segment.
  4. A dynamic segment is written with ___ brackets, as in `pages/users/[id].vue`.
  5. `useRoute().params` holds the values matched from a dynamic segment.
  6. Navigate between pages with the ___ component, which performs a client-side transition.