| | |

Nuxt 04 ๐Ÿ’š File-Based Routing โ€” Static, Dynamic, and Catch-all Routes

โฑ๏ธ Estimated read: 13 min | |

Routing is the backbone of any web application, defining how users navigate between different views and how URLs map to specific content. In many frameworks, routing requires a manual configuration file where every path is explicitly mapped to a component. Nuxt simplifies this process entirely through “File-Based Routing.” By leveraging the structure of your file system, Nuxt automatically generates a high-performance router configuration using Vue Router under the hood.

The core of this system is the pages/ directory. Every .vue file placed inside this folder becomes a reachable URL in your application. For example, pages/about.vue automatically becomes the /about route. This convention-over-configuration approach not only speeds up development but also ensures that your project structure remains organized and predictable, even as it scales to hundreds of routes.

This chapter explores the various types of routing Nuxt supports, from simple static pages to complex dynamic structures and catch-all “404” style routes. We will also examine the essential navigation components provided by the frameworkโ€”NuxtPage and NuxtLinkโ€”and how to utilize Nuxt’s modern “Typed Routing” feature to catch broken links at build time.

By the end of this chapter, you will understand how to architect a complex navigation system that handles dynamic data, nested layouts, and edge-case URLs, all while maintaining the performance benefits of automatic code-splitting and prefetching.

Key point: Nuxt uses the file system as the source of truth for routing; any file in the pages/ directory is automatically transformed into a route, with square-bracket syntax enabling dynamic parameters and catch-all patterns.


Why exists

The Manual Mapping problem

In traditional Vue applications, you must maintain a router.js or routes.ts file. As the app grows, this file becomes a bottleneck, prone to merge conflicts and human error. Nuxt exists to eliminate this file entirely. By using the folder structure as the map, there is zero configuration required to add a new page, making the development workflow significantly more fluid.

The Code-Splitting trade-off

Performance is often compromised when a single large “routing bundle” is sent to the client. Nuxt addresses this by automatically code-splitting every route. Because Nuxt knows exactly which file corresponds to which URL, it only loads the JavaScript necessary for the current page. This ensures that the initial load remains fast, regardless of the total number of pages in the application.

The Dynamic URL problem

Modern applications frequently need to display content based on IDs or slugs (e.g., /products/123). Manually writing regex patterns for these URLs is tedious. Nuxt provides a standardized naming convention using square brackets, allowing developers to define dynamic segments directly in the file name. This makes it immediately obvious to any developer looking at the folder structure which routes are dynamic.

The Prefetching problem

Slow navigation between pages can make a web app feel sluggish. Nuxt includes the NuxtLink component, which automatically observes links as they enter the browser’s viewport. When a link becomes visible, Nuxt “prefetches” the code for that page in the background. By the time the user clicks the link, the destination page is already loaded, making the transition feel instantaneous.

The Link Integrity problem

In large projects, it is easy to accidentally link to a page that doesn’t exist or has been renamed. Nuxtโ€™s “Typed Routing” feature exists to solve this. By generating TypeScript definitions based on your pages/ directory, Nuxt can provide autocomplete for URLs and throw a build-time error if you attempt to navigate to an invalid path.


a. Static and Nested Routing

Static routing is the most straightforward part of the Nuxt system. The index.vue file is a special name that represents the root of a directory.

  • pages/index.vue โ†’ /
  • pages/about.vue โ†’ /about
  • pages/contact/index.vue โ†’ /contact

Nuxt also supports nested routing, which allows you to display a UI inside another UI. This is achieved by creating a folder and a file with the same name. For example, if you have pages/parent.vue and a folder pages/parent/child.vue, Nuxt will look for a <NuxtPage /> component inside parent.vue to render the contents of child.vue.

<!-- pages/parent.vue -->
<template>
  <div>
    <h1>Parent Layout</h1>
    <!-- The child page will be rendered here -->
    <NuxtPage />
  </div>
