Routing, Dynamic Segments and Navigation
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Build dynamic, catch-all and optional catch-all segments and read their values from awaited params.
- Navigate with Link and the router APIs and explain what prefetch does per rendering mode.
- Use route groups to organize files without changing URLs.
Overview
#Dynamic segments
A folder named [slug] matches one URL segment and a folder named [...slug] matches the rest of the path. [[...slug]] also matches the path with the segment absent. In Next.js 15 and later the values arrive as a promise you must await:
// app/blog/[slug]/page.tsx
export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
return <h1>{slug}</h1>;
}
Catch-all values are arrays: /docs/a/b gives slug: ['a', 'b']. Optional catch-all [[...slug]] additionally matches /docs itself, with an empty array. Recent Next.js releases also generate global PageProps helper types for validated routes, so PageProps<'/blog/[slug]'> gives you the awaited shape without writing it by hand.
Link and prefetch
<Link href="/blog/hello"> renders an anchor and prefetches the route in the background. Prefetch behavior is version-qualified: for a fully static route Next.js prefetches the whole page; for a dynamic route it prefetches the shared layout and loading shell rather than guessing at request-time data, so a dynamic page still gets an instant shell and streams the rest. Client-side navigation then swaps the rendered tree without a document reload, preserving scroll for back and forward.
Programmatic navigation
In client components use useRouter from next/navigation for push, replace, refresh and back, usePathname for the current path, and useSearchParams to read query strings. In server components call redirect(path) from next/navigation, which throws a control-flow signal to stop rendering, and notFound() to render the nearest not-found boundary. A common upgrade mistake is importing useRouter from next/router, the Pages Router module; in the App Router that import is wrong.
Route groups
A folder in parentheses like (marketing) organizes files and layouts without contributing to the URL. /app/(marketing)/about/page.tsx serves /about. Route groups let two parts of the tree use different root layouts, but the same URL must resolve through exactly one group, or the build fails with a conflicting-routes error.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
app/docs/[[...slug]]/page.tsx exists. Which URLs match it, and what is params inside each? 1. /docs 2. /docs/api 3. /docs/api/auth
Exercise 2Explain
Explain what Link prefetch does for a static route versus a dynamic route in recent Next.js versions, and why the difference exists.
Reveal the reference answer
reference.textFor a static route the rendered output is known at build time, so the viewport-entering Link prefetches the complete payload and the click renders instantly. For a dynamic route the payload depends on the request, so Next.js prefetches only the shared layout and loading shell. The shell appears immediately on click while request-specific content streams in. The difference exists because prefetching request-time data would either cache stale personal content or waste server work on pages the user never opens.Authored expected output: Static full prefetch, dynamic shell prefetch, and the reason: request-time data cannot be known ahead.
This is why every dynamic route benefits from a meaningful loading.tsx or Suspense fallback.
Exercise 3Implement
Implement app/shop/[category]/[item]/page.tsx that awaits params and renders 'Category: X, Item: Y'.
starter.tsx// app/shop/[category]/[item]/page.tsx // TODO: await params and render both valuesReveal the reference answer
reference.tsxexport default async function Page({ params, }: { params: Promise<{ category: string; item: string }>; }) { const { category, item } = await params; return ( <main> <h1>Category: {category}</h1> <p>Item: {item}</p> </main> ); }Authored expected output: Visiting /shop/electronics/lamp renders Category: electronics and Item: lamp.
The component must be async because params is a promise in Next.js 15 and 16.
Exercise 4Debug
This client component throws at runtime after a Pages Router to App Router migration. Identify the bug and fix it. 'use client' import { useRouter } from 'next/router' export function GoHome() { const router = useRouter() return <button onClick={() => router.push('/')}>Home</button> }
starter.tsx'use client' import { useRouter } from 'next/router' export function GoHome() { const router = useRouter() return <button onClick={() => router.push('/')}>Home</button> }Reveal the reference answer
reference.tsxThe import is from the Pages Router module. Change it to import { useRouter } from 'next/navigation'. The App Router hook lives in next/navigation along with usePathname and useSearchParams.Authored expected output: The button navigates client-side without errors.
next/router still exists for Pages Router apps, so the import resolves and then fails or misbehaves at runtime, which makes this a classic migration bug.
Exercise 5Test
Write a pure function matchDynamicRoute(pattern: string, path: string) that returns the params object or null, supporting [param] and [...param] patterns, then write assertions: pattern '/blog/[slug]' against '/blog/hello' gives { slug: 'hello' }, against '/blog/hello/x' gives null, and pattern '/docs/[...slug]' against '/docs/a/b' gives { slug: ['a', 'b'] }.
starter.tsexport function matchDynamicRoute(pattern: string, path: string): Record<string, string | string[]> | null { // TODO }Reveal the reference answer
reference.tsexport function matchDynamicRoute(pattern: string, path: string): Record<string, string | string[]> | null { const patternParts = pattern.split('/').filter(Boolean); const pathParts = path.split('/').filter(Boolean); const params: Record<string, string | string[]> = {}; for (let i = 0; i < patternParts.length; i++) { const p = patternParts[i]; if (p.startsWith('[...') && p.endsWith(']')) { params[p.slice(4, -1)] = pathParts.slice(i); return params; } if (pathParts[i] === undefined) return null; if (p.startsWith('[') && p.endsWith(']')) { params[p.slice(1, -1)] = pathParts[i]; } else if (p !== pathParts[i]) { return null; } } return patternParts.length === pathParts.length ? params : null; } // The trailing length check runs after the loop so a catch-all can consume the remaining segments, while a single segment still rejects a longer path.Authored expected output: All three assertions pass.
This is the matching core the router performs; writing it makes segment semantics concrete.
Exercise 6Interview
An interviewer asks: walk me through what happens between clicking a Link and the new content appearing. Cover prefetch, the router cache, and when a server round trip happens.
Reveal the reference answer
reference.textA good answer: on viewport entry Link prefetches the route payload into the client router cache, full payload for static routes and the layout plus loading shell for dynamic ones. On click the router reads the cached payload, renders the new segment tree immediately from it, and for dynamic content awaits or streams the remaining request-time data while the loading fallback shows. A server round trip happens for any data that was not prefetched; if the payload is fully cached the navigation can complete without one. back and forward use the browser history stack and restore scroll. Mentioning that the router cache is client-side and short-lived per session, and that Next.js 16 tightens this with partial prefetching under Cache Components, shows current knowledge.Authored expected output: Prefetch, router cache, shell-first render, server round trip only for unprefetched data.
The navigation pipeline question separates learners who use Link from those who understand it.
Common misconceptions
#- params is a plain object. Since Next.js 15 it is a promise; awaiting it is required and Next.js 16 removed synchronous property access entirely.
- Link prefetches every page fully. Static routes prefetch fully, dynamic routes prefetch the shell, and prefetch can be disabled with prefetch={false}.
- useRouter comes from next/router. In the App Router it comes from next/navigation; next/router is the Pages Router module.
- Route groups change the URL. Parenthesized folders are organizational only and never appear in the path.
Follow-up practice
#- nextjs-layouts-metadata
- nextjs-request-apis
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.