File System Based Routing in Next JS

Aakash Sonawane
VirtouStack
3 min readMay 5, 2022

--

As we all knows that Next.js is java-script (open-source) framework which we use to develop web applications and also which allows us to use React based web applications functionalities such as server-side rendering and generating static websites.

But Next JS provides something more than that, As a react developer we always expected in a react application and that is nothing but the simple way of routing.

To reduce time required to add routing Next JS introduced to us with File-System Based Routing mechanism.

File-System Based Routing

Next JS has a file-system based routing mechanism which is built on the concept of pages. When a new components is added to the pages directory, it’s automatically available as a route. The files inside the pages directory can be used to define most common patterns.

In above screenshot we can see in side the page directory we have a class components named as About.js. to use that page we don’s have to do any additional process like installing third party package which requires configuration and integration for routing the pages. None of this things are required it here.

When a file is added to the pages folder it’s automatically became available as a route so we just need to open browser and go to http://localhost:3000/about As you can see you are now allow to use that component without doing any configurations.

Nested Routes

By mixing and matching file names with a nested folder structure, it is possible to pretty much define the most common routing patterns. Suppose I need to create a blogs web site in which I need following structure of routes, of my components.

In order to achieve this kind of nested routing we need to follow 3 steps :

Step 1 : Create a folder inside the page directory and rename it as ‘blog’

Step 2 : Inside that blog directory create new index.js file which will be your default route as http://localhost:3000/blog

Step 3 : After that in the same directory create two more file for first and second page

Once you done with the above steps, your page directory will be look like this :

And here we go, Now just go to browser and enter following routes to achieve nested routing in your Next JS Application.

http://localhost:3000/blog

http://localhost:3000/blog/first

http://localhost:3000/blog/second

--

--