Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

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)
Jun 1, 2021, 9:07 AM
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
Jun 1, 2021, 9:11 AM
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
Jun 1, 2021, 9:54 AM
amazingggggggg thanks so much!
Jun 1, 2021, 9:55 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?