completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Next.js performance

Measure what next/image, next/font, next/script, caching and the client boundary change on a real Next.js page, then read its bundle and field data.

By the end, you can
  • 01
    Measure what the components changeCompare next/image, next/font and next/script with the plain way, in LCP, CLS and how soon a tap works.
  • 02
    Put the right parts in the first bytesCache the data every visitor shares, stream the rest, and keep "use client" on the parts that answer clicks.
  • 03
    Check the bundle and the fieldRead a route's browser JavaScript with next analyze, and collect real visitors' numbers with Speed Insights or useReportWebVitals.

Ravi's shop moves to Next.js

Module 36 looks at this course's ideas through each framework's own tools. Lesson 36.1 did React. This lesson does Next.js, the framework built on React.

Ravi's Mint tea page has grown. It has a big photo, the tea's details and 200 reviews. A bar at the bottom holds the price and Add to cart. The text is in Lora, a Google font. A chat widget sits in the corner. Ravi wants a framework to do more of the work, so he moves his shop to Next.js.

He moves it in a weekend, and keeps his old habits. The photo is a plain img. Lora comes from a font link. The chat script loads the default way. One line at the top makes the whole page run in the browser too. And the tea comes fresh from his shop's API, the server that knows his teas, on every visit.

Asha opens the page on her phone. At first she sees only a loading line and the green footer. Then the tea appears, and the footer jumps away. She taps Add to cart, and for a while nothing happens. So Ravi learns Next.js's own tools, and tries again. Here are real frames of both visits:

Real frames of the Mint tea page on Asha's phone. Ported page: at 398 ms, only "Loading Mint tea…" and the footer; still the same at 728 ms; at 817 ms, the photo, the name and the buy bar, with the footer pushed off the screen. Tuned page: at 560.9 ms, the name, the stock and the buy bar, in a stand-in font, with an empty space kept for the photo; at 614.9 ms, the photo, and the text in Lora; at 1,715.9 ms, the chat bubble.Ported398 msThe header, the words Loading Mint tea, and the green footera loading line728 msThe same loading line and footer, with the text now in Lorastill loading817 msThe photo of the mint tea, its name, rating, stock and details, and the buy barthe tea, a jumpTuned560.9 msAn empty space at the top, then the name, rating, stock, details and buy bar in a plain serif fontspace for the photo614.9 msThe photo of the mint tea above the same text, now in Lorathe photo, Lora1,715.9 msThe same page with an orange chat bubble over Add to cartthe chat bubble
Real frames from the course's recording, in ms after Asha asked for the page. The ported page showed a loading line first, then jumped. The tuned page showed the tea in its first frame, with the photo's space kept. Chrome's LCP counts the tuned photo at 564 ms, the paint it was first drawn in; its pixels reached the screen in the next frame.

So Next.js didn't make the page fast by itself. Its tools did, once Ravi used them well. But which tool changed which number? The course built the page nine ways to find out. First, the two ends:

The ported page and the tuned pagePop out in the code editor (opens in a new tab)JavaScript
// Asha opens Ravi's Mint tea page on her phone, two ways.// Times are in milliseconds (ms) after she asked for the page.const ported = { lcp: 816, cls: 0.1787, cartWorked: 1213.7 };const tuned = { lcp: 564, cls: 0, cartWorked: 864.5 }; console.log(`The photo appeared at ${ported.lcp} ms, then ${tuned.lcp} ms.`);console.log(`The page jumped by ${ported.cls}, then ${tuned.cls}.`);console.log(`Add to cart first worked at ${ported.cartWorked} ms, then ${tuned.cartWorked} ms.`);
  • Lines 1 and 2 are comments. A millisecond (ms) is a thousandth of a second.
  • Line 3 holds three numbers for the ported page. lcp is LCP, Largest Contentful Paint: when the biggest thing on the screen appeared. Here, that's the photo (lesson 17.1). cls is CLS, Cumulative Layout Shift. It adds up how much the page jumped (lesson 30.1). cartWorked is when Asha's tap first changed the cart.
  • Line 4 holds the same three numbers for the tuned page.
  • Lines 6 to 8 print The photo appeared at 816 ms, then 564 ms., The page jumped by 0.1787, then 0. and Add to cart first worked at 1213.7 ms, then 864.5 ms.

Every number got better. A good LCP is 2.5 seconds or less, and a good CLS is 0.1 or less (lesson 3.1). So the ported page failed CLS, even on a fast phone line. Why it matters: moving to a framework changes little on its own. What you tell its tools changes a lot.

Real-life analogyA new kitchen

Ravi's friend moves her café into a new kitchen. It has a fast oven, a timer and a warming shelf. But she cooks the way she did at home: every dish from scratch, one at a time. The food comes out no faster. The tools help only once she tells them what each dish needs.

In real life: The new kitchen
In Next.js: Next.js
In real life: Its fast oven, its timer and its warming shelf
In Next.js: next/image, next/script and use cache
In real life: Cooking the old way in it
In Next.js: The ported page
In real life: Telling each tool what the dish needs
In Next.js: sizes, a script strategy, a cache life
The main idea

Next.js's tools work best when you tell them what the page needs. How wide does the photo show? Which script can wait? Which data is the same for every visitor? Which parts answer clicks? Answer those, and the numbers follow.

