What is File Based routing in Next.js?

Posted by Ashutosh on March 31, 2021


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.


Index Routes

  • pages/index.js → /
  • pages/blog/index.js → /blog


NESTED Routes

Example of Nested routes

  • pages/blog/first-post.js → /blog/first-post
  • pages/dashboard/settings/username.js → /dashboard/settings/username


Dynamic Routes

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.