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

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

What is the dynamic route in NextJS

Dynamic routes have created paths with dynamic values.

For example, In blogging applications, you have path post/{postname}, post name 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 the pages folder.

For example, the blog website maintains a 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, accessible 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 a react component for the dynamic route.

[name].tsx

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

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

NextJS dynamic routes query params

NextJS dynamic routes request params