File-Based Routing in Next.js

In this tutorial, you will understand File bases routing, Next.js automatically creates routes based on your folder structure. This is known as file-based routing, and it works in both App Router and Pages Router.

How to define routes in the App Router?

I will show you example which has routes in the app folder.


app/
 ├─ page.js          → /
 ├─ about/
 │    └─ page.js     → /about
 └─ contact/
      └─ page.js     → /contact

Note: each page.js file become a route.

What is Dynamic Routes?

for the Dynamic Routes, we use square bracket ([]).

Example: Suppose, we create dynamic routes for blog.


app/blog/[id]/page.js             // blog1, blog2, etc.

Note: where id has a numeric value.

Routing in the Pages Router (/pages)

In the below example, you can see, how to use Page Router.


pages/
 ├─ index.js      → /
 ├─ about.js      → /about
 └─ blog/[id].js  → /blog/:id

Benefits of File-based Routing

we have many benifits of File based Routing.

1. There is no need for third-party routing libraries.

2. It has simple folder structure.

3. It has easy dynamic routing.

4. It has automatic code-splitting.

File-Based Routing in Next.js – Interview Questions

Q 1: What is file-based routing?
Ans: Routes are created based on folder and file structure.
Q 2: How do you create a route?
Ans: By creating a page.js file inside a folder.
Q 3: What is a dynamic route?
Ans: Routes created using square brackets like [id].
Q 4: Are nested routes supported?
Ans: Yes, through nested folders.
Q 5: Is routing automatic in Next.js?
Ans: Yes, no extra configuration is required.

File-Based Routing in Next.js – Objective Questions (MCQs)

Q1. How are routes created in Next.js?






Q2. What file defines a route in the App Router?






Q3. Which folder name creates a dynamic route?






Q4. Which file is required to render a page?






Q5. What happens if a folder does not contain page.js?






Related File-Based Routing in Next.js Topics