🚀 Next.js Blog – Day 2: Understanding the File-Based Routing System

 

📌 What is File-Based Routing?

In traditional React applications, routing is managed using a third-party library like React Router. However, Next.js simplifies routing with a file-based approach, meaning the structure of your pages/ directory directly maps to routes in your application.

📂 Folder Structure & Routing

Consider this simple project structure:

java
/pages ├── index.js → Home Page ("/") ├── about.js → About Page ("/about") ├── contact.js → Contact Page ("/contact") ├── blog/ │ ├── index.js → Blog Listing ("/blog") │ ├── post.js → Single Blog Post ("/blog/post")

🛠️ How It Works

  • Each file inside pages/ automatically becomes a route.
  • Nested folders create nested routes.
  • There’s no need for explicit route definitions—Next.js handles it dynamically.

⚡ Dynamic Routes

What if we need dynamic pages like /blog/[slug]? Next.js supports dynamic routing using square brackets [ ].

Example:

jsx
// pages/blog/[slug].js import { useRouter } from "next/router"; export default function BlogPost() { const router = useRouter(); const { slug } = router.query; return <h1>Blog Post: {slug}</h1>; }

👉 This page handles any dynamic route like /blog/nextjs-routing, /blog/react-tips, etc.

✅ Benefits of File-Based Routing

No need for additional routing libraries
Improved performance with automatic code-splitting
SEO-friendly URLs by default
Easier maintenance with a structured file system

🔥 What’s Next?

Tomorrow, I’ll cover API Routes in Next.js—how you can create backend functionalities inside a Next.js app. Stay tuned!

💬 Have any questions? Drop them in the comments! 🚀

Comments

Popular posts from this blog

Next.js