The previous module ended with a confession: we've been trusting that AgendaViva is fast. There are reasons to believe it, because the shell is served without querying anything, the posters weigh just what they need to and the JavaScript is limited to a few islands. But "it should be fast" isn't a measurement, and the experience of whoever develops it, on a powerful computer with the server right next to them, has little in common with that of someone opening it on the bus.
The Core Web Vitals are three measurements of that experience: how long it takes for the important part to appear, how long it takes to respond when you tap, and how much the page moves while you're using it. In this lesson you'll learn what each one measures and with what thresholds, why you need both lab data and data from real visits, and how to diagnose each metric in a Next.js application. Along the way we'll settle several outstanding debts: the notice banner that pushes the page down, the session hole in the header and which home page card deserves priority.
- The metrics
| Metric | Question it answers | Good | Poor |
|---|---|---|---|
| LCP (Largest Contentful Paint) | When does the largest element on the first screen appear? | 2.5 s or less | More than 4 s |
| INP (Interaction to Next Paint) | How long does the screen take to react to a click, a tap or a key press? | 200 ms or less | More than 500 ms |
| CLS (Cumulative Layout Shift) | How much does the content move without anyone asking? | 0.1 or less | More than 0.25 |
These three are the Core Web Vitals. Two others don't count towards the score, but they help explain a poor LCP:
| Metric | What it measures | Reference |
|---|---|---|
| TTFB (Time to First Byte) | From when the page is requested until the first byte arrives | 0.8 s or less |
| FCP (First Contentful Paint) | When the first thing is painted, even if it's just a logo | 1.8 s or less |
The thresholds apply to the 75th percentile, separately on mobile and on desktop: a page is "good" if it's good for three out of four visits. The average is misleading, because lots of fast visits hide the quarter that suffers.
Each one has a subtlety worth knowing:
- LCP doesn't always pick the same element. On a phone it may be the
<h1>and on a monitor the first image. Images and blocks of text count; a background color doesn't. It stops being measured as soon as the person taps or scrolls. - INP looks at one of the worst interactions of the whole visit, not the first one. It includes the wait until the main thread is free, the execution of the handlers and the time until the result is painted.
- CLS isn't a time. It combines how much of the screen moved and how far. Shifts that happen right after an action by the person don't count: opening a dropdown isn't penalized.
1.1. Field and lab
| Lab | Field | |
|---|---|---|
| What it is | A simulated load, with fixed network and CPU | What the visitors' browsers measured |
| Tools | Lighthouse, DevTools Performance panel | CrUX, PageSpeed Insights, Search Console, your own collection |
| INP | No: nobody interacts. TBT (Total Blocking Time) is used as an approximation | Yes |
| Good for | Finding the cause and preventing regressions | Knowing whether there's a problem and for whom |
You need both. The field tells you what is wrong; the lab lets you repeat it until you know why. A Lighthouse score of 100 with a poor INP in the field isn't a contradiction: they measure different things.
- Measuring in the lab
Three rules before writing down a number:
- Production, always.
npm run build && npm run start. In development there's no prefetching, the code isn't minified and React performs extra checks. - No extensions, in an incognito window.
- With a warm cache and
QUERY_DELAY_MS=0. Otherwise you'll be measuring our fake latency.
npm run build && npm run start
npx lighthouse http://localhost:3000 --view # simulated mobile
npx lighthouse http://localhost:3000 --preset=desktop --view
npx lighthouse http://localhost:3000/events/jazz-night --viewRepeat each measurement three to five times and keep the median: there can be a ten-point difference between two runs without anything changing. The SEO score will come out low locally because of the X-Robots-Tag: noindex from 09-04; that's expected without ALLOW_INDEXING.
Lighthouse summarizes. To understand, open the browser tools' Performance panel, throttle the CPU to a quarter and the network to slow 4G, and record a reload. The track that tells you the most is the LCP one, split into four parts:
| LCP part | It's high if… | In Next.js it's usually |
|---|---|---|
| TTFB | The server is slow | Page without a shell, slow proxy, no CDN |
| Load delay | The resource is discovered late | Image with lazy loading, or inside a hole |
| Load duration | The resource is heavy | sizes set wrong |
| Render delay | It's there, but it isn't painted | Blocking JavaScript or CSS, or a Suspense boundary that hasn't been revealed yet |
- Measuring in the field
Once the site has enough visits, Search Console and PageSpeed Insights show the data Chrome collects. It's per domain or per group of pages, it arrives days late and it doesn't include other browsers. For our own data, Next.js offers a hook that hands each metric to the browser as soon as it's known:
// lib/metrics.ts — neutral, no dependencies
export const METRICS_PATH = '/api/metrics'
const FIXED_ROUTES = new Set([
'/', '/events', '/venues', '/my-bookings', '/account', '/sign-in', '/sign-up',
'/dashboard', '/dashboard/events', '/dashboard/events/new', '/admin',
])
const PATTERNS: [RegExp, string][] = [
[/^\/events\/[^/]+$/, '/events/[slug]'],
[/^\/venues\/[^/]+$/, '/venues/[slug]'],
[/^\/dashboard\/events\/[^/]+\/edit$/, '/dashboard/events/[id]/edit'],
]
// '/events/jazz-night' → '/events/[slug]'
export function routePattern(path: string): string {
if (FIXED_ROUTES.has(path)) return path
return PATTERNS.find(([shape]) => shape.test(path))?.[1] ?? 'other'
}// components/web-metrics.tsx
'use client'
import { useReportWebVitals } from 'next/web-vitals'
import { METRICS_PATH, routePattern } from '@/lib/metrics'
type OnMetric = Parameters<typeof useReportWebVitals>[0]
const SAMPLE_RATE = process.env.NODE_ENV === 'production' ? 0.2 : 1
let sampled: boolean | undefined // One decision per page load
const report: OnMetric = (metric) => {
sampled ??= Math.random() < SAMPLE_RATE
if (!sampled) return
const url = metric.navigationURL ?? window.location.href
const body = JSON.stringify({
name: metric.name,
value: metric.value,
rating: metric.rating,
navigation: metric.navigationType,
route: routePattern(new URL(url, window.location.href).pathname),
device: window.matchMedia('(pointer: coarse)').matches ? 'touch' : 'mouse',
})
navigator.sendBeacon(METRICS_PATH, new Blob([body], { type: 'application/json' }))
}
export function WebMetrics() {
useReportWebVitals(report)
return null
}- The function is outside the component. The hook subscribes again if the reference changes, and it would then duplicate the data. The documentation warns about this.
sendBeaconhands the request over to the browser and doesn't wait. It's essential: CLS and INP are known when the page is left, when an ordinaryfetchwould be canceled. Theconnect-src 'self'in our CSP allows it.- The pattern is sent, not the address.
/events/[slug]groups the event pages, which is what matters for making decisions, and it keeps identifiers or the/sign-up/confirmtoken from traveling. Anything unknown is grouped underother: otherwise, anyone could create as many categories as addresses they made up. Math.randomis called inside an effect, in the browser. In the component body it would be the prerendering error from 05-01.- One in five. A percentile doesn't need every visit, and the server is grateful.
navigationURLis the address the metric belongs to. Next.js also reports client-side navigations (navigationType: 'soft-navigation') in browsers that measure them, and by then the address bar may have changed.
The component goes in app/layout.tsx, inside the <body> and before <ThemeProvider>. It doesn't render anything, so it can't move anything. The receiver looks like the one for CSP reports (08-05):
// app/api/metrics/route.ts
import * as z from 'zod'
import { guarded } from '@/lib/api/responses'
import { readJson } from '@/lib/api/body'
const schema = z.strictObject({
name: z.enum(['LCP', 'INP', 'CLS', 'FCP', 'TTFB']),
value: z.number().min(0).max(600_000),
rating: z.enum(['good', 'needs-improvement', 'poor']),
navigation: z.string().max(40),
route: z.string().max(60).regex(/^[a-z0-9/[\]-]*$/),
device: z.enum(['touch', 'mouse']),
})
export async function POST(request: Request) {
return guarded(async () => {
const body = await readJson(request, schema)
if (!body.valid) return body.response
console.info('metric', JSON.stringify(body.data))
return new Response(null, { status: 204 })
})
}There's no cookie, no visit identifier and no stored IP address: these are anonymous measurements. Even so, note it in the privacy policy and ask whoever handles compliance whether anything else is needed.
We don't count the requests in PostgreSQL either, as we did with sign-ins. Every visit produces five of them, and recording them would cost more than handling them; the limit is set at the load balancer or the platform. And remember that anyone can send made-up numbers: the data is for spotting trends, not for billing.
For now the destination is the server log. In 10-05 it will become a structured log, from which a tool can calculate the 75th percentile per route and device.
- TTFB: the shell works in your favor
With Cache Components, the first byte of a ◐ route doesn't depend on any query: the shell is ready. If your TTFB is high, look in this order:
| Suspect | What it looks like | What to do |
|---|---|---|
| Distance | High TTFB only far from the server | A CDN in front that stores the shell (11-04) |
| The proxy | Every route in its matcher has the same delay |
Less work, timeouts. Ours makes an internal request on event pages (07-02) |
An ƒ page |
Symbol in the next build table |
Remove instant = false (05-01) |
| A redirect | Two requests in the network tab | Link to the final destination |
| The shell isn't stored | Erratic TTFB | CDN headers, or content that expires too soon |
A first byte that arrives early doesn't mean something useful arrives. A shell made of a giant skeleton has a magnificent TTFB and a dreadful LCP.
- LCP: what's largest and when it arrives
The first step is knowing which element it is. The Performance panel points it out, and so does the console:
// Paste it into the DevTools console and reload with "Preserve log"
new PerformanceObserver((list) => {
for (const { element, startTime, url } of list.getEntries()) {
console.log(Math.round(startTime), 'ms', element, url)
}
}).observe({ type: 'largest-contentful-paint', buffered: true })In AgendaViva:
| Page | Candidate | Where it is | Risk |
|---|---|---|---|
/ |
The <h1>, or the first card's poster |
Shell | The poster being lazy-loaded |
/events |
The <h1>, or the first card |
The title, in the shell; the cards, in a hole, because they depend on the URL | The hole being slow |
/events/[slug] |
The poster or the title | Shell on prerendered event pages (05-05) | Those outside the list start with the skeleton |
/venues |
Text | Depends on the hole | Low |
/dashboard/** |
Dashboard title | Shell | None that matters: they're returning users |
Which home page card deserves priority was left pending in 09-02. In a phone viewport, the first card with a poster fits on the first screen and is the LCP; on desktop, the first two fit. The answer is the first one, and only that one: giving priority to two splits the bandwidth at the moment it's scarcest.
// components/event-card.tsx
interface Props {
event: AgendaEvent & { venue?: VenueSummary }
isMain?: boolean
}
export function EventCard({ event, isMain = false }: Props) {
// … and in the poster
<EventPoster
image={event.image}
alt=""
sizes="(min-width: 64rem) 30rem, (min-width: 40rem) 50vw, 100vw"
isMain={isMain}
/>
// app/(public)/page.tsx (UpcomingEvents) and the /events list
{events.map((event, index) => (
<li key={event.id}>
<EventCard event={event} isMain={index === 0} />
</li>
))}The other lists (your district, related events) are further down: they stay as they were.
The rest of the recipe is already done, and it's worth seeing it as a checklist for other projects:
- The largest element, outside boundaries whenever possible (04-04). Every
<Suspense>above the LCP adds its query to it. - Cached content, in the shell. It's the biggest improvement we made:
UpcomingEventsstopped being a hole in 05-02. - Prerender the most visited event pages (05-05).
- Correct
sizes,loading="eager"andfetchPriority="high"on one image. - Self-hosted fonts with an adjusted fallback: the text is painted without waiting.
- Nothing blocking in the
<head>. Our only script is the theme one, small and inline.
- CLS: the three debts
To see the shifts, open Rendering in DevTools and enable Layout Shift Regions: every area that moves flashes. Reload with the network throttled. In AgendaViva you'll see three.
6.1. The notice banner
SiteNotice is a deliberate hole with fallback={null}, and it sits above everything. When there's a notice, it arrives a few tenths of a second later and pushes the entire page down: it's the worst possible case. We can't reserve height for it, because it almost never exists and an empty strip would be left behind. The solution is to put it where it doesn't push: at the end of the document, stuck to the bottom edge of the window.
// app/(public)/layout.tsx
export default function PublicLayout({ children }: LayoutProps<'/'>) {
return (
<>
<SkipToContent />
<Header />
<main id="content" tabIndex={-1} className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">
{children}
</main>
<Footer />
<Suspense fallback={null}>
<SiteNotice />
</Suspense>
</>
)
}
// components/site-notice.tsx (the <p>)
<p role="status" className="sticky bottom-0 bg-amber-100 px-4 py-2 text-center text-amber-950">With sticky bottom-0, the banner takes its place at the end of the page and, until you reach it, stays visible at the bottom. Nothing above it moves; on a page shorter than the window, only the footer rises a few pixels. So that it doesn't cover the element focused with the keyboard, add scroll-padding-bottom: 4rem to html in globals.css.
6.2. The session in the header
In 08-01 we reserved a fixed-width hole for AccountMenu, and in 08-04 we added role-based links to it. The content is now wider than the hole, and when it arrives it shifts whatever is next to it. On narrow screens it's worse: the bar wraps onto two lines and the whole page moves down.
// components/header.tsx (the container)
<div className="mx-auto flex max-w-5xl flex-wrap items-center gap-x-6 px-4">
<Link href="/" className="flex min-h-12 items-center text-xl font-bold text-accent">
{SITE_NAME}
</Link>
<nav aria-label="Main" className="order-last flex min-h-12 w-full items-center gap-6 sm:order-none sm:w-auto">
{/* … the links and "My bookings" … */}
<span className="inline-block min-w-10">
<Suspense fallback={null}>
<FavoritesCounter />
</Suspense>
</span>
</nav>
<ThemeSelect />
<div className="ml-auto flex min-h-12 w-44 items-center justify-end overflow-hidden">
<Suspense fallback={null}>
<AccountMenu />
</Suspense>
</div>
</div>
// components/account-menu.tsx: the name is truncated if it doesn't fit
<Link href="/my-bookings" className="max-w-20 truncate">{user.name}</Link>The idea applies to any variable-size hole: the container sets the space, not the content. The width is the same when signed in, when signed out and while it's being worked out; the content is aligned to the right, so it grows towards the empty side; and the navigation moves onto a second line always on narrow screens, instead of doing so depending on what arrives. The favorites counter, which appears after hydration, also has its minimum.
6.3. The holes on the event page
The availability and the booking arrive after everything else. The booking fallback is h-12 tall, and the form, quite a bit more. Measure both with the inspector and bring them closer: on the event page, the booking container gets min-h-28 both in the fallback and in the component. With the short cases ("Sign in to book") there's a bit of extra air underneath; it's a small price to pay so that the calendar link doesn't move just as someone is about to tap it.
Things that don't cause CLS matter too: changes to transform or opacity, and the SWR availability update, which replaces one text with another of the same height.
- INP: the main thread
A slow interaction has three possible causes, and each has its remedy:
| Phase | What happens | In Next.js |
|---|---|---|
| Input delay | The thread is busy and doesn't respond | Hydration, third-party scripts |
| Processing | The handlers take a long time | Synchronous calculations or writes |
| Presentation | React renders and the browser paints | Too many components affected by a change |
Server Components are the first line of defense: what isn't sent isn't hydrated. The second is Suspense boundaries, which split hydration into chunks and prioritize whatever is being tapped (04-04). Even so, go over AgendaViva's interactions with the CPU throttled to a quarter:
- Typing in the search box.
SearchFieldkeeps the text in its state, which only affects that component, and the debounce (useDebounce) separates the keystroke from the query. Correct. - Marking a favorite.
useFavoritesnotifies every star on the page. With six you don't notice; with two hundred, every tap would render two hundred buttons. The remedy would be for the hook to return one boolean per event, becauseuseSyncExternalStoredoesn't render if the value doesn't change (exercise 2). - Filtering venues.
VenueSearchfilters a short list on every keystroke. If there were thousands,useDeferredValuewould let typing take precedence over filtering. - Submitting a form. The work happens on the server; what you see immediately is the pending state (06-04).
For a long, unavoidable calculation, don't block: yield to the browser every so many steps.
// Example only: yield the thread between batches
async function yieldToMain(): Promise<void> {
if ('scheduler' in window && typeof window.scheduler?.yield === 'function') {
await window.scheduler.yield()
} else {
await new Promise((resolve) => setTimeout(resolve))
}
}scheduler.yield isn't available in every browser, hence the fallback. If TypeScript doesn't know about scheduler, declare its type. And before resorting to this, ask whether the calculation shouldn't live in a Server Component.
7.1. React Compiler
React Compiler adds at build time the memoization that used to be written with useMemo, useCallback and memo: a component whose props don't change isn't rendered again. In Next.js it's a stable option since version 16, disabled by default:
// Example only: next.config.ts
const nextConfig: NextConfig = {
// Only components marked with 'use memo'
reactCompiler: { compilationMode: 'annotation' },
// Or, for all of them: reactCompiler: true
}It runs with Babel, and Next.js only applies it to files with JSX or hooks, so the build gets somewhat longer. It acts on the presentation phase of Client Components; it doesn't reduce JavaScript or help LCP.
In AgendaViva we don't enable it, for a reason worth more than the tool: we don't have a problem it solves. Our islands are small and render little. An editor, a calendar or a dashboard with hundreds of cells is another story. If you try it, measure before and after, start in annotation mode and use 'use no memo' to exclude the component that causes trouble.
- A budget
Improvements get lost on their own: a dependency here, a hole there. A budget is a written limit that makes noise when it's exceeded. It should have numbers of two kinds:
| What | AgendaViva's limit | Where it's monitored |
|---|---|---|
| LCP, 75th percentile, mobile | 2.5 s | Field, per route |
| INP, 75th percentile | 200 ms | Field |
| CLS, 75th percentile | 0.1 | Field |
| Initial JavaScript per route | Today's measurement plus 10% | On every change (10-02) |
| Poster weight on mobile | 150 KB | Review |
| Holes above the LCP on public routes | None | Review, and tests (10-04) |
The field ones tell you whether things are going well and react late; the others are checked before publishing. A limit nobody looks at isn't a budget, and one so strict that it fails every week ends up being disabled.
Common Mistakes and Tips
- Measuring in development, or with
QUERY_DELAY_MSactive. - Drawing conclusions from a single Lighthouse run.
- Optimizing the score instead of the experience.
- Looking at the average instead of the 75th percentile, or mixing mobile and desktop.
- Defining the
useReportWebVitalsfunction inside the component: duplicated data. - Sending the metrics with
fetchwithoutkeepalive: they're lost when leaving. - Storing the full URL, with identifiers and tokens.
fetchPriority="high"on several images.fallback={null}on something that takes up space above the content.- Skeletons that aren't the same size as the content.
- Assuming a low TTFB means a low LCP.
- Enabling React Compiler expecting the page to load sooner.
Exercises
Exercise 1: diagnosing
With this field data (75th percentile, mobile), say what the most likely problem is for each route and what you'd check first: (a) /events: TTFB 0.3 s, FCP 0.6 s, LCP 3.9 s, CLS 0.02; (b) /venues/[slug]: TTFB 1.9 s, LCP 2.6 s; (c) /: LCP 1.4 s, CLS 0.21, INP 90 ms; (d) /dashboard/events/new: LCP 1.2 s, INP 620 ms.
Solution
- (a) The shell arrives and the large element doesn't: the LCP is in the list's hole. Check whether the
listEventsquery hits the cache (a search withqisn't cached) and whether the first card lazy-loads its poster. - (b) The server is slow to start. That's odd on a
◐route: check whether someone setinstant = false, whether there's a redirect beforehand (/halls/…) or whether that route doesn't go through the CDN. - (c) Something is pushing the page. Enable the layout shift regions: the suspects are the notice, the header with a session, or a "your district" block that appears above other content.
- (d) The thread is busy during interaction. Record while typing: the whole form is probably rendering on every keystroke (controlled fields) or there's a calculation in the handler.
Exercise 2: one favorite, one render
With two hundred cards, tapping one star renders all of them. Add a useIsFavorite(eventId) hook to lib/favorites.ts that avoids this and use it in FavoriteButton. Explain why it works.
Solution
// lib/favorites.ts (added; uses subscribe and read, which already exist)
export function useIsFavorite(eventId: string): boolean {
return useSyncExternalStore(
subscribe,
() => read().includes(JSON.stringify(eventId)),
() => false, // On the server and during hydration
)
}
// components/favorite-button.tsx
const isFavorite = useIsFavorite(eventId)useSyncExternalStore calls the read function when the store notifies, and only renders if the result differs from the previous one according to Object.is. With a boolean, a hundred and ninety-nine buttons get the same value. read() returns the JSON text; searching for the identifier with its quotes keeps evt-1 from matching evt-10.
With six cards the difference can't be measured: you can keep either version.
Exercise 3: a cookie banner
Someone proposes a consent banner that's shown if the visitor doesn't have the corresponding cookie. The first version reads cookies() in a Server Component at the top of PublicLayout, inside <Suspense fallback={null}>. Which metrics does it make worse, and how would you build it?
Solution
It makes CLS worse, because it appears late and pushes things down. Removing the <Suspense> would be worse still: it would block the whole shell, and the TTFB of every public page would depend on a cookie. It can also become the LCP itself, if it's the largest block of text on the screen, and then you'd be measuring a banner instead of the content.
The alternative is the SiteNotice approach: at the end of the document, stuck to the bottom with position: sticky or fixed, small and without covering the controls. Since it depends on the person, it stays in its hole. And scripts that require consent aren't loaded until it's given (10-02).
Conclusion
LCP, INP and CLS sum up whether a page appears quickly, responds and stays still; they're assessed at the 75th percentile of real visits and diagnosed in the lab, with the production build. In Next.js, the shell takes care of TTFB and, if the important part is in it, LCP too; Server Components ease INP; and CLS depends on every hole taking up the same space empty as full. AgendaViva now measures its visitors, has a priority image on the home page and has stopped moving.
All of the above is about the first page. The second one, and those that follow, depend on how much was fetched ahead of the click and how much code has to be brought in. The next lesson, Prefetching, Lazy Loading and Bundle Analysis, deals with both, and with the JavaScript budget we've just written down.