How the course recorded it

  • Ravi's page: Next.js 16.4.3, built with next build and served with next start. That's the server a real shop runs, not the one for writing code.
  • Nine versions: the ported page, the tuned page, and seven more. Each of the seven is the tuned page with one thing changed back.
  • Asha's phone: Chrome 157, a screen 412 by 823 pixels, and the CPU 4 times slower. The course's own server played a Fast 4G line: 165 ms before each answer starts, then 8.1 megabits a second, as in lessons 35.1 to 35.3.
  • The helpers: Ravi's API is a stand-in that answers after 250 ms. The chat widget is lesson 24.1's stand-in. It works for 260 ms to set itself up, then 180 ms to draw its bubble.
  • Two kinds of visits: watched visits have no taps, for LCP and CLS. In tap visits, a mouse clicks Add to cart every 50 ms, from the moment it appears until the cart changes. Each version had 5 visits of each kind, taking turns. The lesson quotes the middle one.
  • One limit: before each click, the course asked Chrome where the button was. That question waits for the page's main thread. So a click could land a little later than a finger would.

Pick a version to see all its numbers. Each section below explains a few of them.

Playground: nine versions of the Mint tea page
Ported: Asha's visit
  1. First byte170.5 ms
  2. First paint400 ms
  3. LCP, the photo816 ms
  4. CLS0.1787
  5. Photo filemint-tea.jpg, 102.8 kB
  6. Lora arrived656.8 ms
  7. JavaScript152.2 kB in 7 files
  8. Stock shown454 ms
  9. Chat bubble shown1,465.6 ms
  10. Add to cart first worked1,213.7 ms
  11. Slowest tap328 ms
Try it yourself
Ported: Ravi's habits from before Next.js, all at once.

The first frame came at 400 ms, with only "Loading Mint tea…" and the footer. The tea arrived later, the footer jumped down, and the photo showed at 816 ms.

From the course's recording in Chrome 157, with the CPU slowed 4 times on an imitated Fast 4G line: times in ms after Asha asked for the page, from the middle of 5 visits. JavaScript is what went over the network, compressed.

next/image: the right file, early

The Next.js course shows how next/image works, in Optimizing images. Lessons 18.2 and 18.3 did the same jobs by hand. Here we measure what it changed on Ravi's page. The photo line came three ways:

The photo, three waysJSX
// 1. The plain img Ravi used before Next.js<img className="hero" src="/mint-tea.jpg" alt="A cup of mint tea" /> // 2. next/image as it comes<Image className="hero" src={mintTea} alt="A cup of mint tea" /> // 3. next/image, told how wide the photo shows, and asked to preload it<Image className="hero" src={mintTea} alt="A cup of mint tea" sizes="(max-width: 640px) 100vw, 640px" preload />
  • Line 2 is the plain img from Ravi's old shop. It points at one file, 1,600 pixels wide.
  • Line 5 is next/image as it comes. mintTea is the photo, imported as a file. So Next.js knows its width and height.
  • Line 8 adds two things. sizes tells the browser how wide the photo shows: the whole screen, up to 640 pixels. preload asks Next.js to start the photo early.

With sizes, Next.js offers the photo at eight widths, from 640 to 3,840 pixels (image-config.ts, line 238). The browser picks one, like picking a print that fills your frame. Which one does Asha's phone pick?

Which width does Asha's phone pick?Pop out in the code editor (opens in a new tab)JavaScript
// The widths Next.js wrote into the photo's srcset, because of sizes.const widths = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];// On Asha's phone the photo is the screen's width: 412 CSS pixels,// and each CSS pixel is 1.75 of the screen's own pixels.const needed = 412 * 1.75;const picked = widths.find((width) => width >= needed);console.log(`Needed ${needed} pixels; picked w=${picked}`);
  • Line 1 is a comment. Line 2 lists the eight widths Next.js offered.
  • Lines 3 and 4 are comments. Asha's screen is 412 CSS pixels wide. Each CSS pixel is 1.75 of the screen's own pixels.
  • Line 5 works out how many of those the photo needs.
  • Line 6 takes the first width that covers it. That's a simple form of the browser's choice.
  • Line 7 prints Needed 721 pixels; picked w=750.

The recording agrees: Chrome asked for w=750. Here is the photo on all three pages:

The photo on Asha's phone, three waysPop out in the code editor (opens in a new tab)JavaScript
// The photo on Asha's phone, three ways. Times in ms.const photos = [  { way: "Plain img", file: "mint-tea.jpg", bytes: 102809, asked: 179.4, lcp: 736 },  { way: "Lazy image", file: "w=3840", bytes: 22856, asked: 553, lcp: 808 },  { way: "Tuned", file: "w=750", bytes: 4810, asked: 181.5, lcp: 564 },]; for (const photo of photos)  console.log(`${photo.way}: ${photo.file}, ${(photo.bytes / 1000).toFixed(1)} kB, asked for at ${photo.asked} ms, LCP ${photo.lcp} ms`);
  • Lines 2 to 6 hold one row for each way: the file Chrome asked for, its size in bytes, when Chrome asked for it, and LCP.
  • Lines 8 and 9 print one line for each way. First, Plain img: mint-tea.jpg, 102.8 kB, asked for at 179.4 ms, LCP 736 ms. Then Lazy image: w=3840, 22.9 kB, asked for at 553 ms, LCP 808 ms. Last, Tuned: w=750, 4.8 kB, asked for at 181.5 ms, LCP 564 ms.

The plain img sent the whole JPEG: 102.8 kB. Chrome found it early, because it was in the page's first bytes. But all those bytes took time, and the photo showed at 736 ms.

next/image as it comes was later still. Its photo is lazy: Chrome waits until it has laid out the page and sees the photo near the screen. So it asked at 553 ms. And with no sizes, Next.js offered just two files: one for screens with 1 pixel per CSS pixel, one for 2 (get-img-props.ts, lines 185 to 200). Asha's phone took the bigger one, w=3840. What came back was the photo at its own width, 1,600 pixels, as WebP: 22.9 kB.

