Dynamic routing with Nextjs 13

Minh-Tri Le

Minh-Tri Le on Dec 11, 2022

next.js

blog

Next.js version 13 introduced the new file-system based router built on top of React Server Components with support for layouts nested routing and more.
Currently, we will have a slight difference in defining a dynamic router for a Next.js app. Firstly, we need to look at something new from Next.js 13.

The app Directory

The new router works in a new directory named app. The app directory works alongside the pages directory to allow for incremental adoption.
In the app directory:
  • Folders are used to define routes. A route is a single path of nested folders, following the hierarchy from the root folder down to a final leaf folder. Each folder in a route represents a route segment. Each route segment is mapped to a corresponding segment in a URL path.
  • Files are used to create UI that is shown for the route segment. A special page.js file is used to make route segments publicly accessible.
    Result

    Defining routes page

Dynamic Segments

A Dynamic Segment can be created by wrapping a folderโ€™s name in square brackets: [folderName].
For example, a simple blog could include the following route app/blog/[slug]/page.js where [slug] is the Dynamic Segment for blog posts.
/app/[slug]/page.tsx
export default function Post({ params }) {
  return <div>My Post</div>;
}
RouteExample URLparams
app/post/[slug]/page.tsx/post/post-1{ slug: post-1 }

Generate Static Params

The generateStaticParams function introduced with next js 13 to replace getStaticePath and getStaticProps to define the list of route segment parameters that will be statically generated at build time.
/app/[slug]/page.tsx
export default function Post({ params }) {
  const post = fetch(`https://example-api/post/${params.slug}`)
  return <div>{post.title}</div>;
}

export async function generateStaticParams() {
  const posts = await getPosts();

  return posts.map((post) => ({
    slug: post.slug,
  }));
}
The value returned by generateStaticParams is used to generate a list of static segments. Each segment receives the value of the returned object as their params prop.
With this method, you can create a dynamic router for your Next.js 13 app.

Comments