0
0
NextJSframework~15 mins

Nested routes with folders in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - Nested routes with folders
What is it?
Nested routes with folders in Next.js let you organize your web pages in a folder structure that matches the URL paths users visit. Each folder inside the pages or app directory represents a part of the URL path, and files inside those folders become the pages. This helps keep your project tidy and makes it easy to build complex websites with many pages. It also allows you to create layouts and components that apply to groups of pages.
Why it matters
Without nested routes, your project would quickly become messy and hard to manage as it grows. URLs would not clearly reflect the structure of your site, confusing both developers and users. Nested routes with folders solve this by linking your file system to your website’s navigation, making development faster and your site easier to understand and maintain.
Where it fits
Before learning nested routes, you should understand basic Next.js routing and how pages work. After mastering nested routes, you can explore advanced topics like dynamic routes, layouts, and server components to build scalable and maintainable web apps.
Mental Model
Core Idea
Nested routes with folders map your website’s URL paths directly to a folder and file structure in your project.
Think of it like...
It’s like organizing your house by rooms and closets: each room (folder) holds related things (pages), so you always know where to find or add something based on its location.
root folder (app or pages)
├── about (folder)
│   └── page.js (renders /about)
├── blog (folder)
│   ├── page.js (renders /blog)
│   └── [postId] (folder)
│       └── page.js (renders /blog/:postId)
└── contact.js (renders /contact)
Build-Up - 7 Steps
1
FoundationBasic file-based routing
🤔
Concept: Next.js uses files inside the pages or app folder to create routes automatically.
Create a file named page.js inside the app folder. This file becomes the homepage at '/'. Add another file about.js to create the '/about' page. The file name matches the URL path segment.
Result
Visiting '/' shows the homepage, and '/about' shows the about page.
Understanding that files correspond to URLs is the foundation for grasping nested routes.
2
FoundationFolders create nested paths
🤔
Concept: Folders inside the app or pages folder represent nested parts of the URL path.
Create a folder named blog inside app. Inside blog, add page.js. This creates the '/blog' route. Add another folder inside blog named [postId] with page.js to create dynamic nested routes like '/blog/123'.
Result
The URL '/blog' shows the blog page, and '/blog/123' shows the post with id 123.
Folders let you build multi-level URLs that match your site’s structure.
3
IntermediateUsing layout.js for nested layouts
🤔Before reading on: do you think each nested folder can have its own layout that wraps its pages? Commit to yes or no.
Concept: Next.js allows you to add a layout.js file inside any folder to wrap all pages in that folder with a shared layout.
Add layout.js inside the blog folder to create a blog-specific layout. This layout wraps all pages inside blog, like /blog and /blog/[postId]. Layouts can include navigation, headers, or footers specific to that section.
Result
Pages under /blog share the same layout, separate from the rest of the site.
Layouts let you reuse UI parts for groups of pages, making your app easier to maintain and consistent.
4
IntermediateDynamic nested routes with parameters
🤔Before reading on: do you think dynamic route folders can be nested inside other dynamic or static folders? Commit to yes or no.
Concept: You can nest dynamic route folders inside other folders to capture multiple URL parameters.
Inside blog, create a folder [postId]. Inside that, create another folder [commentId] with page.js. This creates routes like /blog/123/456 where 123 is postId and 456 is commentId.
Result
You can access deeply nested dynamic routes with multiple parameters.
Nesting dynamic routes lets you model complex URL structures that reflect real data relationships.
5
IntermediateIndex routes with page.js files
🤔
Concept: A page.js file inside a folder acts as the index route for that folder’s path segment.
Inside a folder like blog, page.js renders the '/blog' path. If you add other files like about.js inside blog, they become '/blog/about'.
Result
You can have a default page for a folder and additional nested pages.
Index routes help you organize default content for a URL segment cleanly.
6
AdvancedShared layouts and nested routing combined
🤔Before reading on: do you think nested layouts can be combined with nested routes to create complex UI hierarchies? Commit to yes or no.
Concept: Nested layouts wrap nested routes, allowing you to build UI hierarchies that match URL hierarchies.
Create a root layout.js for the whole app, then nested layout.js files inside folders like blog or dashboard. Each layout wraps its nested pages and layouts, composing the UI.
Result
Your app UI matches the URL structure, with shared parts at each level.
Combining nested routes and layouts creates scalable, maintainable apps with clear structure.
7
ExpertRoute groups and folder naming tricks
🤔Before reading on: do you think you can create folders that group routes without affecting the URL path? Commit to yes or no.
Concept: Next.js supports route groups using parentheses in folder names to organize files without adding to the URL path.
Create a folder named (admin) inside app. Pages inside (admin) are not part of the URL path but help organize code. For example, app/(admin)/dashboard/page.js renders '/dashboard' but is grouped in code.
Result
You can organize routes in folders without changing URLs, keeping code clean and URLs simple.
Route groups let you separate concerns in your codebase without affecting user-facing URLs.
Under the Hood
Next.js reads the folder and file structure inside the app or pages directory at build time. Each folder corresponds to a URL segment, and each page.js file corresponds to a route endpoint. Dynamic routes use folder or file names wrapped in square brackets to capture URL parameters. layout.js files wrap pages and nested layouts by exporting React components that receive children. Route groups use parentheses in folder names to exclude folders from URL paths but include them in the component tree. This file-based routing system is powered by Next.js’s compiler and server, which map URLs to components automatically.
Why designed this way?
Next.js was designed to simplify routing by using the file system as the source of truth, reducing the need for manual route configuration. This approach makes it easy for beginners to understand and speeds up development. Dynamic routes and layouts were added to handle real-world app complexity. Route groups were introduced to improve code organization without complicating URLs. Alternatives like manual route definitions were rejected because they add boilerplate and risk mismatches between code and URLs.
app folder
├── layout.js (root layout)
├── page.js (homepage)
├── about
│   └── page.js (/about)
├── blog
│   ├── layout.js (blog layout)
│   ├── page.js (/blog)
│   └── [postId]
│       └── page.js (/blog/:postId)
└── (admin)
    └── dashboard
        └── page.js (/dashboard, not /admin/dashboard)