The tuned photo had both fixes. Chrome asked for w=750 at 181.5 ms. It was 4.8 kB, and it showed at 564 ms, in the very first paint. Why it matters: next/image as it comes is lazy, so turn that off for the photo at the top. And give it sizes, or a phone may get a file made for a big screen.

What preload does, and when you need it

In Next.js 16, preload took over from priority, which still works but is deprecated. In the App Router, preload does two things. It turns off lazy loading (get-img-props.ts, lines 425 to 428). And it adds a preload link for the photo to the page's head (image-component.tsx, lines 337 and 338).

But look at the plain img again. Chrome asked for it at 179.4 ms, with no preload at all. The photo was in the first bytes, so Chrome's preload scanner found it (lesson 17.3). On this page, preload's real job was to turn off lazy. The Image docs say that in most cases, loading="eager" or fetchPriority="high" is the better way. Keep preload for a photo the browser would find late.

In development, Next.js even warns you. If a lazy image turns out to be the LCP element, it asks you to add loading="eager" (get-img-props.ts, lines 634 to 668, inside a block that runs only in development).

None of the three pages jumped. next/image always writes the photo's width and height, so the browser keeps its space. You can see that empty space in the tuned page's first frame, above. The plain img had no size written. It didn't jump here, because its first bytes, which hold its size, came before the first paint. On a slower line, it could.

next/font: Lora from Ravi's own site

Lessons 20.2 and 20.3 loaded fonts by hand. They preloaded the file, and gave the fallback font Lora's size. The Next.js course's Optimizing fonts shows next/font doing both. Here is all of Ravi's font code:

app/fonts.tsTypeScript
import { Lora } from "next/font/google";

export const lora = Lora({ subsets: ["latin"] });
  • Line 1 imports Lora from next/font/google.
  • Line 3 asks for its Latin letters. When Ravi runs next build, Next.js downloads Lora's files. They are then served from his own site, not from Google.

The Font docs add two defaults. next/font preloads the file. And it makes a fallback font sized like Lora, to cut layout shift. The font-link version did it the old way:

The font-link layout's headHTML
<html lang="en">  <head>    <link rel="stylesheet" href="https://fonts.example/css2?family=Lora:wght@400..700&display=swap" />  </head>  <body className="lora">
  • Line 3 links a stylesheet on another site, fonts.example. It stands in for Google Fonts. The stylesheet says where Lora's file is. So Chrome learns about the file only after the stylesheet arrives.
  • Line 5 puts the page's text in Lora.
Lora's file on Asha's phone, two waysPop out in the code editor (opens in a new tab)JavaScript
// Lora's file on Asha's phone, two ways. Times in ms.const fonts = {  "next/font": { asked: 178.8, arrived: 468.9, frameWaited: 109, cls: 0 },  "font link": { asked: 362.2, arrived: 649, frameWaited: 7.6, cls: 0.0003 },}; for (const [way, font] of Object.entries(fonts)) {  console.log(`${way}: asked for at ${font.asked} ms, arrived at ${font.arrived} ms`);  console.log(`  the first frame waited ${font.frameWaited} ms; CLS ${font.cls}`);}
  • Lines 2 to 5 hold, for each way: when Chrome asked for Lora's file, when it arrived, how long the first frame waited, and CLS.
  • Lines 7 to 10 print next/font: asked for at 178.8 ms, arrived at 468.9 ms and the first frame waited 109 ms; CLS 0. Then font link: asked for at 362.2 ms, arrived at 649 ms and the first frame waited 7.6 ms; CLS 0.0003.

next/font asked for Lora 183.4 ms sooner. There was no second site to reach, and the file was preloaded. The font-link page moved a tiny bit when Lora arrived: CLS 0.0003. With next/font, nothing moved. A sized fallback is like a stand-in actor of the same height: when the star arrives, nobody on stage has to move.

But look at the first frame. On the next/font page, it waited 109 ms. On the font-link page, it waited 7.6 ms. And the font-link page painted first: at 464 ms, against 564 ms.

Why? A font preload is a promise: "this font is needed for the first paint." Chrome keeps that promise. If a font preload is in the head, Chrome holds the first paint for it (render_blocking_resource_manager.cc, lines 68 to 76). Once only fonts are left to wait for, it waits at most 100 ms more (lines 262 to 269). And never past 1.5 seconds after the visit starts (document_loader.cc, lines 3910 and 3911).

Lora came a moment too late, so the first frame used the sized fallback. Lora took over in the next frame, and nothing moved. Every next/font version waited about 100 to 110 ms. The font-link versions waited less than 10 ms.

Why it matters: next/font trades up to 100 ms of first paint for text that never jumps, and for no request to another site. For the main body font, that's usually worth it. For a font used only lower down, its preload option can be turned off.

next/script: when the chat widget runs

First, one word you'll need. When a page arrives, its HTML can't answer clicks yet. React runs the page's interactive parts again in the browser, and attaches their click handlers. That's hydration (lesson 35.3). Until it's done, Add to cart looks ready but does nothing.

Lesson 24.2 loaded other sites' scripts by hand. Next.js gives each script a strategy instead. The Next.js course's Scripts and third-party code shows each one. Ravi's chat widget came three ways:

The chat widget, three waysJSX
// In the root layout, after the page
<Script src="https://chat.example/widget.js" strategy="beforeInteractive" />
<Script src="https://chat.example/widget.js" strategy="afterInteractive" />
<Script src="https://chat.example/widget.js" strategy="lazyOnload" />
  • Line 2 is beforeInteractive. The docs say it loads before any Next.js code, and before hydration.
  • Line 3 is afterInteractive, the default. It loads after some of the page is hydrated.
  • Line 4 is lazyOnload. It loads when the browser has nothing else to do.
