0
0
NextJSframework~5 mins

Why file-based routing simplifies navigation in NextJS

Choose your learning style9 modes available
Introduction

File-based routing lets you create pages by just adding files. This makes navigation easy because the file structure matches the website paths.

When building a website with many pages and you want simple navigation setup.
When you want your folder and file names to directly control the website URLs.
When you want to avoid manually writing route code for each page.
When you want to quickly add or remove pages by adding or deleting files.
When you want your project structure to clearly show the website structure.
Syntax
NextJS
app/
  page.tsx  --> renders '/' route
  about/
    page.tsx  --> renders '/about' route
  blog/
    [id]/
      page.tsx  --> renders '/blog/[id]' dynamic route
Each folder with a page.tsx file becomes a route.
Dynamic routes use square brackets like [id] to capture URL parts.
Examples
The file page.tsx inside app folder creates the home page route.
NextJS
app/page.tsx
// This file renders the home page at '/'
Adding a folder about with page.tsx creates the '/about' page automatically.
NextJS
app/about/page.tsx
// This file renders the about page at '/about'
The folder [id] captures any value in the URL after '/blog/' as a parameter.
NextJS
app/blog/[id]/page.tsx
// This file renders dynamic blog posts at '/blog/[id]'
Sample Program

This example shows three pages created by files. The home page at '/', the about page at '/about', and dynamic blog posts at '/blog/[id]'. The dynamic page reads the URL part as id and shows it.

NextJS
/*
Folder structure:
app/
  page.tsx
  about/
    page.tsx
  blog/
    [id]/
      page.tsx
*/

// app/page.tsx
export default function HomePage() {
  return <h1>Home Page</h1>;
}

// app/about/page.tsx
export default function AboutPage() {
  return <h1>About Us</h1>;
}

// app/blog/[id]/page.tsx
export default function BlogPost({ params }: { params: { id: string } }) {
  return <h1>Blog Post: {params.id}</h1>;
}
OutputSuccess
Important Notes

File names and folders directly control the website URLs, so naming is important.

Dynamic routes let you handle many similar pages without writing extra code.

File-based routing reduces mistakes because you don't write route code manually.

Summary

File-based routing matches files to website pages automatically.

It makes adding or changing pages as easy as creating or deleting files.

Dynamic routes let you handle many pages with one file using URL parameters.