Myth Busters - 4 Common Misconceptions
Quick: Does creating a folder inside app always add a segment to the URL path? Commit to yes or no.
Common Belief:Many think every folder inside app becomes part of the URL path.
Tap to reveal reality
Reality:Folders with names in parentheses, called route groups, do NOT add to the URL path but help organize code.
Why it matters:Without this knowledge, developers may create unwanted URL segments or messy URLs.
Quick: Can you use any file name for a page in Next.js? Commit to yes or no.
Common Belief:Some believe any file name inside app can be a route.
Tap to reveal reality
Reality:Only files named page.js (or page.tsx) define routes; other files are ignored for routing.
Why it matters:Misnaming files causes routes not to work, leading to confusion and bugs.
Quick: Do nested layouts replace parent layouts completely? Commit to yes or no.
Common Belief:People often think nested layouts override or replace parent layouts.
Tap to reveal reality
Reality:Nested layouts wrap inside parent layouts, composing UI layers rather than replacing.
Why it matters:Misunderstanding this leads to broken UI structure and layout bugs.
Quick: Are dynamic route parameters always strings? Commit to yes or no.
Common Belief:Some assume dynamic route parameters are automatically typed or parsed.
Tap to reveal reality
Reality:Parameters are always strings and need manual parsing if other types are needed.
Why it matters:Assuming automatic typing causes runtime errors or unexpected behavior.
Expert Zone
1
Route groups can be combined with layouts to create complex UI structures without affecting URLs, a subtle but powerful pattern.
2
Dynamic route segments can be optional by using double square brackets [[param]], allowing flexible URL matching.
3
Nested layouts preserve state and React context between route changes, improving performance and user experience.
When NOT to use
Avoid deeply nested folder structures that are more than 4-5 levels deep as they become hard to navigate and maintain. For very dynamic or API-heavy apps, consider using API routes or client-side routing with React Router instead of deeply nested file-based routes.
Production Patterns
In production, teams use nested routes with layouts to separate concerns like admin vs public areas. Route groups organize code by feature or team ownership without changing URLs. Dynamic nested routes model real-world data hierarchies like blogs with posts and comments. Layouts are used to cache UI parts and reduce re-renders for better performance.
Connections
Filesystem Hierarchy
Nested routes mirror the folder and file hierarchy of the filesystem.
Understanding how files and folders organize data on your computer helps grasp how URLs map to files in Next.js.
URL Path Structure
Nested routes directly represent the structure of URL paths users visit.
Knowing how URLs are built from segments clarifies why nested folders create nested routes.
Object-Oriented Programming (OOP) - Composition
Nested layouts compose UI components like objects composed of smaller parts.
Seeing layouts as composable parts helps understand how nested layouts build complex interfaces from simple pieces.
Common Pitfalls
#1Creating a folder inside app with a name that includes parentheses but expecting it to add to the URL path.
Wrong approach:app/(admin)/dashboard/page.js // expecting URL to be /admin/dashboard
Correct approach:app/admin/dashboard/page.js // URL is /admin/dashboard
Root cause:Misunderstanding that folders with parentheses are route groups and do not add to the URL path.
#2Naming a route file something other than page.js inside a folder expecting it to create a route.
Wrong approach:app/blog/post.js // expecting /blog/post route
Correct approach:app/blog/page.js // creates /blog route app/blog/[postId]/page.js // creates /blog/:postId route
Root cause:Not knowing that only page.js files define routes in the app directory.
#3Placing layout.js files incorrectly or forgetting to nest them properly, causing layouts not to apply.
Wrong approach:app/blog/page.js app/layout.js app/blog/page.js without app/blog/layout.js when needed
Correct approach:app/layout.js (root layout) app/blog/layout.js (blog layout) app/blog/page.js
Root cause:Not understanding that layouts must be placed in the folder they wrap.
Key Takeaways
Next.js uses your folder and file structure to create nested routes that match URL paths automatically.
Folders represent URL segments, and page.js files inside them become the pages users visit.
Layouts in nested folders wrap pages and other layouts, letting you build reusable UI parts for sections of your site.
Route groups with parentheses let you organize code without changing URLs, keeping your project clean.
Understanding nested routes helps you build scalable, maintainable web apps that reflect real-world URL and UI structures.