How next.js handles routing

Ankita Panigrahi
2 min readJan 25, 2022

--

When I first saw how beautifully routing is handled by next.js, at that moment I knew I was in love.

In React, we always need to use an external package(i.e react-router-dom) and define which path leads to which component. It was always a pain.

Next.js introduces routing which requires no external package and no extra overhead of describing the path or components. Not only that, it ensures we maintain a folder structure.

When we create a next.js application, it gives us folder name pages. Inside the pages, we have index.tsx(or .jsx) which is the entry point.

So if you are in the development server, whatever you write in index.tsx, it will correspond to http://localhost:3000/

Bear in mind if you have added a basePath in next.config.js, that would be preceded in every path. Like pages/index.tsx will correspond to http://localhost:3000/{basePath}/

You can create folders inside pages to make other routes. Like if we want to have a products page that lists down a number of products, we can make a folder with the name products or we can create a file products.tsx. So pages/products (or pages/products/index.tsx) would corresponds to http://localhost:3000/{basePath}/products

Now what if we want to create dynamic pages for each products. Thats where [product] comes into picture. We need to create a folder names [product] inside the products folder. So now pages/products/[product] (or pages/products/[product]/index.tsx) will correspond to http://localhost:3000/{basePath}/products/{id}

Now, this is the next.js routing for the frontend.

Next.js also gives us a provision to write APIs inside the application. We have a /api folder inside /pages which will form API endpoint. The API endpoint would be /api/{folder}/{subfolder}/… and so on!

Keep in mind that if you have added a basePath in next.config.js, the basePath will be preceded in the API endpoint.

It would be /basePath/api/{folderName}/{subFolder}.

I hope you learned something from this article!

--

--