</template>

This is particularly useful for dashboards or settings pages where a sidebar remains constant while the main content area changes based on the sub-route.


b. Dynamic and Catch-all Routes

When you need a route to handle variable data, such as a user profile or a blog post, you use square brackets in the filename. This creates a “Dynamic Route.”

  • pages/users/[id].vue โ†’ /users/1, /users/abc

Inside the component, you can access the dynamic value using the useRoute() composable. This allows you to fetch the specific data associated with that ID from an API.

<script setup>
const route = useRoute();
// route.params.id will contain the value from the URL
const userId = route.params.id;
</script>

For even more complex scenarios, Nuxt offers Catch-all routes using the [...slug].vue syntax. This is often used for documentation sites or CMS-driven pages where the depth of the URL is unknown. If a user visits /docs/getting-started/installation, the slug parameter will be an array: ['getting-started', 'installation'].

Finally, Optional Dynamic Routes use double square brackets: pages/list/[[filter]].vue. This file will match both /list (where filter is undefined) and /list/active.


c. Navigation and Typed Routing

Navigation in Nuxt should almost always be done using the <NuxtLink> component instead of standard <a> tags. NuxtLink provides the intelligent prefetching mentioned earlier and ensures that navigation happens within the Vue application context (preventing full page reloads).

<template>
  <nav>
    <NuxtLink to="/">Home</NuxtLink>
    <NuxtLink :to="`/users/${userId}`">Profile</NuxtLink>
  </nav>
</template>

For programmatic navigation (e.g., redirecting after a form submission), Nuxt provides the navigateTo() function. This function is preferred over the standard router because it is SSR-compatible, meaning it can handle redirects correctly on both the server and the client.

To enable Typed Routing, you modify your nuxt.config.ts. Once enabled, the to prop on NuxtLink and the arguments for navigateTo become type-checked.

// nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    typedPages: true
  }
})

With this enabled, if you try to navigate to to="/producs" (a typo for /products), TypeScript will underline the error in your IDE, significantly reducing runtime 404 errors.


Complete Example Session

# ============================================
# PART 1: PROJECT SETUP
# ============================================
# Assume we have a fresh Nuxt project.
# Routing starts the moment we create the pages directory.
mkdir pages
<!-- PART 2: THE HOMEPAGE -->
<!-- File: pages/index.vue -->
<template>
  <div>
    <h1>Welcome to the Shop</h1>
    <NuxtLink to="/products">View Products</NuxtLink>
  </div>
</template>
<!-- PART 3: THE PRODUCT LIST -->
<!-- File: pages/products/index.vue -->
<template>
  <div>
    <h2>Our Items</h2>
    <ul>
      <li><NuxtLink to="/products/1">Gadget A</NuxtLink></li>
      <li><NuxtLink to="/products/2">Gadget B</NuxtLink></li>
    </ul>
  </div>
</template>
<!-- PART 4: THE DYNAMIC PRODUCT DETAIL -->
<!-- File: pages/products/[id].vue -->
<script setup>
const route = useRoute();
const id = route.params.id;
</script>
<template>
  <div>
    <h3>Showing Product: {{ id }}</h3>
    <NuxtLink to="/products">Back to List</NuxtLink>
  </div>
</template>
<!-- PART 5: OPTIONAL FILTERS -->
<!-- File: pages/products/search/[[query]].vue -->
<script setup>
const route = useRoute();
const query = route.params.query || 'All Products';
</script>
<template>
  <p>Search Result for: {{ query }}</p>
</template>
<!-- PART 6: CATCH-ALL ROUTE (404/Content) -->
<!-- File: pages/[...slug].vue -->
<template>
  <div>
    <h1>404 - Page Not Found</h1>
    <p>The path "{{ $route.params.slug.join('/') }}" does not exist.</p>
    <NuxtLink to="/">Return Home</NuxtLink>
  </div>
