Dynamic Routing in Next.js (Page Router)


Objectives

Learn how to use Page Router to create dynamic routes in Next.js.

What is Dynamic Routes

The definition of Dynamic Routes from the official Next.js documentaion: When you don't know the exact segment names ahead of time and want to create routes from dynamic data, you can use Dynamic Segments that are filled in at request time or prerendered at build time.

File Structure

Let's take a look at the file structure of a typical Next.js project using TypeScript and Page Router.

Notice that the pages folder contains all the pages of the website.

Add Dynamic Routes

To add dynamic routes, we need to create a file with the name of the dynamic route and wrap the file name with square brackets. For example, if we want to create a dynamic route for the job post with the id of 1, we can create a file named [id].tsx in the pages/jobs folder.

Here is the file structure of the pages folder now.

To test the dynamic route, we need to add some code to [id].tsx

In the [id].tsx file, we can use the useRouter hook to get the id from the URL.

Check the result in the browser

Run npm run dev in the terminal and go to the browser.

Notice that the URL is http://localhost:3001/jobs/1, which means the [id].tsx file is working. You can also try to change the id in the URL to see if the page is updated.

Conclusion

Hooraay! We have learned how to create dynamic routes in Next.js. Isn't it easy? To learn more about dynamic routes, please visit the official Next.js documentation. Thank you for reading. See you next time!

Resources