React
Next.js
3 minute read | February 22, 2024

Dynamic routes with the Nextjs App Router

Sometimes you need your Next.js route segments to be dynamic as might not know your exact segment names ahead of time. An example of this could be if you have a blog with many posts. We can easily create a dynamic route by making a new folder where the folder name is in square brackets "[]". This tutorial assumes you are using the new Next.js App Router rather then the Pages Router.

Example

Let says we have a blog folder, we can create a new folder inside the blog folder called [slug].

We are using [slug] but the name can be any string e.g. [id]

  • blog
    • page.jsx
    • [slug]

Now any request to "/blog/x" will be routed to our dynamic route. Lets create a new page to show our dynamic content, inside of the [slug] folder create a new file called page.jsx.

  • blog
    • page.jsx
    • [slug]
      • page.jsx
Javascript
const Page = ({ params }) => { const { slug } = params; return ( ...some ui ); }; export default Page;

Our new page will receive the dynamic route segment as a "params" prop, you can then use this to show whatever content you need to load on the page. e.g. if the entered route was "/blog/post-1" then slug would contain the string "post-1".

Typescript

If you are using Typescript you can type the page props with the following interface.

Typescript
interface Props { params: { slug: string; } }

Statically rendering dynamic routes

Your dynamic routes will currently be generated on demand at request time. You can use "generateStaticParams" to pre-render your dynamic routes instead. See our post here for a walkthough.