Asha's taps on three pagesPop out in the code editor (opens in a new tab)JavaScript
// Asha taps Add to cart from the moment she sees it. Times in ms.const pages = [  { strategy: "beforeInteractive", cartWorked: 1351.6, slowestTap: 360 },  { strategy: "afterInteractive", cartWorked: 1156.5, slowestTap: 272 },  { strategy: "lazyOnload", cartWorked: 864.5, slowestTap: 32 },]; for (const page of pages)  console.log(`${page.strategy}: the cart worked at ${page.cartWorked} ms; slowest tap ${page.slowestTap} ms`);
  • Lines 2 to 6 hold each page: when the cart first worked, and the slowest tap. With fewer than 50 taps, the slowest tap is the visit's INP, Interaction to Next Paint (lesson 26.1). A good INP is 200 ms or less.
  • Lines 8 and 9 print one line for each page. First, beforeInteractive: the cart worked at 1351.6 ms; slowest tap 360 ms. Then afterInteractive: the cart worked at 1156.5 ms; slowest tap 272 ms. Last, lazyOnload: the cart worked at 864.5 ms; slowest tap 32 ms.

The photo didn't care: LCP was 572 ms, 580 ms and 564 ms. Asha's taps did. Here is the main thread on each page while she tapped:

The main thread's long tasks while Asha tapped Add to cart, from 400 to 1800 ms, to scale. beforeInteractive: from 468.1 ms for 98.8 ms, the chat widget from 655.1 ms for 263 ms, from 918.1 ms for 95.6 ms, the chat widget from 1,133 ms for 180.9 ms; Add to cart first worked at 1,351.6 ms. afterInteractive: from 468.5 ms for 97 ms, from 569.6 ms for 52.8 ms, from 644.3 ms for 111.8 ms, the chat widget from 862.4 ms for 262.8 ms, the chat widget from 1,294.6 ms for 182.4 ms; Add to cart first worked at 1,156.5 ms. lazyOnload: from 463 ms for 92.8 ms, from 560.8 ms for 51.4 ms, from 617.8 ms for 109.2 ms, the chat widget from 1,136.8 ms for 263.4 ms, the chat widget from 1,570.7 ms for 181 ms; Add to cart first worked at 864.5 ms.beforeInteractivecart works, 1,351.6 ms ↑afterInteractivecart works, 1,156.5 ms ↑lazyOnload↑ cart works, 864.5 ms400 ms1,800 ms
From Chrome's trace of each page's middle click visit, to scale. Each bar is a task of 50 ms or more. Shaded bars are the chat widget: setting itself up, then drawing its bubble. The ↑ marks when Asha's tap first changed the cart.

With beforeInteractive, the cart worked at 1,351.6 ms. The docs say these scripts don't hold up hydration while they run. In Next.js 16.4.3, the code does wait. Its startup code loads them one after another. It starts React only once the last one has loaded (app-bootstrap.ts, lines 18 to 81). In the trace, React started in the same long task as the widget, right after it.

With afterInteractive, Next.js adds the script once React has hydrated the page (script.tsx, lines 259 to 271). It also asks for the file early (lines 361 to 376). So the widget ran at 862.4 ms, right while Asha was tapping. One tap waited 245.2 ms behind it, and took 272 ms in all. The ported page used this default too. Its slowest tap waited 248.2 ms behind the widget.

With lazyOnload, Next.js waits for the page's load event, then for an idle moment (script.tsx, lines 169 to 177). The widget ran at 1,136.8 ms. By then, the cart had already worked, at 864.5 ms.

The cost is the chat bubble. In the watched visits, it appeared at 1,261.4 ms with beforeInteractive, and at 1,708.9 ms with lazyOnload. Why it matters: a strategy decides whose turn comes first. Asha came to buy tea, not to chat. The docs even list chat widgets as a use for lazyOnload.

Real-life analogyDeliveries at lunchtime

A café gets a big delivery every day. If the café won't open until it's unpacked, the first customers wait outside. If the van comes just after opening, boxes block the counter in the lunch rush. If it comes in the quiet afternoon, nobody waits.

In real life: The big daily delivery
In Next.js: The chat widget's script
In real life: Opening only once it's unpacked
In Next.js: beforeInteractive
In real life: Unpacking it in the lunch rush
In Next.js: afterInteractive
In real life: Unpacking it in the quiet afternoon
In Next.js: lazyOnload

Cache Components: what the first bytes hold

The Next.js course explains Cache Components and Partial Prerendering in depth. Lesson 35.2 measured streaming by hand. Here is the short version.

When Ravi runs next build, Next.js renders each page ahead of time, as far as it can. That part is the shell. It's saved as HTML, and sent at once on every visit. Anything that must be fresh streams in after it, in the same answer. That's Partial Prerendering, or PPR.

How far can the shell go? It stops at data that must be fetched for each visit. The tea is the same for everyone, so Ravi caches it:

lib/shop.ts: the tea, cachedTypeScript
import { cacheLife } from "next/cache"; export async function getTea(): Promise<Tea> {  "use cache";  cacheLife("hours");  return fetchTea();}
  • Line 1 imports cacheLife.
  • Line 3 starts getTea, which returns the tea.
  • Line 4, "use cache", tells Next.js to keep what this function returns. Later visits get the kept copy.
  • Line 5 says how long to keep it: the hours profile.
  • Line 6 fetches the tea from Ravi's API. It runs only when there's no kept copy.