</template>
<!-- PART 7: NESTED ROUTE STRUCTURE -->
<!-- File: pages/dashboard.vue -->
<template>
  <div class="dashboard">
    <aside>Navigation Sidebar</aside>
    <NuxtPage /> <!-- Child routes render here -->
  </div>
</template>
<!-- PART 8: THE NESTED CHILD -->
<!-- File: pages/dashboard/settings.vue -->
<template>
  <section>Dashboard > Settings</section>
</template>
// PART 9: PROGRAMMATIC NAVIGATION
// Inside a component script
const submitForm = async () => {
  const success = await save();
  if (success) {
    await navigateTo('/dashboard/settings');
  }
}
// PART 10: CONFIGURING TYPED PAGES
// File: nuxt.config.ts
export default defineNuxtConfig({
  experimental: { typedPages: true }
});

The steps above cover the entire spectrum of Nuxt routing: from basic static pages to dynamic IDs, optional segments, catch-alls, nested parent-child relationships, and programmatic navigation.


Quick Reference

File Naming Patterns

File StructureURL PathType
pages/index.vue/Static (Root)
pages/blog.vue/blogStatic
pages/post/[id].vue/post/123Dynamic
pages/user/[[name]].vue/user or /user/bobOptional Dynamic
pages/[...slug].vue/any/path/hereCatch-all

Navigation Tools

ToolUsageContext
<NuxtLink><NuxtLink to="/path">Template (Preferred)
navigateTo()navigateTo('/path')Script (Redirects)
useRoute()const route = useRoute()Access current URL state
useRouter()const router = useRouter()Direct router access

Route Object Properties

PropertyDescriptionExample (/shop/1?sort=asc)
route.pathThe path string/shop/1
route.paramsDynamic segments{ id: '1' }
route.queryQuery parameters{ sort: 'asc' }
route.fullPathPath + Query/shop/1?sort=asc

Best Practices

โœ… Do This:

<!-- Use NuxtLink for internal navigation -->
<NuxtLink to="/about">About</NuxtLink>                       <!-- โœ… -->

<!-- Use index.vue for directory roots -->
<!-- pages/contact/index.vue -->                               <!-- โœ… -->

<!-- Use navigateTo for logic-based redirects -->
<script setup>
const go = () => navigateTo('/home');                         // โœ…
</script>

<!-- Enable experimental typedPages in large projects -->
<!-- nuxt.config.ts -> typedPages: true -->                    // โœ…

<!-- Use square brackets for IDs or Slugs -->
<!-- pages/post/[slug].vue -->                                 // โœ…

โŒ Don’t Do This:

<!-- Don't use standard <a> tags for internal links -->
<a href="/about">About</a>                                   <!-- โŒ -->

<!-- Don't manually import Vue Router to navigate -->
<script setup>
router.push('/home'); // Use navigateTo instead                // โŒ
</script>

<!-- Don't name dynamic files with generic names -->
<!-- pages/[id].vue (Better: pages/user/[id].vue) -->           <!-- โŒ -->

<!-- Don't forget to include <NuxtPage /> in app.vue -->
<template><NuxtPage /></template>                            <!-- โŒ (Missing) -->

Common Pitfalls

PitfallWhy It HappensFix
404 on valid fileFolder name case sensitivity or missing pages/ dir.Ensure the folder is named pages (lowercase).
Params missingTrying to access route.params in app.vue.app.vue is outside the page scope; use params inside pages/.
Full page reloadUsed <a> instead of <NuxtLink>.Replace with <NuxtLink>.
Child page not showingMissing <NuxtPage /> in the parent .vue file.Add <NuxtPage /> to the parent component template.
Catch-all priority[...slug].vue is intercepting other routes.Nuxt prioritizes static routes; check for conflicting names.

Real-World Examples

1. Blog Post by Slug

pages/blog/[slug].vue

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

2. Product Search with Category

pages/shop/[category]/[id].vue

