Lesson 24 of 27Production Next.js
Performance and Bundle Size in Next.js
Measure real users first, find the bytes with the bundle analyser, then fix LCP and INP by moving work to the server and loading less JavaScript.
The marketing team says the product page "feels slow on phones". You run Lighthouse on your laptop against next dev and get 96. Search Console disagrees: Largest Contentful Paint at the 75th percentile is 4.1 seconds on mobile, and Interaction to Next Paint is 380 ms. Both can be true, because they measure different things on different machines. Next.js gives you a fast default, but a single "use client" in the wrong file, a chat widget in the root layout or a charting library imported on every page can undo it. This lesson is about working like a senior engineer on performance: measure the right thing, find the cause with tools rather than guesses, and fix the cause rather than the symptom.
Measure first: field data and lab data
The Metadata and Images lesson introduced the three Core Web Vitals (LCP, INP, CLS) and their thresholds. Two kinds of measurement feed them, and you need both.
Field data (real user monitoring, RUM) comes from actual visitors on their actual devices and networks. Google's Chrome User Experience Report (CrUX) is field data, and it is what search ranking uses. Field data is reported at the 75th percentile: the value that 75% of page loads beat. A site is "good" when its p75 is under the threshold, so a fast median with a slow tail still fails.
Lab data comes from a controlled run: Lighthouse, the Chrome Performance panel, WebPageTest. It is repeatable and gives you a trace to dig into, which makes it the tool for diagnosing. But a lab run on a fast laptop on office Wi-Fi tells you little about a mid-range Android phone on a train. Lab tools also cannot measure INP properly, because there is no real user clicking; they report Total Blocking Time (TBT) as a stand-in.
Two rules follow. Never measure next dev: it compiles on demand, skips minification and adds dev-only checks. Measure next build && next start or a preview deployment. And let field data tell you which page and metric is a problem, then use lab tools to find why.
Collect your own field data with useReportWebVitals from next/web-vitals. Put it in a small Client Component rendered once from the root layout:
"use client";
import { useReportWebVitals } from "next/web-vitals";
export function WebVitals() {
useReportWebVitals((metric) => {
const body = JSON.stringify({
name: metric.name, // "LCP", "INP", "CLS", "FCP", "TTFB"
value: metric.value,
rating: metric.rating, // "good" | "needs-improvement" | "poor"
id: metric.id,
page: window.location.pathname,
});
navigator.sendBeacon?.("/api/vitals", body);
});
return null;
}sendBeacon survives the page being closed, which matters because LCP and INP are often reported as the user leaves. Group the results by route, not by URL, or /products/123 and /products/456 look like different pages.
Press Run (⌘ Enter) to see what happens.The median looks fine. The p75 does not, and p75 is what counts. The slow quarter of interactions are usually on slower phones, which is exactly where JavaScript cost hurts most.
Find the bytes: the bundle analyser
Most Next.js performance problems are JavaScript problems: too much of it downloaded, parsed and run on the main thread before the page responds. Before changing code, find out where the bytes come from.
Next.js 16.1 added a bundle analyser built into Turbopack. In 16.1 the command was next experimental-analyze; it is now next analyze (the old name still works as an alias):
npx next analyze # interactive treemap in the browsernpx next analyze --output # write the analysis to .next/diagnostics/analyzeThe treemap shows each module as a rectangle sized by its weight. Filter by route and by environment (client or server), then click a large module to see its import chain: the exact path of imports from your route to that file. That chain is the answer to "why is moment in my checkout page?" Usually it is something like app/layout.tsx → components/header.tsx ("use client") → lib/format.ts → moment. Save an analysis before and after a change (--output, plus a named snapshot from 16.4) so the pull request can show the difference. Projects still on webpack use the older @next/bundle-analyzer plugin.
Three things deserve attention first in any treemap:
- The shared chunk. Code imported by the root layout or a component used everywhere lands in JavaScript that every page downloads. One heavy import there costs every route.
- Single large libraries in client code: charting, rich text editors, maps, date libraries with all locales, syntax highlighters, Markdown parsers, animation libraries.
- Barrel imports.
import { Check } from "icons"can pull in thousands of icons if the package exports them from one index file. Next.js already optimises many popular packages automatically; for others, add them toexperimental.optimizePackageImportsinnext.config.ts.
Move work to the server
The single most effective tool you have in the App Router is the one you learned in Server and Client Components: code in a Server Component sends zero JavaScript to the browser. Only the rendered result is sent. Every performance review in Next.js starts with "does this need to run in the browser?"
The classic win is a library that only turns data into markup. A syntax highlighter in a Client Component ships the highlighter and its grammars to every visitor, just to produce a <pre> that never changes. Run it in a Server Component instead and the browser receives only HTML:
import { codeToHtml } from "shiki"; // runs on the server only
export async function CodeBlock({ code, lang }: { code: string; lang: string }) {
const html = await codeToHtml(code, { lang, theme: "github-dark" });
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}The same reasoning covers Markdown rendering, date formatting for display, sorting and filtering a list the user does not interact with, and charts that are only looked at (render them to SVG on the server).
Keep "use client" at the leaves. The directive marks a boundary: that file and everything it imports goes into the client bundle. Put it at the top of a layout or a big page component and you have opted the whole subtree out of Server Components. Push it down to the smallest interactive piece, such as the "Add to cart" button, not the product page.
Watch the RSC payload. Props you pass from a Server Component to a Client Component are serialised and sent to the browser, inside the streamed HTML as the RSC payload. Pass a full product catalogue of 5,000 rows to a client-side filter and you ship it as data, even though no JavaScript was added. Pass only the fields the component renders (a DTO, as in the Databases lesson), paginate, or do the filtering on the server through searchParams.
Server Components only contribute to the HTML. A highlighter or Markdown parser here costs the visitor nothing in JavaScript.
Load less up front: lazy loading
Some client code is genuinely needed, just not at first paint: a modal, an emoji picker, a rich text editor below the fold, a chart behind a tab. Split it out with next/dynamic so it becomes a separate chunk that downloads only when rendered:
"use client";
import { useState } from "react";
import dynamic from "next/dynamic";
const RevenueChart = dynamic(() => import("./revenue-chart"), {
ssr: false, // the chart library touches window; skip server prerendering
loading: () => <div className="h-72 animate-pulse bg-gray-100" />,
});
export function ReportPanel() {
const [open, setOpen] = useState(false);
return (
<section>
<button onClick={() => setOpen(true)}>Show revenue chart</button>
{open && <RevenueChart />}
</section>
);
}Three rules keep this correct. ssr: false is only allowed inside Client Components; using it in a Server Component is an error. Give the loading state the same height as the final component or you trade a bundle problem for a CLS problem. And for a library you only need inside an event handler (a CSV exporter, a PDF generator), skip the component entirely and await import("papaparse") inside the handler.
Do not lazy-load what is above the fold and visible immediately. Splitting the hero carousel just adds a second round trip before the LCP element can render.
Third-party scripts
Tag managers, analytics, chat widgets, A/B testing and consent banners are the most common cause of poor INP on otherwise well-built sites. They run on the main thread, they are written by someone else, and marketing can add more without a deploy. Load them through next/script with a deliberate strategy:
| Strategy | When it loads | Use for |
|---|---|---|
beforeInteractive | Before any Next.js code and hydration | Almost nothing: bot detection or consent that must run first |
afterInteractive (default) | Early, after some hydration | Analytics you need on every page view |
lazyOnload | During browser idle time | Chat widgets, social embeds, anything non-essential |
worker | In a web worker (Partytown) | Experimental, and not supported with the App Router |
For the Google family, @next/third-parties provides GoogleTagManager, GoogleAnalytics, YouTubeEmbed and GoogleMapsEmbed components that load efficiently (the YouTube embed, for example, uses a lightweight facade until the user interacts). The package is still labelled experimental. The most effective fix is often not technical: agree a script budget with the team that owns the tag manager, and measure INP before and after each new tag.
INP: keep the main thread free
INP measures the time from a user's input to the next frame being painted. Anything that keeps the main thread busy delays it: hydration of a big tree, a heavy re-render, a third-party script. The browser calls any task over 50 ms a long task, and Total Blocking Time adds up the part of each long task beyond 50 ms.
Press Run (⌘ Enter) to see what happens.Breaking a long task into smaller ones does not reduce the total work, but it gives the browser gaps to handle a click. That is the idea behind most INP fixes in a Next.js app:
- Hydrate less. Fewer and smaller Client Components mean less hydration work. This is the server-first rule again.
- Mark non-urgent updates as transitions. Wrapping a filter update in
startTransition(or rendering a slow list fromuseDeferredValue) lets React keep the input responsive and render the expensive part in interruptible chunks, as you saw in Transitions, Suspense and Deferred Values. - Do less per keystroke. Debounce searches, virtualise long lists (Performance in the React course covers this), and move heavy computation to a Web Worker.
- Turn on the React Compiler.
reactCompiler: trueinnext.config.ts(withbabel-plugin-react-compilerinstalled) memoises components and values automatically, which cuts wasted re-renders. It does not shrink your bundle and it will not fix a slow third-party script, so measure before and after.
What does this print?
const tasks = [40, 120, 55, 300, 10]; const tbt = tasks.filter((t) => t > 50).reduce((s, t) => s + (t - 50), 0); console.log(tbt);
LCP: fast server, early image
LCP is usually the hero image or the main heading. Its time breaks into four parts: time to first byte (TTFB), the delay before the browser discovers the LCP resource, the time to download it, and the time to render it. Fix the biggest part.
- TTFB. A page that waits on a slow database query before sending any HTML has a slow TTFB. With Cache Components the static shell is prerendered and sent immediately, while the slow parts stream inside
<Suspense>. Check the build output from Deploying Next.js: a route that drifted from◐toƒlost its static shell. - Discovery. Mark the hero image with
preloadonnext/image(in Next.js 16 this replaces the deprecatedpriorityprop) so the browser fetches it from the HTML head rather than after layout. Use it on one image per page, not ten. - Download. Correct
sizesso a phone does not download a 2,400 px desktop image, as covered in Metadata and Images. - Render delay. A Client Component that renders the hero only after hydration (or after a
useEffectfetch) delays LCP until the JavaScript has run. Render the LCP element on the server.
Match each finding to the fix that addresses its cause.
Keep it fast: budgets in CI
Performance regresses one reasonable-looking pull request at a time. Teams that keep a fast site make regressions visible:
- Save a bundle analysis on
mainand compare each pull request against it; fail or flag the build when a route's client JavaScript grows past an agreed budget. - Run Lighthouse CI (or a similar lab check) against the preview deployment for the three or four most important routes, with a fixed device profile so results are comparable.
- Watch field data on a dashboard by route after every release, because only field data shows what users feel.
Put a performance investigation in the order a senior engineer would run it.
- Tap the steps below in the right order.
- field data
- Performance measured from real visitors (RUM, CrUX), reported at the 75th percentile. What search ranking uses.
- lab data
- Performance measured in a controlled run such as Lighthouse. Repeatable and good for diagnosis, but not what users experience.
- p75
- The 75th percentile: the value that 75% of page loads or interactions beat. Core Web Vitals are judged on it.
- import chain
- The path of imports from a route to a module, shown by the bundle analyser to explain why code is in a bundle.
- long task
- Any main-thread task over 50 ms. Long tasks delay input handling and drive poor INP.
- RSC payload
- The serialised Server Component output, including props passed to Client Components, sent to the browser alongside the HTML.
- next/dynamic
- Lazy loading for Client Components: the component's code becomes a separate chunk loaded only when rendered.