Performance Optimization in the App Router
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
#- Diagnose which parts of a page ship JavaScript and move client boundaries down the tree.
- Apply dynamic imports, streaming, font and image techniques to improve loading performance.
- Explain what changed with Turbopack becoming the default bundler in Next.js 16.
Overview
#Measure, then cut JavaScript
Performance work starts with measurement: a Lighthouse or DevTools performance profile tells you whether you have a network problem, a JavaScript problem or a backend problem. In the App Router the most common self-inflicted problem is JavaScript volume, and the mental model from the server components lesson is your diagnostic tool: every component outside a 'use client' boundary contributes zero JavaScript for its own logic, while every client boundary ships its real code plus its imports to the browser. A page that feels heavy usually has one boundary placed too high in the tree.
Placing boundaries and splitting bundles
The fix is structural, not micro-optimization. Move 'use client' from a page-level wrapper down to the leaf that actually needs state or events, so the surrounding server tree stays free. For dependencies that are heavy and non-critical, split them out of the initial bundle with a dynamic import:
"use client";
import dynamic from "next/dynamic";
const HeavyChart = dynamic(() => import("./heavy-chart"), {
ssr: false,
loading: () => <p>Loading chart...</p>,
});
Route-level code splitting is automatic: each segment gets its own bundle, so navigating to a route loads only that route's code. What is not automatic is keeping barrel files honest. An index.ts that re-exports forty components pulls every transitive import into every importer; import directly from the module you need.
Streaming and assets
Streaming improves perceived performance independently of bundle size. A fast shell with Suspense fallbacks reaches the browser quickly while slow data streams into place, which is why the loading.tsx lesson matters for performance and not just polish. For assets, next/font self-hosts fonts with preloading and eliminates the layout shift of third-party font CSS, and priority on the LCP image removes the render delay of a lazy-loaded hero. Turbopack is the default bundler for both next dev and next build as of Next.js 16, which shortens the feedback loop that all of this iteration depends on.
The serialization tax
One hidden cost deserves its own mention: props crossing a server-to-client boundary are serialized. Passing a huge array from a server component into a client component costs serialization on the server, transfer on the network and parsing in the browser. Pass the identifiers and let the client component fetch what it renders, or keep the rendering server-side and hand the client only the interactive sliver.
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
A page.tsx (server component) renders <ProductGrid />, and ProductGrid.tsx starts with 'use client' and imports a 300 KB charting library at module scope to render one small sparkline per row. What ships to the browser for this route, and which single change reduces it most?
Exercise 2Explain
Explain why moving a 'use client' directive from a page-level wrapper down to the interactive leaf reduces the client bundle, and what stays behind on the server.
Reveal the reference answer
reference.textThe directive marks the root of a client subtree, and everything it imports ships as JavaScript. A page-level wrapper drags the whole page's rendering logic, its imports and any libraries it uses into the bundle, even though most of the page is static presentation. Moving the directive to the leaf that owns state or events leaves the surrounding markup as server components: they render to HTML on the server, contribute no component JavaScript, and the browser downloads only the interactive sliver plus its imports.Authored expected output: An explanation that the directive defines a subtree boundary whose imports all ship, and that lower placement shrinks that subtree.
The bundle is the transitive closure of client-boundary imports, so boundary placement is bundle architecture.
Exercise 3Implement
A dashboard page imports a 400 KB analytics panel synchronously inside a client component. Convert it to a dynamic import that excludes it from SSR, shows a skeleton while loading, and only loads when the panel section scrolls near the viewport.
starter.tsx"use client"; import AnalyticsPanel from "./analytics-panel"; export function Dashboard() { return ( <div> <h1>Dashboard</h1> <AnalyticsPanel /> </div> ); }Reveal the reference answer
reference.tsx"use client"; import dynamic from "next/dynamic"; const AnalyticsPanel = dynamic(() => import("./analytics-panel"), { ssr: false, loading: () => <div className="skeleton" aria-busy="true" />, }); export function Dashboard() { return ( <div> <h1>Dashboard</h1> <div style={{ contentVisibility: 'auto' }}> <AnalyticsPanel /> </div> </div> ); } // contentVisibility: auto lets the browser skip rendering work for offscreen content; // combined with the dynamic import the panel's code loads when it approaches the viewport.Authored expected output: The initial route bundle excludes the analytics panel; a skeleton renders immediately and the panel's code loads on approach.
next/dynamic with ssr:false removes the module from both the server render and the initial client chunk, and the loading option covers the gap.
Exercise 4Debug
A marketing page was fast before a refactor. Now every page in the app ships a heavy animation library and Lighthouse shows a large bundle on routes that never animate. Find the cause. // app/layout.tsx "use client"; import { MotionProvider } from "./motion-provider"; export default function RootLayout({ children }: { children: React.ReactNode }) { return <MotionProvider>{children}</MotionProvider>; }
starter.tsx// app/layout.tsx "use client"; import { MotionProvider } from "./motion-provider"; export default function RootLayout({ children }: { children: React.ReactNode }) { return <MotionProvider>{children}</MotionProvider>; }Reveal the reference answer
reference.tsxThe 'use client' on the root layout turns the entire layout subtree into client components, so every route's content becomes client JavaScript and the animation library imported by MotionProvider ships everywhere. Fix by removing the directive from the layout, keeping the layout a server component, and placing 'use client' inside motion-provider only if it needs hooks, importing the animation library there or dynamically.Authored expected output: Non-animated routes stop shipping the animation library because the root layout is a server component again.
A client boundary at the root is the most expensive possible placement: it converts the whole tree below it.
Exercise 5Test
Write a pure function clientCost(components: Array<{ name: string, isClient: boolean, imports: Array<{ name: string, gzipKb: number }> }>) that returns the total gzipKb a route must ship: every client component contributes its imports' sizes, server components contribute nothing, and write assertions for a mix of two client components sharing one library and one server component.
starter.tsexport function clientCost(components: Array<{ name: string, isClient: boolean, imports: Array<{ name: string, gzipKb: number }> }>): number { // TODO } // assertions // const lib = { name: 'chart-lib', gzipKb: 100 } // const grid = { name: 'grid', isClient: true, imports: [lib] } // const spark = { name: 'spark', isClient: true, imports: [lib] } // const text = { name: 'text', isClient: false, imports: [lib] } // expect(clientCost([grid, spark, text])).toBe(100)Reveal the reference answer
reference.tsexport function clientCost(components: Array<{ name: string, isClient: boolean, imports: Array<{ name: string, gzipKb: number }> }>): number { const shipped = new Set<string>(); for (const component of components) { if (!component.isClient) continue; for (const dependency of component.imports) shipped.add(dependency.name); } const sizes = new Map(components.flatMap((c) => c.imports).map((d) => [d.name, d.gzipKb])); let total = 0; for (const name of shipped) total += sizes.get(name) ?? 0; return total; } // Both client components import chart-lib, but a bundler deduplicates it, so the shared // library counts once. The server component's import never ships.Authored expected output: The assertion passes with 100, not 200, because shared imports are counted once.
The model captures two real bundler behaviors: server components contribute nothing and shared client dependencies deduplicate.
Exercise 6Interview
Interview question: a product page has poor LCP and INP scores. Walk through your investigation and the fixes you would apply in an App Router codebase, in priority order.
Reveal the reference answer
reference.textInvestigate first: field data (real users) over lab data, then a performance profile to classify the bottleneck as backend, network or JavaScript. For LCP: make the LCP element an Image with priority, stream the shell fast with Suspense so the element renders early, and cache the data it depends on so the server responds quickly. For INP: profile the main thread during interaction, move non-interactive rendering back to server components to shrink hydration and script cost, split heavy client subtrees with dynamic imports, and defer non-critical work out of the input path. Structural fixes (boundary placement, caching, streaming) come before micro-optimizations because they change the cost model rather than shaving constants.Authored expected output: A measure-first answer that separates LCP work (priority image, streaming, cached data) from INP work (smaller client tree, deferred work) and prioritizes structural fixes.
Strong answers tie each metric to its dominant cost and to the App Router mechanism that addresses it.
Common misconceptions
#- Dynamic imports are the first tool to reach for. Boundary placement comes first: a wrongly placed 'use client' costs more than any import trick saves.
- Turbopack changes what code ships to the browser. It is the bundler for dev and build; bundle composition is still determined by your boundaries and imports.
Follow-up practice
#- nextjs-testing-debugging
- nextjs-deployment-capstone
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.