Next.js App Router: Layouts, Route Groups, and Nested Routing
Next.js App Router: Leverage modern layout systems, route groups, and nested routing.
In the legacy Pages Router (pages/), every route was essentially an isolated page template. Composing persistent layouts meant wiring up custom HOCs (like getLayout) or writing fragile wrappers in _app.js. Route transitions routinely caused full-page unmounts, scroll jumps, and duplicate data fetching.
The App Router treats your folder structure as a nested, hierarchical component graph. Built on React Server Components (RSC), Streaming <Suspense>, and React Transitions, it allows independent subtrees to render, stream in parallel, and cache on the client—all without unmounting persistent UI elements like sidebars, navigation bars, or audio players.
## 1. File-System Conventions & Component Hierarchy
The App Router uses folder-based routing inside the app/ directory. Each directory segment maps to a URL path, and specific reserved filenames govern the layout and boundary behavior of that segment:
- Plaintext
- app/
```text
├── layout.tsx # Mandatory Root Layout (wraps and )
├── page.tsx # Route UI for '/'
├── loading.tsx # Automatic boundary fallback
├── error.tsx # Client-side Error Boundary ('use client')
├── not-found.tsx # Fallback UI for 404 boundaries
├── global-error.tsx # Top-level boundary fallback for Root Layout errors
└── dashboard/
├── layout.tsx # Nested Layout (persists across all dashboard sub-routes)
├── page.tsx # Route UI for '/dashboard'
└── settings/
└── page.tsx # Route UI for '/dashboard/settings'
```
### Component Hierarchy Inside a Segment
When you declare these reserved files within the same folder, Next.js composes them into an automatic, nested component tree behind the scenes:
```ts
// Mental model of Next.js folder composition
}>
}>
```
## 2. Nested Layouts: State Persistence & Partial Rendering
A layout.tsx file defines UI shared across child routes. During navigation, layouts stay mounted, remain interactive, preserve internal state, and avoid unnecessary re-renders.
### 2.1 The Root Layout (app/layout.tsx)
The root layout is mandatory. It replaces _app.js and _document.js from the Pages Router, and is the only location where <html> and <body> tags should be defined:
```ts
// app/layout.tsx (Server Component by default)
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import '@/styles/globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: {
template: '%s | Enterprise Cloud',
default: 'Enterprise Cloud Portal',
},
description: 'Mission-critical telemetry and fleet management platform.',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{/* Mount application-wide providers, alerts, or telemetry */}
{children}
);
}
```
### 2.2 Nested Layouts & Partial Rendering
When a user moves between /dashboard/analytics and /dashboard/settings:
- The shared app/dashboard/layout.tsx does not remount.
- State inside that layout (such as active navigation toggles, search inputs, or player controls) remains completely intact.
- Next.js only unmounts and swaps the changing leaf route components (analytics/page.tsx settings/page.tsx).
```ts
// app/dashboard/layout.tsx
import { SidebarNav } from '@/components/SidebarNav';
import { DashboardHeader } from '@/components/DashboardHeader';
export default async function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
## 3. Route Groups: Organizing Folders Without Changing the URL
By default, every directory in app/ adds a segment to the public URL path. Route Groups bypass this mapping.
Enclosing a folder name in parentheses—(folderName)—signals to the router: "Use this folder strictly for organizing files, applying shared layouts, or grouping middleware, but exclude its name from the final URL path."
### Plaintext
```text
app/
├── (marketing)/
│ ├── layout.tsx # Marketing shell: sales navbar and marketing footer
│ ├── page.tsx # Resolves to: '/'
│ ├── pricing/
│ │ └── page.tsx # Resolves to: '/pricing' (NOT '/marketing/pricing')
│ └── about/
│ └── page.tsx # Resolves to: '/about'
│
└── (app)/
├── layout.tsx # Application shell: sidebar, notification center
├── dashboard/
│ └── page.tsx # Resolves to: '/dashboard' (NOT '/app/dashboard')
└── settings/
└── page.tsx # Resolves to: '/settings'
```
### Key Architectural Capabilities
- **Multiple Root Layouts:** You can omit the top-level app/layout.tsx and place distinct root layouts inside (marketing)/layout.tsx and (auth)/layout.tsx. This makes it easy to render completely different HTML document structures (e.g., stripping navigation shells from checkout or login screens).
- **Domain-Driven Organization:** Teams can organize workspaces by domain ((billing), (analytics), (catalog)) without having to alter public route URLs.
- **Targeted Providers:** Wrap specific branches in dedicated Context providers or themes without forcing them onto unrelated pages.
## 4. Dynamic Route Segments
### Plaintext
- **Basic Dynamic Route:** app/shop/[category]/page.tsx --> /shop/shoes
- **Catch-All Route:** app/docs/[...slug]/page.tsx --> /docs/api/v1/auth
- **Optional Catch-All:** app/wiki/[[...slug]]/page.tsx --> /wiki AND /wiki/react/hooks
In Catch-All routes ([...slug]), segments arrive as an array of strings. In modern Next.js releases, page params are asynchronous:
```ts
// app/docs/[...slug]/page.tsx
interface PageProps {
params: Promise<{
slug?: string[];
}>;
}
export default async function DocsPage({ params }: PageProps) {
const resolvedParams = await params;
const pathHierarchy = resolvedParams.slug ?? [];
return (
);
}
```
## 5. Parallel & Intercepting Routes
The App Router provides declarative patterns for dashboard widgets, split screens, and modal dialogs without turning to client-side modal state management.
### 5.1 Parallel Routes: Named Slots (@slotName)
Parallel routing renders one or more sibling pages simultaneously inside a shared layout using Named Slots. Slots use the @ prefix and arrive as props in the parent layout:
- Plaintext
- app/dashboard/
```text
├── layout.tsx
├── page.tsx
├── @analytics/
│ ├── page.tsx
│ └── loading.tsx
└── @metrics/
├── page.tsx
└── loading.tsx
```
```ts
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
analytics,
metrics,
}: {
children: React.ReactNode;
analytics: React.ReactNode;
metrics: React.ReactNode;
}) {
return (
);
}
```
When navigating to /dashboard:
- RootLayout and DashboardLayout render immediately without waiting on data.
- Next.js displays <DashboardLoading/> in place of the page content instantly.
- Server Components fetch data on the backend.
- As data resolves, React streams the finished HTML over the wire and swaps out the fallback skeleton in place.
{/* Sidebar stays mounted and preserves state across sub-navigations */}
{/* Only this slot changes when moving between child pages */}
{children}
);
}
```
### 2.3 Layouts vs. Templates (layout.tsx vs. template.tsx)
While layouts persist state across navigations, template.tsx creates a fresh component instance on every route change. This is useful for route entry animations, per-page view trackers, or clearing form inputs on page transitions.
| Metric | layout.tsx | template.tsx |
| --- | --- | --- |
| Instance Lifecycle | Maintained across sub-navigation. | Remounted on every page navigation. |
| DOM & Form State | Preserved (input values, scroll positions, focus stay put). | Completely reset. |
| useEffect Calls | Fires once on initial mount. | Fires on every route change. |
| Ideal Use Cases | Navigation shells, sidebars, context providers. | CSS/Framer Motion enter animations, feedback forms, route-change logging. |
```ts
// app/dashboard/template.tsx
'use client';
import { motion } from 'framer-motion';
export default function Template({ children }: { children: React.ReactNode }) {
return (
Breadcrumb: {pathHierarchy.join(' / ')}
{children}
);
}
```
Because each slot maintains its own loading.tsx boundary, fast panels stream in immediately without being blocked by slower sibling widgets.
### 5.2 Intercepting Routes: Context-Aware Navigation
Intercepting routes let you load a route from another part of the application inside the current layout (such as rendering a photo modal over a photo feed) while updating the browser URL.
(.) targets segments on the same directory level.
(..) targets segments one level up.
(...) targets segments from the root app/ directory.
### The Photo Feed Modal Pattern
When a user clicks a photo card in /feed:
- **Client-side navigation:** Next.js matches app/feed/(..)photo/[id]/page.tsx, displaying the photo as an overlay modal directly over the feed. The browser URL updates to /photo/123.
- **Hard refresh or shared link:** If the user pastes /photo/123 into a new tab or refreshes, there is no feed context to overlay. Next.js serves the standalone route at app/photo/[id]/page.tsx.
- Plaintext
- app/
```text
├── feed/
│ ├── page.tsx # Feed page with image thumbnail grid
│ └── (..)photo/[id]/
│ └── page.tsx # Renders as a MODAL on client navigation
└── photo/[id]/
└── page.tsx # Full standalone page on direct visit or hard refresh
```
## 6. Fine-Grained Streaming with loading.tsx
Adding a loading.tsx file automatically places the adjacent page.tsx and its descendants inside a <Suspense> boundary:
```ts
// app/dashboard/loading.tsx
export default function DashboardLoading() {
return (
{/* Each slot renders concurrently with its own loading and error boundaries */}
{analytics}
{metrics}
