Routing in Next.js

Tram Ho

Next.js has one of the most robust and easy to use routes that you can just use out of the box. You don’t need to hassle by configuring it.
Because Next.js follows the Convention over Configuration philosophy, every file inside the pages directory will be automatically considered as a route.
So, let’s see what different types of routing we get with Next.

Static Routing

Let’s create an About page for our blog app

For it, just create a file about.js insided pages directory

with content

That’s it. Next’s built HMR should automatically pick up the added file, and create a route for it.

Just go to localhost:3000/about and you should see your about page.

Now, let’s think for some reason you need to structure your about routes in a different
maybe

For that, you need your folder structured like this

Let’s create them

We renamed our old about.js file to index.js and moved it inside the pages/about folder.
If you refresh the page, it’ll behave in the same way.

and your weird random page

Dynamic Routing

Ofcourse, you can just use Static routes for some simple urls.
Let’s think you’re creating a blog and you need to show your posts through posts/1 url

The folder structure for that will be

the index.js file is for your all posts page.

What about the weird [id].js file?
This is a special syntax used by Next.js called slugs. The string inside the [ and ] brackets denote which parameters the page will receive.
Let’s see the code

We need to import the useRouter module from next/router to catch which param was sent in the URL.
That is done by the following code

if you instead named your slug as [post_id].js, then the code should be

Now, if you visit the url posts/1234567 the page will receive the data { "id": "1234567" } and render

Catch all routes

So, what about when you want to pass more data through the url and catch them in the following page.

in that case, we will need Catch all routes. It’s syntax is like

This will match posts/1, at the same time match posts/1/2/3/abc and so on.
Remember with [id].js we received the vlaue like { "id": "1234567" }

With […slug.js] we will receive the value in an array.
So, posts/a/b will give you { "slug": ["a", "b"] }

If you go to localhost:3000/articles/12/32 it’ll get an array [12, 32]

That’s it.

Shallow Routing

Shallow routing is used for changing the url without fetching any data.
This means getStaticProps or getServerSideProps will not be called.

Example:

The URL will get updated to /?counter=123 and the page won’t get replaced, only the state of the route is changed.

Learning Materials

Next.js doc

Static and dynamic routing with Next.js

Source code

Share the news now

Source : Viblo