You learned how routing works and configured new static routes here.

In this post, Learn what is dynamic route and how to configure it. How to create a Course Website.

What is dynamic route in NextJS

Dynamic routes are created the paths with dynamic values.

For example, In blogging applications, you have path post/{postname}, postname is dynamically replaced at runtime. Examples are post/hello-world-abc and post/setup-abc.

NextJS configure dynamic routes using brackets with string in [name] file name in pages folder.

For example, blog website maintains folder structure as follows

+---pages
|   |   about.tsx
|   |   contactus.tsx
|   |   index.tsx
|   |   _app.tsx
|   +---courses
|   |   \---course1
|   |       \---post1
|   +---employee
|   |       create.tsx
|   |       delete.tsx
|   |       edit.tsx
|   |       index.tsx
|   |       view.tsx
|   |
|   \---posts
|           index.tsx
|           [name].tsx

posts/index.tsx - indexed route and displayed all blog posts and mapped to posts/ path, accessable at localhost:3000/posts. posts/[name].tsx: dynamic route where name is dynamically passed in, mapped to posts/[name], and localhost:3000/post/name where name is any dynamic string passed as query string passed to react component.

Let’s create an react component for dynamic route

[name].tsx

export default function PostPage({ example }) {
  return <div>My example is {example}</div>
}

MyDynamicPage.getInitialProps = ({ query: { example } }) => {
  return { name }
}

NextJS dynamice routes query params

NextJS dynamice routes request params