Part 7 built the pieces by hand: rendering to HTML and streaming it, hydrating, Server Components with a "use client" cut in the module graph, and Server Functions behind forms. What it didn't give you is an app. Something still has to map a URL to a tree of components, decide which parts of that tree survive a navigation, put Suspense and error boundaries in sensible places, and fetch the next page before the user clicks.
Next.js's App Router is that something. Its central idea is small: folders are URL segments, and a few specially named files in each folder are the components for that segment. This chapter builds the mapping from scratch, then walks through every file convention, nested layouts, route groups, dynamic segments, parallel and intercepting routes, and how <Link> prefetches. Everything here is current for Next.js 16.4.
The problem: a router that keeps the right things alive#
Picture the reading list grown into a dashboard, the shape it takes for the rest of Part 8. A sidebar with a search box sits on every /dashboard/* page. Each page loads its own data. Some URLs carry an id, like /dashboard/books/42. You want:
- The sidebar to stay mounted while the page next to it changes, so the search box keeps what the user typed and its scroll position.
- A loading state for the page area only, not a blank screen.
- An error in one page to show an error panel in that page's slot, with the sidebar still usable.
- The next page's code and data fetched before the click, so navigation feels instant.
With the Part 7 primitives you could do each of these by hand: match the URL, nest components, wrap each level in <Suspense> and an error boundary, keep the outer levels from remounting. The App Router turns all of that into a folder structure.
Build it: a file-system router in 30 lines#
Before the real thing, here's the core of it as plain JavaScript. A router gets a list of files under app/ and a URL. It finds the page.tsx whose folders match the URL, then collects every layout.tsx on the way down. That list of layouts, outermost first, is the nesting.
// A toy version of the App Router's matching step. Static segments only.
export function resolve(files, url) {
const urlSegs = url.split("/").filter(Boolean);
const pages = files.filter((f) => f.endsWith("page.tsx"));
for (const page of pages) {
// "app/dashboard/settings/page.tsx" -> ["dashboard", "settings"]
const dirSegs = page.split("/").slice(1, -1);
if (dirSegs.length !== urlSegs.length) continue;
if (!dirSegs.every((seg, i) => seg === urlSegs[i])) continue;
// Walk down from app/ and collect every layout on the way.
const layouts = [];
for (let i = 0; i <= dirSegs.length; i++) {
const dir = ["app", ...dirSegs.slice(0, i)].join("/");
if (files.includes(dir + "/layout.tsx")) layouts.push(dir + "/layout.tsx");
}
return { layouts, page, params: {} };
}
return null; // no page.tsx matches: a 404
}Two things to notice. First, the result for /dashboard/settings is exactly the nesting Next.js renders: root layout, dashboard layout, page. Second, /books returns null. The toy doesn't know that a folder in parentheses is a route group that doesn't appear in the URL, and it doesn't know dynamic segments like [id] either. You'll add both in an exercise at the end of the chapter.
Everything else in the App Router hangs off this list. Next.js wraps each segment's layout around the next one, puts boundaries from loading.tsx and error.tsx between them, and on navigation compares the new list with the old one to decide what to keep.
A request for /dashboard. Next.js walks the folders that match the URL. The root layout.tsx wraps every page, so it renders first: the <html>, <body> and the top nav.
The file conventions#
Inside app/, a folder is a route segment. A folder becomes a URL only once it has a page.tsx (or a route.ts). Other files can live next to them safely; only these names are special:
| File | What it is |
|---|---|
layout.tsx | UI shared by a segment and everything below it. Receives children. Stays mounted across navigations inside it. The root app/layout.tsx is required and must render <html> and <body>. |
page.tsx | The UI unique to a URL. Makes the segment publicly reachable. |
template.tsx | Like a layout, but gets a fresh key on every navigation, so it remounts. |
loading.tsx | A loading UI. Next.js wraps the segment's content in <Suspense fallback={<Loading />}>. |
error.tsx | An error boundary for the segment. Must be a Client Component. |
global-error.tsx | The error boundary for the root layout itself. Replaces the whole document, so it renders its own <html> and <body>. |
not-found.tsx | Rendered when notFound() is called in the segment. The root one also handles unmatched URLs. |
default.tsx | The fallback for a parallel route slot when Next.js can't recover which page it should show (more below). |
route.ts | A Route Handler: an HTTP endpoint using the Web Request and Response APIs. Can't sit in the same segment as a page.tsx. |
There are a few more for specific jobs (forbidden.tsx and unauthorized.tsx, metadata files like icon.png and sitemap.ts, and the project-root proxy.ts and instrumentation.ts you'll meet in the next chapters), but those nine are the routing core.
The order they nest in matters, because it decides what each boundary catches. For one segment, Next.js composes them like this:
<Layout>
<Template>
<ErrorBoundary fallback={<Error />}>
<Suspense fallback={<Loading />}>
<ErrorBoundary fallback={<NotFound />}>
<Page />
</ErrorBoundary>
</Suspense>
</ErrorBoundary>
</Template>
</Layout>Read it from the inside out and three facts fall out that interviewers like:
error.tsxdoesn't catch errors from the layout in the same folder, because the layout is outside the boundary. An error thrown inapp/dashboard/layout.tsxis caught byapp/error.tsx, one level up. That's also whyglobal-error.tsxexists: nothing sits above the root layout.loading.tsxcovers the page, not the layout. The layout renders first and stays visible while the page suspends.- Child segments nest inside the parent's
<Page />position. A layout'schildrenprop is the next segment's whole stack.
error.tsx in Next.js 16#
An error boundary has to be a Client Component (Chapter 21 explains why: boundaries catch errors during rendering, which needs component state on the client). Since Next.js 16.3 the file receives the error and a retry function. retry() re-fetches and re-renders the segment from the server inside a transition, which is what you want when the failure came from data. The older reset() still exists; it only clears the boundary's state and re-renders on the client, so it can't fix a server-side failure.
"use client";
export default function DashboardError({ error, retry }: { error: Error & { digest?: string }; retry: () => void }) {
return (
<div role="alert">
<p>Couldn't load this page.</p>
<button onClick={() => retry()}>Try again</button>
</div>
);
}In production, errors from Server Components reach the client with a generic message and a digest you can match against server logs. The real message never leaks to the browser.
Nested layouts persist#
Here's the behavior the whole design is built around. When you navigate from /dashboard to /dashboard/settings, the two URLs share the root layout and the dashboard layout. Next.js keeps both mounted and only fetches and renders the segment that changed. The docs call this partial rendering. Layouts "preserve state, remain interactive, and do not rerender" on navigation.
You can't run Next.js in this page, but you can run the same idea with React Router's nested routes, which work the same way on the client: a parent route renders an <Outlet /> where its child goes, and navigating between children leaves the parent mounted. This is React Router, not Next.js; it's here so you can feel the behavior.
import { useState } from "react";
import { MemoryRouter, Routes, Route, Outlet, Link } from "react-router";
import { Rendered } from "guide-tools";
function RootLayout() {
return (
<div>
<nav style={{ display: "flex", gap: 12 }}>
<Link to="/dashboard">Dashboard</Link>
<Link to="/dashboard/settings">Settings</Link>
<Link to="/books">Books</Link>
</nav>
<Outlet />
</div>
);
}
function DashboardLayout() {
const [query, setQuery] = useState("");
return (
<div style={{ display: "flex", gap: 16, marginTop: 12 }}>
<aside>
<input placeholder="Search the sidebar" value={query} onChange={(e) => setQuery(e.target.value)} />
</aside>
<Outlet />
</div>
);
}
const Overview = () => <Rendered label="dashboard/page">Overview</Rendered>;
const Settings = () => <Rendered label="settings/page">Settings</Rendered>;
const Books = () => <Rendered label="books/page">Books</Rendered>;
export default function App() {
return (
<MemoryRouter initialEntries={["/dashboard"]}>
<Routes>
<Route element={<RootLayout />}>
<Route path="dashboard" element={<DashboardLayout />}>
<Route index element={<Overview />} />
<Route path="settings" element={<Settings />} />
</Route>
<Route path="books" element={<Books />} />
</Route>
</Routes>
</MemoryRouter>
);
}Type something in the sidebar, then switch between Dashboard and Settings. The text stays, because the dashboard layout never unmounted; each page box mounts fresh. Go to Books and back: the dashboard layout unmounted on the way out, so its state is gone.
Next.js goes one step further than this client-side analog. On the server, a soft navigation (a <Link> click or router.push) renders only the segments below the shared layouts and sends just that part of the RSC payload. The layouts' Server Components don't run again at all. That's fast, and it has a consequence you'll meet in the next chapter: a check that lives in a layout doesn't run when the user navigates between pages under it.
Two more consequences worth knowing:
- Layouts don't receive
searchParams, because they don't re-render when the query string changes. Read search params in the page (thesearchParamsprop) or in a Client Component withuseSearchParams. - A layout can't pass data down to its page as props, since
childrenis an opaque slot. If both need the current user, both callgetUser(). That's fine:fetchcalls with the same URL and options are memoized within a render, and for non-fetchdata you wrap the function in React'scache()(Chapter 44), so the work happens once.
Template: when you want a remount#
template.tsx sits between the layout and the rest, and it gets a unique key per segment. Navigate to a different child and the template remounts: its Client Components lose state and effects run again. Use it for things that should restart per page, like an enter animation or a page-view effect. Search param changes don't remount it.
Route groups#
A folder named in parentheses, like (shop) or (marketing), organizes files without adding a URL segment. app/(shop)/books/page.tsx serves /books. Groups are useful for three things:
- Giving a set of routes a shared layout without changing their URLs:
app/(marketing)/layout.tsxwraps/aboutand/pricingbut not/dashboard. - Splitting an app into areas owned by different teams.
- Multiple root layouts: with no
app/layout.tsx, each group can have its own root layout with its own<html>. Navigating between two different root layouts is a full page reload, not a soft navigation.
Two groups can't both define the same URL. (marketing)/about and (shop)/about both resolve to /about, which is a build error.
Dynamic segments, and why params is a Promise#
Square brackets make a segment dynamic:
| Folder | Matches | params |
|---|---|---|
[id] | /books/42 | { id: "42" } |
[...slug] (catch-all) | /docs/a/b, not /docs | { slug: ["a", "b"] } |
[[...slug]] (optional catch-all) | /docs and /docs/a/b | { slug: undefined } or { slug: ["a", "b"] } |
Since Next.js 15, params and searchParams are Promises, and since 16 synchronous access is removed:
export default async function BookPage({ params }: PageProps<"/books/[id]">) {
const { id } = await params;
const book = await getBook(id);
if (!book) notFound();
return <h1>{book.title}</h1>;
}PageProps<"/books/[id]"> and LayoutProps<"/dashboard"> are global type helpers that Next.js generates from your folders (during next dev, next build or next typegen), so params is typed from the route literal. notFound() comes from next/navigation.
Why a Promise? Because it lets the framework start rendering before it knows the request-specific values. A component that never awaits params can be prerendered once for every URL. A component that does await it can sit inside a <Suspense> boundary and stream in later, while the rest of the layout ships immediately. With synchronous props, reading a param anywhere would force the whole tree to wait for the request. You'll see in Chapter 48 how much of a page Cache Components can prerender because of this, and Chapter 49 covers generateStaticParams, which lists the param values to prerender at build time.
In a Client Component you read params with useParams(), or unwrap the promise passed as a prop with use().
Parallel and intercepting routes#
Some screens show two independent routes at once: a dashboard with a team panel and an analytics panel, each with its own loading and error states, or a feed with a photo open in a modal over it.
Parallel routes are folders prefixed with @. Each one is a slot, passed to the parent layout as a prop next to children:
export default function Layout({ children, team, analytics }: LayoutProps<"/dashboard">) {
return (
<>
{children}
<section>{team}</section>
<section>{analytics}</section>
</>
);
}app/dashboard/@team/page.tsx and app/dashboard/@analytics/page.tsx fill the slots. Slots aren't URL segments (@analytics/views serves /views relative to its parent), and each slot can have its own loading.tsx and error.tsx, so one panel can fail or stream without touching the other.
The tricky part is navigation. On a soft navigation, a slot that has no match for the new URL keeps showing whatever it showed before. On a hard navigation (a full reload), Next.js can't know what that was, so it renders the slot's default.tsx. Next.js 16 requires a default.tsx for every slot; the build fails without one. Return null from it to render nothing, or call notFound() to keep the old 404 behavior.
Intercepting routes let one route render another route's URL in the current layout. The folder prefix says where the target lives, relative to route segments (not file paths, so @slot folders don't count):
(.)photomatches a segment at the same level.(..)photoone level up,(..)(..)phototwo levels up.(...)photofrom the rootappfolder.
Combined, they give you the classic modal: clicking a login link opens a modal over the current page with the URL changed to /login, while visiting /login directly (or refreshing) shows the full page.
import Link from "next/link";
export default function RootLayout({ children, auth }: LayoutProps<"/">) {
return (
<html lang="en">
<body>
<nav>
<Link href="/login">Log in</Link>
</nav>
{auth}
{children}
</body>
</html>
);
}The Modal component (a Client Component) closes with router.back(). Because the open modal is a URL, it's shareable, survives the back button correctly, and a refresh degrades into the full page instead of losing context.
Route Handlers#
A route.ts exports functions named after HTTP methods and uses Web Request and Response:
export async function GET(request: Request) {
const books = await getBooks();
return Response.json(books);
}Route Handlers don't take part in layouts or client navigation, and a folder can have a page.tsx or a route.ts, not both. For mutations triggered by your own UI, prefer Server Actions (next chapter). Route Handlers are for things other clients call: webhooks, a public API, an OAuth callback.
Link and prefetching#
<Link> from next/link renders an <a> and turns clicks into soft navigations: the router fetches the RSC payload for the segments that change and React reconciles it into the existing tree, with state preserved in the layouts that stay.
import Link from "next/link";
<Link href="/dashboard/settings">Settings</Link>;The speed comes from prefetching: when a <Link> enters the viewport, the router fetches what it can for that route ahead of time, and bumps the priority when the user hovers. Prefetching only runs in production builds (next build then next start), which is why navigation in next dev feels slower than in production.
How much it prefetches depends on the prefetch prop and on your configuration:
- Default (
prefetchunset,"auto"ornull): without Partial Prefetching, a static route is prefetched completely and a dynamic route down to its nearestloading.tsxboundary, so a click shows the loading UI instantly. With Partial Prefetching enabled, the default prefetches the route's App Shell: its static and cached content with Suspense fallbacks where request-time data goes. prefetch={true}: more of the route, including cached content that depends on the link's URL (its params and search params).prefetch={false}: never prefetch, neither on viewport entry nor on hover.
The prefetching machinery has changed a lot in 16.x, and interviewers who use Next.js will ask about it:
- Next.js 16 Layout deduplication and incremental prefetching. Prefetches are per segment. If 50 links share a layout, the layout is downloaded once, not 50 times, and the router only fetches segments not already in its cache. Prefetches are cancelled when a link leaves the viewport and redone when their data is invalidated.
- Next.js 16.3 Instant Navigations and Partial Prefetching. An opt-in suite: the
partialPrefetching: trueconfig, a devtools panel (Instant Insights) that flags navigations that aren't instant, and a Playwright helper to test that they stay instant. Small prefetch payloads are also bundled together to cut the request count. - Next.js 16.4 Cache Components on by default for new apps.
create-next-app's recommended defaults now include Cache Components, and the 16.4 release post treatscacheComponents: truepluspartialPrefetching: trueas the model to adopt (check your generatednext.config.tsfor the second flag). Two functions fromnext/cache,navigation()andprefetch(), let a component defer its work to a later stage (skip it in prefetches, or include it only in explicitprefetch={true}prefetches). Chapter 48 shows how caching decides what goes in the App Shell.
For programmatic navigation in Client Components, useRouter() from next/navigation gives you push, replace, back, refresh and prefetch. usePathname() and useSearchParams() read the current URL.
Why useSearchParams needs a Suspense boundary#
This one confuses people because it only fails at build time.
A route that reads nothing request-specific gets prerendered: Next.js renders it to HTML at build time, once, for every visitor. At build time there's no query string. So what should a Client Component that calls useSearchParams() render into that HTML?
Next.js's answer: it can't, so that component (and everything up to the nearest <Suspense> boundary above it) is rendered on the client only. The prerendered HTML contains the Suspense fallback in its place. If there's no Suspense boundary at all, the bailout would swallow the entire page, so the production build fails with the "Missing Suspense boundary with useSearchParams" error. With Cache Components on, the same mistake fails the build with a differently worded error ("Next.js encountered URL data in a Client Component outside of Suspense"), and one nuance changes: if anything else on the route reads request data like cookies(), the boundary is rendered on the server at request time with the real search params instead. In next dev nothing suspends, which is why you don't notice until next build.
"use client";
import { useSearchParams } from "next/navigation";
export function SearchBox() {
const params = useSearchParams();
return <input defaultValue={params.get("q") ?? ""} name="q" />;
}The fix is the same idea as params being a Promise: draw a boundary around the part that depends on the request, so the rest can be static. Alternatives: read searchParams in the page (a Server Component) and pass the value down, or make the route dynamic so there's no build-time render to worry about.
Run it locally (optional)#
Next.js can't run in this page, but it takes a minute on your machine. You need Node.js 20.9 or later.
npx create-next-app@latest reading-list --yes
cd reading-list
npm run dev--yes skips the prompts and uses the recommended defaults (or your saved preferences if you've run it before): TypeScript, Tailwind, ESLint, App Router and, since 16.4, Cache Components. Then try the things from this chapter:
- Create
app/dashboard/layout.tsxwith an<input>and{children}, plusapp/dashboard/page.tsxandapp/dashboard/settings/page.tsx. Link between them and type in the input. - Add
app/dashboard/loading.tsxand make the settings pageawait new Promise((r) => setTimeout(r, 2000)). - Add a Client Component that calls
useSearchParams()without a Suspense boundary and runnpm run buildto see the error (with Cache Components on, it's the "URL data in a Client Component outside of Suspense" variant). - Run
npm run build && npm startand watch the Network panel: links prefetch as they scroll into view.
Pitfalls#
Check your understanding#
Extend resolve so it handles:
- Route groups: a folder like
(shop)is skipped when matching the URL, but itslayout.tsxstill counts. - Dynamic segments:
[id]matches any one segment and recordsparams.id. - Catch-all segments:
[...slug]matches one or more remaining segments and records them as an array. - Priority: a static segment beats a dynamic one, and a dynamic one beats a catch-all.
/books/newmust hitbooks/new/page.tsx, notbooks/[id]/page.tsx.
Press Check when you're done.
export function resolve(files, url) {
const urlSegs = url.split("/").filter(Boolean);
const pages = files.filter((f) => f.endsWith("page.tsx"));
for (const page of pages) {
const dirSegs = page.split("/").slice(1, -1);
if (dirSegs.length !== urlSegs.length) continue;
if (!dirSegs.every((seg, i) => seg === urlSegs[i])) continue;
const layouts = [];
for (let i = 0; i <= dirSegs.length; i++) {
const dir = ["app", ...dirSegs.slice(0, i)].join("/");
if (files.includes(dir + "/layout.tsx")) layouts.push(dir + "/layout.tsx");
}
return { layouts, page, params: {} };
}
return null;
}This app has app/layout.tsx, app/error.tsx, app/dashboard/layout.tsx, app/dashboard/error.tsx and app/dashboard/page.tsx.
app/dashboard/page.tsxthrows while rendering. Whicherror.tsxrenders, and is the dashboard sidebar (inapp/dashboard/layout.tsx) still visible?app/dashboard/layout.tsxthrows. Whicherror.tsxrenders?app/layout.tsxthrows. What renders?
A Client Component calls useSearchParams() on a route that's otherwise static. next dev works, next build fails. Why?
app/shop/layout.tsx renders a Client Component with a counter, and app/shop/template.tsx renders another one. You click each counter to 3, then navigate from /shop/a to /shop/b with a <Link>. Then you change the URL to /shop/b?sort=price. What do the two counters show after each step?
An interviewer asks: "In the Next.js App Router, what happens when a user clicks a link from /dashboard to /dashboard/settings?"
"How would you build a photo modal in Next.js that has its own URL, closes with the back button, and shows a full page if someone opens the link directly?"
Interview angle
The App Router maps folders under app to URL segments, and special files in each folder define that segment: layout, page, template, loading, error, not-found, default and route. Next.js nests them in a fixed order, so loading.tsx becomes a Suspense boundary and error.tsx an error boundary around the page. Layouts persist: on a soft navigation only the changed segments are fetched and rendered, so shared layouts keep their state. Params and searchParams are Promises so request-specific parts can stream while the rest prerenders, and Link prefetches routes in production as they enter the viewport.
What happens when a user navigates between two pages that share a layout?
Why can't app/dashboard/error.tsx catch an error thrown in app/dashboard/layout.tsx?
Why does useSearchParams need a Suspense boundary in Next.js?
Why are params and searchParams Promises since Next.js 15?
How do parallel and intercepting routes work together to build a modal?
How does Link prefetching work in Next.js 16, and what changed recently?
Recap#
- Folders under
app/are URL segments. A folder is reachable once it haspage.tsx(orroute.ts), and special files add a layout, template, loading state, error boundary, not-found UI or slot fallback to that segment. - Next.js nests them in a fixed order: layout, template, error boundary, Suspense for loading, not-found boundary, page. That order explains why
error.tsxcan't catch its own layout's errors. - On navigation, shared layouts stay mounted and don't re-render; only the changed segments are fetched. Templates remount, and layouts never see
searchParams. paramsandsearchParamsare Promises (required since Next.js 16) so request-specific parts can stream behind Suspense while the rest prerenders.useSearchParamsneeds a Suspense boundary for the same reason.- Parallel routes (
@slot) and intercepting routes ((.),(..),(...)) combine into URL-addressable modals; every slot needsdefault.tsxin Next.js 16. <Link>prefetches in production when links enter the viewport. Next.js 16 deduplicates shared layouts, 16.3 added Partial Prefetching, and 16.4 turns Cache Components on for new apps.
Sources#
- nextjs.org: Layouts and Pages, File-system conventions, template.js, error.js, not-found.js, default.js
- nextjs.org: Dynamic Segments, Route Groups, Parallel Routes, Intercepting Routes, Route Handlers
- nextjs.org: Link, useSearchParams
- nextjs.org blog: Next.js 16, Next.js 16.3, Next.js 16.4
- Facts checked November 24, 2026.