The tuned pageTSX
import { Suspense } from "react";import Image from "next/image";import { MintTea } from "@/app/ui/mint-tea";import { Stock } from "@/app/ui/stock";import { getTea } from "@/lib/shop";import mintTea from "@/app/mint-tea.jpg"; export default async function Page() {  const tea = await getTea();  const photo = <Image className="hero" src={mintTea} alt="A cup of mint tea" sizes="(max-width: 640px) 100vw, 640px" preload />;  const stock = (    <Suspense fallback={<p className="stock">Checking stock…</p>}>      <Stock />    </Suspense>  );  return <MintTea tea={tea} photo={photo} stock={stock} />;}
  • Line 9 gets the tea from the cache. So when Ravi builds, the tea's name, price and photo go into the shell.
  • Line 10 is the photo, as in the images section.
  • Lines 11 to 15 wrap Stock in Suspense. Stock asks the API for today's stock on every visit. Its fallback, Checking stock…, goes in the shell. The real stock streams in after.
  • Line 16 draws the page.

The fresh page fetched both on every visit, inside one Suspense:

The fresh pageTSX
import { Suspense } from "react";import Image from "next/image";import { MintTea } from "@/app/ui/mint-tea";import { fetchTea, getStock } from "@/lib/shop";import mintTea from "@/app/mint-tea.jpg"; export default function Page() {  return (    <Suspense fallback={<p className="loading">Loading Mint tea…</p>}>      <FreshMintTea />    </Suspense>  );} async function FreshMintTea() {  const [tea, boxes] = await Promise.all([fetchTea(), getStock()]);  const photo = <Image className="hero" src={mintTea} alt="A cup of mint tea" sizes="(max-width: 640px) 100vw, 640px" preload />;  return <MintTea tea={tea} photo={photo} stock={<p className="stock">In stock: {boxes} boxes</p>} />;}
  • Lines 9 to 11 put the whole tea in one Suspense. Its fallback is a loading line.
  • Line 16 fetches the tea and the stock, fresh, for each visit.

Here is what next build printed for the two pages:

next build's route table, two linesText
Route (app)         Revalidate  Expire
├ ◐ /fresh
└ ◐ /tuned                  1h      1d

◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content
  • Lines 2 and 3 both show ◐, Partial Prerender. Next.js made a shell for each page. The symbol says a shell exists. It doesn't say what's in it.
  • Only /tuned has times, from its cacheLife. After 1 hour, a visit still gets the kept tea, while Next.js fetches a fresh copy in the background. After 1 day with no fresh copy, a visit waits for one.
The tuned page and the fresh pagePop out in the code editor (opens in a new tab)JavaScript
// The tuned page and the fresh page, on Asha's phone. Times in ms.const tuned = { ttfb: 169.1, firstPaint: 564, lcp: 564, teaAskedPerVisit: 0 };const fresh = { ttfb: 168.8, firstPaint: 492, lcp: 848, teaAskedPerVisit: 1 }; console.log(`First byte: ${tuned.ttfb} ms and ${fresh.ttfb} ms`);console.log(`First paint: ${tuned.firstPaint} ms and ${fresh.firstPaint} ms`);console.log(`LCP: ${tuned.lcp} ms and ${fresh.lcp} ms`);console.log(`Times Ravi's API was asked for the tea, per visit: ${tuned.teaAskedPerVisit} and ${fresh.teaAskedPerVisit}`);
  • Lines 2 and 3 hold each page's first byte, first paint and LCP, and how often each visit asked Ravi's API for the tea.
  • Lines 5 to 8 print First byte: 169.1 ms and 168.8 ms and First paint: 564 ms and 492 ms. Then they print LCP: 564 ms and 848 ms and Times Ravi's API was asked for the tea, per visit: 0 and 1.
What the first bytes held. Tuned page, at 169.1 ms: Header and cart, Photo, Mint tea, rating, Checking stock…, About, reviews, Price, Add to cart; then In stock: 12 boxes, streamed in at 462.3 ms; first paint 564 ms, LCP 564 ms. Fresh page, at 168.8 ms: Header and cart, Loading Mint tea…, Footer; then The tea, photo and stock, streamed in at 452.9 ms; first paint 492 ms, LCP 848 ms.Tuned: the tea is cachedFirst bytes, 169.1 msHeader and cartPhotoMint tea, ratingChecking stock…About, reviewsPrice, Add to cartIn stock: 12 boxesStreamed in at 462.3 msFirst paint 564 ms, LCP 564 msFresh: fetched per visitFirst bytes, 168.8 msHeader and cartLoading Mint tea…FooterThe tea, photo and stockStreamed in at 452.9 msFirst paint 492 ms, LCP 848 ms
Plain cards were in the prerendered shell, the first bytes of the answer. Shaded cards came later in the same answer, once Ravi's API had answered. Both shells arrived at the same moment. Only the tuned one held the tea.

Both first bytes came at the same moment. Both servers sent a ready shell at once. But only the tuned shell held the tea. So its photo showed in the first paint. Ravi's API was asked for the tea once, while Ravi built the site. No visit asked again.

The fresh page painted sooner, at 492 ms. But that paint held only the loading line. The tea's part of the page had arrived by 452.9 ms, yet it showed only at 848 ms. Why so late?

React decides when streamed parts appear. It notes the moment the browser starts drawing the page's first frame. After that, it shows a streamed part no sooner than 300 ms later (ReactDOMFizzInstructionSetShared.js, lines 439 to 458). In 3 of 5 visits, that first frame began just before the tea was ready to show. So the tea waited, and the footer jumped when it showed: CLS 0.1786. In the others, the tea won the race and was in the first frame.

The ported page had the same problem. Its first frame held only the loading line, and its footer jumped when the tea showed. Why it matters: a fast first byte isn't a fast page. What counts is what the first bytes hold. Cache what every visitor shares, and stream only what must be fresh.

Real-life analogyLunch boxes packed before opening

A sandwich shop packs its lunch boxes before it opens. At noon, you get one the moment you ask. Only the soup is ladled fresh. A shop that makes every box from scratch hands you a ticket first: "Your order is being made." The ticket comes fast. Lunch doesn't.

