Dynamic Routing
Learn how to create dynamic routes in a Next.js application.
We'll cover the following
Why we need dynamic routing
Next.js also comes with an effective out-of-the-box way of handling dynamic routes. We’ll start off with the basics of creating dynamic routes with Next.js. But why would we need dynamic routing? In almost all real-world web applications, dynamic routing is a big part of how they work. For example, in social media applications, the profile page for all users has the same markup, but each user's content is different. This is where we can use dynamic routing to change the content of the page but have the same page layout for each user.
Creating dynamically routed files
Because routing is handled using file names by Next.js, the router needs to be told if the route is dynamic. To create a dynamically routed file in Next.js, we need to use []
to encapsulate the file name, for example, [id].js
. This translates to /:id
in our URL. Next.js then takes the :id
portion of the URL and saves it in a variable named id
that we can use from the router
.
A few things to note with dynamic routes are:
/pages/[id].js
would be mapped to/:id
./pages/collections/[collection].js
would be mapped to/collections/:collection
./pages/[collection]/about-collection.js
would be mapped to/:collection/about-collection
.
Let's take a look at how to work with dynamic routes with the example in the code widget below:
Get hands-on with 1200+ tech skills courses.