Pages, Layouts and Dynamic Segments
Build a small shop catalog with the App Router file conventions: a root layout, a shared catalog layout, a list page, and a dynamic detail route that renders any product slug.
Contentsand lesson path
On this page
- The task
- Step 1: the root layout
- Step 2: a layout for the catalog
- Step 3: the list page
- Step 4: the dynamic detail page
- What usually goes wrong
- Check your understanding
- Apply it
- Review prompt
Lessons of Next.js App Router & Routing
- Where Routing Happens: Client Routers, File-System Routes and Proxy Concept · 25 min
- Pages, Layouts and Dynamic Segments Worked example · 25 min
- Navigation and Keeping State in the URL Worked example · 20 min
- Loading, Error and Metadata per Route Concept · 20 min
- Lab: A Localized Catalog with Shareable Filters and a Members Area Lab · 30 min
- Check: Draw the Route Map Knowledge check · 10 questions
What you will learn
- Create nested routes, shared layouts and dynamic segments with the App Router file conventions (page, layout, loading, error, not-found).
Prerequisites: React Components & State
01. The task
Our shop, Copperleaf Supplies, needs three URLs: a home page, a catalog list, and a detail page that can render any product from its slug — /catalog/gooseneck-kettle, /catalog/hand-grinder, and so on — without a file per product. The catalog pages share an introduction and a row of category links, so that UI should render once and stay put while pages change above it.
Everything below ran on Next.js 16.4.6 with React 19.3.0, Node 22, and the default create-next-app settings, which now enable cacheComponents. The product data is a plain module in lib/products.ts with getProducts() and getProduct(slug) helpers (the lab at the end of this skill prints the whole file); the App Router does not care where data comes from, and files outside app are ordinary modules.
app/
├── layout.tsx root layout: <html>, <body>, site nav
├── page.tsx /
└── catalog/
├── layout.tsx shared intro and category links
├── page.tsx /catalog
└── [slug]/
└── page.tsx /catalog/gooseneck-kettle, /catalog/hand-grinder, …Folder names in plain brackets like [slug] are dynamic segments, covered in step 4. Two more folder conventions organise bigger trees without touching URLs: a folder in parentheses such as app/(shop)/catalog is a route group — it can carry its own layout but contributes no segment to the address — and a folder prefixed with an underscore such as app/_components is private, kept out of routing entirely. The catalog here is small enough to skip both, but knowing them early stops you inventing ways to share a layout across unrelated pages later. The full convention list lives in the Next.js project structure guide, linked in the references.
02. Step 1: the root layout
import type { Metadata } from 'next';
import Link from 'next/link';
import './globals.css';
export const metadata: Metadata = {
title: { default: 'Copperleaf Supplies', template: '%s · Copperleaf Supplies' },
description: 'A small shop catalogue built with the Next.js App Router.',
};
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en">
<body>
<header>
<nav aria-label="Main">
<Link href="/">Copperleaf Supplies</Link>
<Link href="/catalog">Catalog</Link>
</nav>
</header>
<main>{children}</main>
</body>
</html>
);
}The root layout is the one layout the App Router requires, and it must render the <html> and <body> tags itself — Next.js does not inject a document shell around your components. Every page renders inside it through the children prop. LayoutProps is one of Next.js 16's generated type helpers: run next dev, next build or next typegen once and the framework writes route types for you, so LayoutProps<'/'> and later PageProps<'/catalog/[slug]'> need no import. The header uses Link from next/link, which renders a real <a> for crawlers and middle-clicks but navigates on the client when JavaScript is running. The metadata export sets the tab title; we come back to it in the metadata lesson.
03. Step 2: a layout for the catalog
import Link from 'next/link';
import { CATEGORIES } from '../../lib/products';
export default function CatalogLayout({ children }: LayoutProps<'/catalog'>) {
return (
<section>
<p>Every kettle, grinder and brewer we stock, on one shelf.</p>
<nav aria-label="Categories">
<ul>
<li>
<Link href="/catalog">All</Link>
</li>
{CATEGORIES.map((category) => (
<li key={category}>
<Link href={`/catalog?category=${category}`}>{category}</Link>
</li>
))}
</ul>
</nav>
{children}
</section>
);
}Any folder can carry its own layout.tsx, and layouts nest: the root layout wraps the catalog layout, which wraps whatever comes next. Because a layout is shared UI that stays mounted across navigations between its child pages, the introduction and category links here render once and survive every move between the list and the detail pages — only the page segment changes. That also means a layout is the wrong home for anything that should reset per page, and it cannot read the current URL's query string, which is why the category links hard-code their ?category= values rather than reading the current filter.
04. Step 3: the list page
import Link from 'next/link';
<h2>Products</h2>
<ul>
{visible.map((product) => (
<li key={product.slug}>
<Link href={`/catalog/${product.slug}`}>
{product.title}, £{product.priceGBP}
</Link>
</li>
))}
</ul>A page.tsx makes a folder routable — without one, app/catalog would be an invisible organising folder and /catalog would 404. The file exports a component; if it is async, it can await data before returning JSX. What you see is the list part of the running app's page: visible comes from getProducts(), and each product links to /catalog/ plus its slug. The same file also reads searchParams to filter and sort this list — the whole subject of the next lesson, so it is left out of the excerpt here.
05. Step 4: the dynamic detail page
import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getProduct, getProducts } from '../../../lib/products';
export function generateStaticParams() {
return getProducts().map((product) => ({ slug: product.slug }));
}
export async function generateMetadata(
props: PageProps<'/catalog/[slug]'>,
): Promise<Metadata> {
const { slug } = await props.params;
const product = getProduct(slug);
if (!product) return { title: 'Product not found' };
return { title: product.title, description: product.blurb };
}export default async function ProductPage(props: PageProps<'/catalog/[slug]'>) {
const { slug } = await props.params;
if (slug === 'error-demo') {
throw new Error('Inventory service unavailable');
}
const product = getProduct(slug);
if (!product) notFound();
return (
<article>
<h1>{product.title}</h1>
<dl>
<dt>Price</dt>
<dd>£{product.priceGBP}</dd>
<dt>Category</dt>
<dd>{product.category}</dd>
</dl>
<p>{product.blurb}</p>
<p>
<Link href="/catalog">Back to the catalog</Link>
</p>
</article>
);
}The folder name [slug] is a dynamic segment: one folder, many URLs, with the matched value arriving in params. In current Next.js versions params is a Promise, so the page awaits it — a common trap for code written against older tutorials, where props.params.slug worked directly. PageProps<'/catalog/[slug]'> types both params and searchParams from the route literal.
generateStaticParams returns every slug the app knows at build time, so those pages are prerendered while the site builds. It is optional: any slug not in the list still renders on demand, which is what keeps one folder enough. notFound() handles the gap between "any slug" and "this slug exists": calling it throws a signal that renders the nearest not-found.tsx (a file convention the metadata lesson covers). The error-demo branch is a deliberate fault wired in for the next-but-one lesson.
$ npm run buildRoute (app)
┌ ○ /
├ ○ /_not-found
├ ƒ /catalog
└ /catalog/[slug]
├ ◐ /catalog/[slug]
├ ○ /catalog/french-press
├ ○ /catalog/gooseneck-kettle
└ ◐ [+3 more paths]
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
ƒ (Dynamic) server-rendered on demand$ curl -s http://localhost:3131/catalog/gooseneck-kettle \
| grep -o '<title>[^<]*</title>'
$ curl -s http://localhost:3131/catalog/gooseneck-kettle \
| grep -oE '<h1>[^<]*</h1>|<dd[^>]*>[^<]*</dd>' | head -3<title>Gooseneck kettle · Copperleaf Supplies</title>
<h1>Gooseneck kettle</h1>
<dd>kettles</dd>The response for a dynamic URL is complete HTML with the product's own title and heading — the server composed it from params. The build table shows the payoff of generateStaticParams: the home page is static and all five product pages were prerendered at build time (the table folds three of them into [+3 more paths]), while /catalog is marked ƒ (rendered on demand) because it reads request data. Predict what changes once the loading lesson adds a loading.tsx fallback to the catalog: the route becomes ◐ (partial prerender), because the fallback gives it a static shell to send first. Note the title suffix · Copperleaf Supplies: the root layout's title.template from step 1 wrapped the detail page's title automatically.
06. What usually goes wrong
07. Check your understanding
08. Apply it
Extend the running catalog (or your own version of it):
- Add a
/catalog/categories/[category]route that shows one category, reusinggetProducts(category). - Give it its own layout with a one-line description per category.
- Add
generateStaticParamsfor the three known categories and confirm the build output marks them static. - Deliberately break it once: comment out
page.tsxand request the URL, then restore it. Read the error twice so you recognise it in future.
The full app, including filters and the members area, is assembled in the lab at the end of this skill.
09. Review prompt
Without looking back: which two files does a route need to render a URL, and what does each contribute? What does a layout receive, and what stays mounted while it renders? How does one [slug] folder produce a different page per product, what does generateStaticParams change about when that happens, and what should the page do when the slug matches nothing?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.