In real life: Packing lunch boxes before opening
In Next.js: Prerendering the shell at build time
In real life: Handing one over the moment you ask
In Next.js: Sending the shell on every visit
In real life: Today's soup, ladled fresh
In Next.js: The stock, streamed inside Suspense
In real life: "Your order is being made"
In Next.js: A loading line as the whole shell

Server and client components: where the boundary goes

Lesson 35.3 met React Server Components. They run only on the server, and send their result, not their code. In Next.js, pages and layouts are Server Components unless you say otherwise.

A file that starts with "use client" holds Client Components. Their code goes to the browser too, and hydration runs them again there. The docs add a rule that matters here: once a file has "use client", everything it imports goes to the browser as well.

On the tuned page, only the cart's parts are client code: the badge, the button, and the provider that holds the count. The client-page version changed one import. MintTea now came through this file:

app/ui/mint-tea-client.tsxTSX
"use client";

export { MintTea } from "./mint-tea";
  • Line 1 marks the file as client code.
  • Line 3 passes MintTea on, unchanged. But through this file, MintTea and all it imports become client code: the details, the reviews, and marked, the library that turns each review's Markdown into HTML.
The page's components, twice. Tuned: use client on the cart: Client Components CartProvider, CartBadge, AddToCart; JavaScript 143.5 kB, HTML 19.0 kB. Client page: use client on MintTea: Client Components CartProvider, CartBadge, MintTea, About, Reviews, marked, AddToCart; JavaScript 157.6 kB, HTML 15.6 kB.Tuned: use client on the cartRootLayoutCartProviderHeaderCartBadgePageMintTeaAboutReviews, markedAddToCartFooterJavaScript 143.5 kB, HTML 19.0 kBClient page: use client on MintTeaRootLayoutCartProviderHeaderCartBadgePageMintTeaAboutReviews, markedAddToCartFooterJavaScript 157.6 kB, HTML 15.6 kB
Each card is a component, under the one that draws it. Shaded cards are Client Components: their code goes to the browser, and React runs them there again. Sizes are what went over Asha's network, compressed.
The tuned page and the client pagePop out in the code editor (opens in a new tab)JavaScript
// Bytes over Asha's network (compressed), and when the cart first worked (ms).const tuned = { js: 143472, html: 18954, cartWorked: 864.5 };const clientPage = { js: 157618, html: 15634, cartWorked: 902.2 }; console.log(`JavaScript: ${tuned.js} bytes, then ${clientPage.js}`);console.log(`HTML: ${tuned.html} bytes, then ${clientPage.html}`);console.log(`Add to cart worked at ${tuned.cartWorked} ms, then ${clientPage.cartWorked} ms`);
  • Lines 2 and 3 hold each page's JavaScript and HTML, in bytes over the network, and when the cart first worked.
  • Lines 5 to 7 print JavaScript: 143472 bytes, then 157618, HTML: 18954 bytes, then 15634 and Add to cart worked at 864.5 ms, then 902.2 ms.

The browser got 14,146 more bytes of JavaScript: marked and the page's own parts. React also had more to run while hydrating. The cart worked 37.7 ms later.

The HTML got smaller, though. Next.js puts a second copy of the page in the HTML, for React: the RSC payload (lesson 35.3). The docs say it holds Server Components' results, and the props passed to Client Components. For the tuned page, that copy held the finished reviews. For the client page, it held only the tea's data, with each review still in Markdown. So the client page traded 3.3 kB of HTML for 14.1 kB of JavaScript, and the browser did the Markdown work.

Why it matters: here the cost was small, because marked is small. But the rule grows with your page. Put "use client" on the parts that answer clicks, and pass the rest in from the server. The docs say the same: mark your interactive components, not large parts of your UI. The Next.js course shows how, in Composing Server and Client Components.

Real-life analogyThe dish or the recipe

A restaurant can bring you a finished dish. Or it can bring the recipe, the food and a pan, so you cook it again at your table. That's heavier to carry and slower to eat. Most dishes should come finished. Only the sauce you mix yourself needs its own bottle.

In real life: A finished dish
In Next.js: A Server Component's result
In real life: The recipe, the food and a pan
In Next.js: A Client Component's code
In real life: Cooking it again at your table
In Next.js: Hydration
In real life: Only the sauce you mix yourself
In Next.js: "use client" only on the cart's parts

Reading the client JavaScript with next analyze

How would Ravi find marked in his JavaScript? Lesson 22.2 read bundles with an analyzer. The Next.js course's Shrinking the JavaScript bundle shows that next build's route table no longer lists sizes. Since 16.1, Next.js has its own analyzer for Turbopack, its bundler:

The analyzer, three waysShell
npx next analyze
npx next analyze --output --snapshot before
npx next analyze export --snapshot before > bundle-graph.jsonl
  • Line 1 builds the app and opens the analyzer in your browser. It draws each module as a box, sized by its bytes. You can pick a route, and click a module to see the chain of imports that brought it in.
  • Line 2 saves the analysis to .next/diagnostics/analyze instead, as a snapshot named before.
  • Line 3, new in 16.4, writes that snapshot out as JSON Lines, one record per line, for your own scripts. The course read it this way.

Pick a route to see what the analyzer found for the browser:

Playground: what next analyze lists for a route
/tuned: client modules
  1. next465.8 kB, 176.3 kB compressed
  2. [client-fs]261.0 kB, 261.0 kB compressed
  3. next/polyfills112.6 kB, 39.4 kB compressed
  4. [turbopack]10.1 kB, 4.6 kB compressed
  5. [next]4.0 kB, 1.5 kB compressed
  6. app/globals.css1.4 kB, 0.6 kB compressed
  7. @swc/helpers0.8 kB, 0.4 kB compressed
  8. app/ui/cart.tsx0.6 kB, 0.3 kB compressed
