How to Set Up Dynamic Routes in Next.js

3 replies
Last updated: Jun 1, 2021
Does anyone have experience with setting up dynamic routes in NextJS? I need to create /foo/bar and /foo/baz where the last part of the url (bar, baz) is dynamic, and capture the value (ie instead of a key/value param in the URL)
You should be able to pull the last part of the slug by using a
./pages/foo/[…slug].js
file.
The
bar
or
baz
will be available in
params.slug
Worth noting that the
./pages/foo/[…slug].js
pattern will match sub paths as well, e.g.
/foo/bar/baz
. If that’s undesired just drop the spread
./pages/foo/[slug].js
.
The params look slightly different. The first example from Simeon should return the slug in an array (one element for each
/
level, e.g.
['bar','baz']
from
/foo/bar/baz
) whereas the second example should return a single slug and adds it to the query params.
There’s also an optional catch all route with a double bracket
./pages/foo/[[…slug]].js
which, in addition to the above, will also match
/foo
.

https://nextjs.org/docs/routing/dynamic-routes
amazingggggggg thanks so much!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?