<p>Cat: {{ $route.params.category }}, ID: {{ $route.params.id }}</p>

3. User Settings (Nested)

pages/settings.vue (Parent) and pages/settings/profile.vue (Child)

4. Documentation Catch-all

pages/docs/[...slug].vue (Matches any depth under /docs)

5. Optional Filter

pages/archive/[[year]].vue (Matches /archive and /archive/2023)

6. Redirecting Unauthenticated Users

if (!user) return navigateTo('/login');

7. External Link with NuxtLink

<NuxtLink to="https://google.com" external>Google</NuxtLink>

8. Replacing Current History Entry

navigateTo('/new-path', { replace: true });

9. Active Link Styling

<NuxtLink to="/" active-class="text-green-500">Home</NuxtLink>

10. Navigating via Route Name

navigateTo({ name: 'products-id', params: { id: 123 } });

Visual

Directory to URL Mapping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   FILE SYSTEM (pages/)    โ”‚      โ”‚    BROWSER (URL Path)     โ”‚
โ”‚                           โ”‚      โ”‚                           โ”‚
โ”‚  index.vue โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ–บ /                          โ”‚
โ”‚  about.vue โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ–บ /about                     โ”‚
โ”‚  users/                   โ”‚      โ”‚                           โ”‚
โ”‚   โ”œโ”€โ”€ index.vue โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ–บ /users                     โ”‚
โ”‚   โ””โ”€โ”€ [id].vue โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ–บ /users/123                 โ”‚
โ”‚  docs/                    โ”‚      โ”‚                           โ”‚
โ”‚   โ””โ”€โ”€ [...slug].vue โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ–บ /docs/a/b/c                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Nested Routing Components

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  app.vue                                                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚ pages/dashboard.vue (Parent)                          โ”‚  โ”‚
โ”‚  โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚  โ”‚
โ”‚  โ”‚ โ”‚ <NuxtPage /> renders: pages/dashboard/stats.vue  โ”‚  โ”‚  โ”‚
โ”‚  โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Navigation Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ NuxtLink  โ”‚ โ”€โ”€โ”€โ”€โ–บโ”‚ Viewport Check โ”‚ โ”€โ”€โ”€โ”€โ–บโ”‚ Prefetch JS โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
      โ”‚                                           โ”‚
      โ”‚ User Clicks                               โ”‚
      โ–ผ                                           โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Navigationโ”‚ โ—„โ”€โ”€โ”€โ”€โ”‚ Already Loaded!โ”‚ โ—„โ”€โ”€โ”€โ”€โ”‚ Fast Render โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Routing ModeFile-Based (Directory structure)
Dynamic SyntaxSquare brackets [id]
Root Fileindex.vue
NavigationNuxtLink (Prefetching enabled)
Logic NavnavigateTo() (SSR safe)
Nested RoutesRequires <NuxtPage /> in parent
ParametersAccessed via useRoute().params
Code SplittingAutomatic per route

Key takeaways:

  • The file system is your router. Nuxt interprets the pages/ directory to create paths, saving you from writing manual configuration files.
  • Dynamic routing is declarative. Using [id].vue or [...slug].vue allows you to handle variable data and complex URL structures with zero regex.
  • Prefetching is automatic. Using NuxtLink makes your application feel significantly faster by loading page code before the user even clicks.
  • Typed routing catches errors early. By enabling typedPages, you turn URL strings into type-safe paths that TypeScript can validate.
  • Nested routes enable complex layouts. Creating a directory and a file with the same name allows you to preserve UI state while navigating sub-views.
  • SSR-safe navigation. Using navigateTo() ensures that redirects work correctly whether they happen on the server initial load or during client-side interaction.

Remember: If your application doesn’t need multiple pages, you don’t need a pages/ directory. But the moment you create it, Nuxt swaps into “Router Mode,” and you must include <NuxtPage /> in your app.vue to see your content.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!