/tuned: why each file is there
  1. [next]app/(shop)/layout.tsx → app/fonts.ts → [next]
  2. app/globals.cssapp/(shop)/layout.tsx → app/globals.css
  3. app/ui/cart.tsxapp/(shop)/layout.tsx → app/ui/cart.tsx
Try it yourself
/tuned: 856.4 kB for the browser, before compression

Pick a route. The first list is each group of modules the analyzer found for the browser, by size on disk and compressed. The second list is the import chain that pulled each of Ravi's own files, or a package, into the route.

From next analyze --output on the course's build, read with next analyze export. Sizes in kB (1 kB is 1,000 bytes).

On every route, the biggest group is next: Next.js, with the React it ships. It's 176.3 kB compressed. next/polyfills is code for old browsers. The Supported Browsers docs say Next.js loads it only for browsers that need it, and Chrome didn't download it. [client-fs] isn't JavaScript at all. It's other files a route can ask for, like the photo. On /img-plain, which doesn't import the photo, it's smaller by exactly the photo's bytes.

On /client-page, marked shows up, with its chain: app/(shop)/client-page/page.tsx → app/ui/mint-tea-client.tsx → app/ui/mint-tea.tsx → app/ui/parts.tsx → marked. That chain is the answer to "why is this here?" It points straight at the file with "use client".

Why it matters: the analyzer measures the built files. Chrome measures what went over the network. Use the analyzer to find what's in a route, and why. Use Chrome to measure what it cost.

Real visitors: Speed Insights and useReportWebVitals

Every number so far came from one phone in a lab. Lesson 3.3 showed why real visitors' numbers can differ. Lesson 12.6 compared tools that collect them. Next.js gives you two ways. The Next.js course's Core Web Vitals lesson walks through the first one step by step.

useReportWebVitals: send them yourself

app/web-vitals.tsxTSX
"use client"; import { useReportWebVitals } from "next/web-vitals"; const send = (metric: { name: string; value: number }) => navigator.sendBeacon("/vitals", JSON.stringify(metric)); export function WebVitals() {  useReportWebVitals(send);  return null;}
  • Line 1 makes this a Client Component. The hook runs in the browser.
  • Line 3 imports the hook from next/web-vitals.
  • Line 5 sends each metric to Ravi's own /vitals address, with sendBeacon. That still works as the page closes. It sits outside the component on purpose. The docs warn that a new function each time can send the same data twice.
  • Line 8 calls the hook. Line 9 draws nothing.

Under the hood, the hook calls the web-vitals library for CLS, LCP, INP, FCP and TTFB (web-vitals.ts, lines 11 to 21). That's the library from lesson 12.1. The analytics guide puts it in its own small file, like this one. Then only this file and its imports become client code. That's the boundary rule again.

Speed Insights: let Vercel collect them

app/layout.tsx with Speed InsightsTSX
import { SpeedInsights } from "@vercel/speed-insights/next"; export default function RootLayout({ children }: { children: ReactNode }) {  return (    <html lang="en">      <body>        {children}        <SpeedInsights />      </body>    </html>  );}
  • Line 1 imports SpeedInsights from Vercel's package.
  • Line 8 adds it to the root layout. It's a small wrapper around Vercel's tracking script.

On Vercel, its dashboard shows real visitors' numbers, at the 75th percentile by default. Its main number is the Real Experience Score, RES. Each metric gets a score from 0 to 100, and RES is a weighted average of them. The free plan shows RES. Speed Insights Plus adds every Core Web Vital, with breakdowns.

Vercel's docs add two things to know. Data comes from hard navigations: in a Next.js app, only the first page view in a session. And each visit sends up to five data points, at different moments. Exercise 6 asks which ones wait for the visitor to leave.

Here are your own numbers for this visit, read the same way:

Playground: this page's own vitals
This visit, measured in your browser
  1. Reading this page's entries…
Try it yourself
What a field tool would read on this visit

These are your own numbers, read live from this page with PerformanceObserver, the way useReportWebVitals and Speed Insights read them. Tap both buttons and watch the slowest tap. Reset forgets the taps; LCP and CLS belong to the whole visit.

Live in your browser. Slowest tap counts events of 16 ms or more, grouped by interaction, like INP with fewer than 50 interactions. CLS is the largest burst of layout shifts, as Chrome defines it.
Real-life analogyComment cards

A chef tastes each dish in a quiet kitchen. That helps, but it's one person on one afternoon. Comment cards from real diners tell her about the lunch rush and the cold table by the door. She can hand out the cards herself, or pay a service to collect and sort them.

In real life: The chef tasting in a quiet kitchen
In Next.js: The course's lab recording
In real life: Comment cards from real diners
In Next.js: Field data from real visitors
In real life: Collecting the cards yourself
In Next.js: useReportWebVitals
In real life: A service that collects and sorts them
In Next.js: Speed Insights

Which change fixed which number?

Read this table across. Each row is one version of the page, from its middle visits.

Nine versions of the Mint tea page
VersionWhat changedLCPCLSAdd to cart first workedSlowest tapJavaScript
PortedRavi's habits from before Next.js, all at once.816 ms0.17871,213.7 ms328 ms152.2 kB
TunedEvery tool used well.564 ms0864.5 ms32 ms143.5 kB
Plain imgThe photo is a plain <img>.736 ms0885 ms120 ms137.7 kB
Lazy imageThe photo is next/image with no sizes and no preload.808 ms0845.7 ms32 ms143.5 kB
Font linkLora comes from a Google-style stylesheet link.480 ms0.0003785.7 ms120 ms143.5 kB
BeforeThe chat script is beforeInteractive.572 ms01,351.6 ms360 ms143.5 kB
AfterThe chat script is afterInteractive.580 ms01,156.5 ms272 ms143.5 kB
Client pageThe whole page is a Client Component.576 ms0902.2 ms64 ms157.6 kB
FreshThe tea is fetched for every visit, inside one Suspense.848 ms0.1786856.8 ms24 ms143.5 kB

