Nextjs dynamic routes
/posts/[id]
- pages that begin with
[
and end with]
are dynamic routes in Nextjs.
the page file needs:
- a React component to render
export async getStaticPaths()
which returns a list of possible values forid
.export async getStaticProps({ params })
to fetch the necessary data for the requestedid
. the paramparams
is given, which containsid
(bc the file is named[id].js
).
Important: The returned list is not just an array of strings — it must be an array of objects that look like the comment above. Each object must have the params key and contain an object with the id key (because we’re using [id] in the file name). Otherwise, getStaticPaths will fail.
- in development
getStaticPaths
run on every req. In prod it runs at build time.fallback
is a param. that whenfalse
returns default404
when given a route not returnded bygetStaticPaths
- when
true
the behaviour ofgetStaticProps
changes: - The paths returned from getStaticPaths will be rendered to HTML at build time.
- The paths that have not been generated at build time will not result in a 404 page. Instead, Next.js will serve a "fallback" version of the page on the first request to such a path.
- In the background, Next.js will statically generate the requested path. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time.
- when
- Dynamic routes can be extended to catch all paths by adding three dots (...) inside the brackets. For example:
pages/posts/[...id].js matches /posts/a, but also /posts/a/b, /posts/a/b/c and so on.
If you do this, ingetStaticPaths
, you must return an array as the value of the id key like so:
return [
{
params: {
// Statically Generates /posts/a/b/c
id: ['a', 'b', 'c'],
},
},
//...
];
And params.id will be an array in getStaticProps:
export async function getStaticProps({ params }) {
// params.id will be like ['a', 'b', 'c']
}