Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 32 ยท Pages and routing

Dynamic routes and params

Use square brackets in file names for dynamic Nuxt routes: [id].vue, optional [[slug]], catch-all [...slug], useRoute params, validate and match order.

A blog does not have one file per article. It has one page that shows whichever article the URL names. In Nuxt you express that with square brackets in the file name: pages/blog/[slug].vue handles /blog/hello-nuxt, /blog/second-post and every other single segment. The part inside the brackets is a parameter you can read in the page.

This lesson covers the three bracket forms, reading params with useRoute(), rejecting bad values with validate, how Nuxt decides which file wins when several match, and the one trap that surprises most beginners: the page is reused when only the param changes. It builds on File-based routing.

The three kinds of dynamic segments

File name Matches Example
users/[id].vue exactly one segment /users/42 gives { id: "42" }
users/[[id]].vue zero or one segment (optional) /users/42 gives { id: "42" }; /users gives no id
docs/[...slug].vue any number of segments (catch-all) /docs/a/b gives { slug: ["a", "b"] }

Underneath, these become Vue Router patterns: :id, :id? and :slug(.*)*. Note that:

  • Params are strings, even when they look like numbers. Convert them yourself (Number(route.params.id)).
  • A catch-all gives an array of segments. It is commonly used for documentation trees, CMS paths and a custom 404 page (pages/[...slug].vue).
  • An optional parameter may be missing or empty, so check it before using it.
  • The dynamic part can be a folder too: users/[id]/settings.vue is /users/42/settings.

Three bracket styles

[id] Exactly one segment.
[[id]] Zero or one segment.
[...slug] Any number of segments, as an array.

Brackets in a file name make a parameter.

1 / 2

Reading the param

useRoute() returns the current route, and route.params holds the values:

VUE
<!-- app/pages/blog/[slug].vue (read-only) -->
<script setup lang="ts">
const route = useRoute()
const { data: post } = await useFetch(() => `/api/posts/${route.params.slug}`)
</script>

<template>
  <article v-if="post">
    <h1>{{ post.title }}</h1>
    <p>Slug from the URL: {{ route.params.slug }}</p>
  </article>
</template>

With TypeScript, a param may be typed as a string or an array, so you often add a small cast or check. For a catch-all, join the array yourself when you need a path string: (route.params.slug as string[]).join('/').

Links to dynamic pages can use the route name and a params object instead of building the URL by hand:

VUE
<NuxtLink :to="{ name: 'blog-slug', params: { slug: 'hello-nuxt' } }">Read</NuxtLink>

Which file wins?

Several files can match one URL. With users/new.vue, users/[id].vue and [...slug].vue, the URL /users/new matches all three. Vue Router ranks routes by specificity, comparing the path segment by segment:

  1. Static segments (new) beat
  2. Dynamic segments ([id]), which beat
  3. Optional segments ([[id]]), which beat
  4. Catch-all segments ([...slug]).

So /users/new goes to users/new.vue, /users/42 to users/[id].vue, and /anything/else falls through to the catch-all. The order of the files on disk does not matter. This is what lets you write pages/[...slug].vue as a safe 404 page: it only gets URLs that nothing more specific wants.

The first stand-in is a router matcher with exactly this ranking. It converts file names to patterns, finds every route that matches a URL, and picks the most specific one. It is a model of the rules, not Vue Router's real code, which also handles things like regex params and nesting.

JS A tiny matcher with specificity ranking

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check two lines of the output. /users/new is claimed by users/new.vue, even though users/[id].vue also matches it, and /nope/not/here ends up in the catch-all with slug set to ["nope","not","here"].

Validating params

Not every value is a real value. /users/banana matches users/[id].vue, but you probably expect a number. Do not fetch first and fail later: add a validate function in definePageMeta. It runs before the page renders, and if it returns false, Nuxt shows the 404 page:

VUE
<!-- app/pages/users/[id].vue (read-only) -->
<script setup lang="ts">
definePageMeta({
  validate: async (route) => {
    return /^\d+$/.test(route.params.id as string)
  },
})
</script>

validate may also return an object such as { statusCode: 400, statusMessage: 'Bad id' } to choose the error. Validation on the page is about the URL's shape. Whether user 42 actually exists is the job of the data fetch, which should answer with createError({ statusCode: 404 }) (Data fetching).

The second stand-in shows the pattern: a validator per route, run after matching and before rendering. A failing check produces a 404 result instead of a page.

JS validate before rendering

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The reuse trap

Imagine a user page with a link to "next user". When you navigate from /users/1 to /users/2, both URLs use the same page file, so Vue reuses the same component instance and only route.params.id changes. Code in <script setup> does not run again. A value computed once from the param goes stale:

VUE
<script setup lang="ts">
const route = useRoute()

// Stale: this runs once, so it keeps showing the first user's id
const idOnce = route.params.id

// Fresh: reads the param reactively
const idNow = computed(() => route.params.id)

// Re-run side effects when the param changes
watch(() => route.params.id, (id) => console.log('now showing', id))
</script>

For data fetching you rarely need watch yourself: pass a function or computed value as the URL to useFetch, as in the earlier example, and it refetches when the param changes. You can also force a fresh instance per URL with definePageMeta({ key: (route) => route.fullPath }), at the cost of recreating the component and losing its state.

The last, tiny stand-in makes the difference visible: a snapshot taken once versus a getter read each time.

JS Stale snapshot versus live read

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file handles /docs/a/b/c and gives you the segments as an array?

    The three-dot form is the catch-all. It matches any number of segments and provides them as an array.
  2. 2. Files users/new.vue and users/[id].vue both exist. Which one serves /users/new?

    Specificity decides: static beats dynamic, which beats optional, which beats catch-all.
  3. 3. What type is route.params.id for /users/42?

    All params are strings. Convert them with Number() or similar when you need a number.
  4. 4. Navigating from /users/1 to /users/2 does not re-run your script setup code. Why?

    Same file means the same component instance is reused. Read params reactively (computed, watch, or a function in useFetch).
  5. 5. Where should you check that a user id looks like a number, before the page renders?

    validate runs before rendering, and returning false shows the 404 page.

Summary

  • Brackets in a file name create params: [id] for one segment, [[id]] for optional, [...slug] for a catch-all array.
  • Read them with useRoute().params; they are strings.
  • Static segments beat dynamic ones, then optional, then catch-all, regardless of file order.
  • validate in definePageMeta rejects bad URLs before rendering.
  • The same page file is reused when only a param changes, so read params reactively.

Next, Nested routes and layouts shows how pages share frames and child pages.