Nuxt 04 ๐ File-Based Routing โ Static, Dynamic, and Catch-all Routes
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โ/aboutpages/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 Structure | URL Path | Type |
|---|---|---|
pages/index.vue | / | Static (Root) |
pages/blog.vue | /blog | Static |
pages/post/[id].vue | /post/123 | Dynamic |
pages/user/[[name]].vue | /user or /user/bob | Optional Dynamic |
pages/[...slug].vue | /any/path/here | Catch-all |
Navigation Tools
| Tool | Usage | Context |
|---|---|---|
<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
| Property | Description | Example (/shop/1?sort=asc) |
|---|---|---|
route.path | The path string | /shop/1 |
route.params | Dynamic segments | { id: '1' } |
route.query | Query parameters | { sort: 'asc' } |
route.fullPath | Path + 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| 404 on valid file | Folder name case sensitivity or missing pages/ dir. | Ensure the folder is named pages (lowercase). |
| Params missing | Trying to access route.params in app.vue. | app.vue is outside the page scope; use params inside pages/. |
| Full page reload | Used <a> instead of <NuxtLink>. | Replace with <NuxtLink>. |
| Child page not showing | Missing <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
| Item | Value |
|---|---|
| Routing Mode | File-Based (Directory structure) |
| Dynamic Syntax | Square brackets [id] |
| Root File | index.vue |
| Navigation | NuxtLink (Prefetching enabled) |
| Logic Nav | navigateTo() (SSR safe) |
| Nested Routes | Requires <NuxtPage /> in parent |
| Parameters | Accessed via useRoute().params |
| Code Splitting | Automatic 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].vueor[...slug].vueallows you to handle variable data and complex URL structures with zero regex. - Prefetching is automatic. Using
NuxtLinkmakes 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.
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!