Three patterns stand out:

  • The photo: a lazy photo or a huge file made LCP later. next/image with sizes, and no lazy loading, fixed both.
  • The taps: the chat widget's timing decided when Add to cart worked.
  • The jumps: both pages that hid the tea behind one loading line jumped, by about 0.18.

Now sort these problems by the tool that fixes them:

Which tool fixes it?
  • A 1,600-pixel photo on a phone screen
  • A hero photo Chrome asks for only after it lays out the page
  • A font from another site, asked for after its stylesheet arrives
  • Text that changes size when the web font replaces the fallback
  • A chat widget whose setup blocks the first taps
  • A product page whose first bytes say only "Loading"
  • The same tea fetched from the API on every visit
  • A Markdown library in the browser's JavaScript
Try it yourself
0 of 8 correct

Sort each problem by the Next.js tool that fixes it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "Next.js makes a page fast by itself." No. The ported page ran on Next.js too. Its LCP was 816 ms, its CLS 0.1787, and the cart first worked at 1,213.7 ms.
  • "next/image always makes the photo load sooner." No. As it comes, it's lazy. Its LCP was 808 ms, later than the plain img's 736 ms.
  • "next/font makes the first paint sooner." No. Its preload held the first paint: 564 ms, against 464 ms with a font link. What it buys is text that doesn't jump.
  • "beforeInteractive never holds up hydration." No. In Next.js 16.4.3, React started only after the widget had loaded. The cart worked at 1,351.6 ms.
  • "A ◐ route shows the product in its first bytes." No. /fresh was ◐ too. Its shell held only a loading line.
  • "use client on a one-line file sends one line." No. It sent MintTea, the reviews and marked: 14.1 kB more JavaScript.

Practice exercises

Answer each one first, then open the hints if you need them.

Exercise 1 · Warm-upBen's phone

Ben's phone is 390 CSS pixels wide, with 3 of its own pixels for each. What does it print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
// The widths Next.js wrote into the photo's srcset, because of sizes.
const widths = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
// On Ben's phone the photo is the screen's width: 390 CSS pixels,
// and each CSS pixel is 3 of the screen's own pixels.
const needed = 390 * 3;
const picked = widths.find((width) => width >= needed);
console.log(`Needed ${needed} pixels; picked w=${picked}`);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upReady, but not working

    On the afterInteractive page, how long did Add to cart look ready before it worked? What does it print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    // The afterInteractive page, in ms after Asha asked for it.
    const shownAt = 567.2; // Add to cart appeared on her screen
    const worksAt = 1156.5; // the cart first changed
    
    console.log(`Asha waited ${Math.round((worksAt - shownAt) * 10) / 10} ms.`);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeThe stock on the font-link page

      On the font-link page, when was the stock shown, in ms? Why is it so much later than on the tuned page?

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeHow big is marked?

        On /client-page, how big is marked before compression, in kB?

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeReact starts inside the widget's task

          Open the course's trace of the beforeInteractive page in Chrome's DevTools. Its longest task starts by running the chat widget. Right after, in the same task, an event runs. How long does that event take, in ms?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeWhat Speed Insights sends last

            Vercel's docs list when Speed Insights sends each data point. Which metrics does it send when the visitor leaves the page?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask two things: what did the tool change, and what did it leave to Ravi?

              The Next.js performance quiz · 7 questionsScore: first tries count
              1. Question 1 of 7In the App Router, what does preload on next/image do?

                Choose an answer to see the explanation.

              2. Question 2 of 7Why did the recorded plain img page have no layout shift?

                Choose an answer to see the explanation.

              3. Question 3 of 7In the recording, why did the first paint come later on the next/font pages than on the font-link page?

                Choose an answer to see the explanation.

              4. Question 4 of 7What did beforeInteractive do to Asha's first taps on Add to cart?

                Choose an answer to see the explanation.

              5. Question 5 of 7The fresh page and the tuned page had the same time to first byte. Why was the fresh page's LCP later?

                Choose an answer to see the explanation.

              6. Question 6 of 7A file holds only "use client" and one line that exports MintTea from another file. What goes to the browser?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which visits does Speed Insights collect its data points from, in a Next.js app?

                Choose an answer to see the explanation.

              Key takeaways

              • Next.js didn't make Ravi's page fast by itself. Telling its tools what the page needs did.
              • next/image is lazy as it comes. Turn that off for the photo at the top, and give it sizes.
              • next/font serves the font from your own site with a sized fallback. Its preload can hold the first paint up to 100 ms.
              • A script's strategy decides whose turn comes first. lazyOnload let Add to cart work before the chat widget ran.
              • Cache what every visitor shares, so it goes in the shell. Stream only what must be fresh.
              • "use client" sends a file and all it imports. Keep it on the parts that answer clicks.
              • Find what's in a route with next analyze. Collect real visitors' numbers with useReportWebVitals or Speed Insights.

              Remember the one-liner.
              Next.js gives you the tools; you still choose the photo to load first, the script to delay, the data to cache and the boundary to keep small.

              Sources

              The facts on this page come from these docs and source files:

              Coming next: Angular performance. Change detection, signals and deferred views: the same questions, in another framework.

              CompleteFrontend Clear concepts. Working examples.