File-based routing is another feature where Next.js stands out in competition against React. However, In the standard React library, routing is not an inbuilt functionality.
What is Router?
The router is a powerful entity in web applications. It is accountable for organizing an application into multiple views. The router displays the home page when the application is loaded initially and allows navigation based on request. Application changes content on the screen based on the URL.
Routing in Next.js
The routing in Next.js depends on files and folders. We have to structure the folders and files for navigation in our Next.js app.
Next.js supports nested routes and dynamic routes.
When we add a file to the page's directory, it's available as a route. The files inside the page's directory are to define the most common patterns.
Some example from here.
- pages/index.js â /
- pages/blog/index.js â /blog
Example of Nested routes
- pages/blog/first-post.js â /blog/first-post
- pages/dashboard/settings/username.js â /dashboard/settings/username
To match the named parameters. Example of Dynamic Routing:
- pages/blog/[slug].js â /blog/:slug (/blog/hello-world)
- pages/[username]/settings.js â /:username/settings (/foo/settings)
- pages/post/[...all].js â /post/* (/post/2020/id/title)
We'll learn this concept in detail in the upcoming articles.