Understand static and dynamic Page Routing in Next.js

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

Next.js uses a file-system based router, meaning that it treats single-file components in the /pages/ directory as pages. In this lesson, we will set up multiple pages and use next/link to navigate across different routes, and see how to create dynamic routes, and parse URL query strings.

We will be using TypeScript, but for this specific lesson, no changes need to be made if you are using JavaScript.

Instructor: [0:00] Let's create a new About page by creating a file, about.tsx, in the pages directory. After saving this file, our About page can be visited by going to localhost:3000/about in a browser.

[0:21] Next.js has excellent support for client-side routing. Let's create a link on the Index page to the About page by using the nextLink component. Then we pass the destination route to the href prop. Inside the link, we can have some text. Then we can do the same thing in the About page.

[0:48] Let's have a look in the browser. The index files will always be mapped to the root of the directory they are in. For example, let's create an about directory. Move the about.tsx file into it and rename it to index.tsx.

[1:08] We can also create nested routes by simply creating files inside nested directories. Let's create a new file, me.tsx, and link it to the About page. As we can see, everything works in the browser.

[1:32] Next.js allows us to create dynamic routes as well. Let's create a user directory and a [id] .tsx file in it. Inside this page, we'll create a page component called User, with some text. When the browser hits an arbitrary sub-route under the User route, this [id] page will be served.

[1:58] Now we'd like to access and parse the URL itself so we can render content dynamically. Let's do this by importing the useRouter hook from the next/router module. Then, in our page component, fetch the router objects using the hook and grab the parsed ID string from Router.Query.

[2:21] Notice that the name of this variable should match the text we put in the brackets in a filename. We can also pass additional parameters using the { url: { query: string. The parameters will also be parsed and put into the Router.Query object.

[2:43] Now, let's test this in the browser with an URL url/123a, then the query string, action = create, and DarkMode = false. Now we can see the query string is parsed by Next.js, and we can render dynamic contents based on what we have here.