
Nested Routing in NextJS
📂 Nested Routing in Next.js
Next.js automatically creates routes based on the folder structure inside the pages
or app
directory. Nested routes are created by nesting folders inside the pages/
directory.
📌 1. Basic Nested Routing
In the pages/
directory, create a nested structure like this:
pages/│── index.js → Homepage (/)│── about.js → About page (/about)│── blog/│ ├── index.js → Blog listing page (/blog)│ ├── post.js → Specific blog post (/blog/post)
🔹 Example: Nested blog/index.js
<h1>Docs: {slug ? slug.join("/") : "Home"}<div> <h1>Blog Post: {params.id}</h1>;}
✅ Works with /blog/nextjs-routing
📌 7. Best Practices for Nested Routing in Next.js
✔️ Use folders to define nested routes
✔️ Use dynamic routing ([id].js
) for dynamic pages
✔️ Use catch-all ([...slug].js
) for flexible routing
✔️ Use app/
directory for newer Next.js projects