In the previous lesson we measured the first page. The ones that follow are played on a different field: if what's needed was already in the browser when the person clicked, the navigation feels instant; if not, there's a round trip to wait for. Getting ahead costs something, because you download things nobody may open, so the question isn't "should I prefetch?" but "what, when and at what cost?".

The other half of the problem is code. Every Client Component and every library it imports ends up in a bundle the browser downloads, parses and executes. You'll learn to decide what each link prefetches, to check what appears instantly, to defer whatever isn't needed at the start, to keep third-party scripts in check and to look inside the bundle to find out who's taking up space and why. We'll finish with the JavaScript budget we promised.

  1. The stages of a navigation

With Cache Components and partial prefetching (partialPrefetching: true, in our project since 01-02), a route's content arrives in three stages:

Stage What triggers it What it contains
App Shell An ordinary <Link> enters the viewport The static and cached part of the route, without what depends on the URL. One for every link to that route
Per-link prefetch A visible <Link prefetch={true}> Additionally, the cached content that depends on that URL (params, searchParams)
Navigation The click The rest, streamed into its holes
flowchart LR
    A["Visible link<br/>prefetch auto"] --> B["App Shell of /events/[slug]<br/>header and skeleton"]
    C["Intent<br/>prefetch true"] --> D["jazz-night event page<br/>title, date, poster"]
    E["Click"] --> F["Spots, booking, session"]
    B --> D --> F

Six home page cards produce one prefetch, not six: they all share the event page's App Shell. That's why the default is so cheap and why it's not worth disabling it "to save".

The prefetch values work out like this:

Value Effect with partial prefetching
'auto', null or omitted App Shell
true App Shell and that URL's cached content. It does not include what isn't cached
false Nothing, not even on hover

Three more details. Prefetching only works in production. There's a queue that serves what's visible and what's being pointed at first, and discards whatever leaves the viewport. And an immediate invalidation from a Server Action (updateTag, revalidatePath) empties what was prefetched, so after saving an event the links are prefetched again on their own.

Whatever is prefetched runs on the server. A component that counted visits when rendering would count prefetches; we already said in 05-04 that rendering is reading.

1.1. The session and the App Shell

The documentation points out that the App Shell can include session data, if the cookie-based lookup is cached (with the cookie read outside, or with 'use cache: private'). In AgendaViva, getCurrentUser is deliberately not cached: signing out must take effect on the next request (08-01). Our App Shell carries the AccountMenu hole empty, and that's fine: that area is in the header, which is preserved when navigating.

  1. What to prefetch on top

prefetch={true} costs one server execution per visible link, except on fully static pages. Putting it on every card in a list would multiply requests by twenty to save one skeleton on one page. But there's a moment when we know a lot more: when the pointer rests on the link, a finger touches it or the keyboard focuses it. Between that and the click there are one to three hundred milliseconds, enough for an event page that comes out of the cache.

// components/intent-link.tsx
'use client'

import { type ComponentProps, useState } from 'react'
import Link from 'next/link'

type Props = Omit<ComponentProps<typeof Link>, 'prefetch'>

// Prefetches the App Shell when visible and the content when there's intent to open it
export function IntentLink(props: Props) {
  const [hasIntent, setHasIntent] = useState(false)
  const handleIntent = () => setHasIntent(true)

  return (
    <Link
      {...props}
      prefetch={hasIntent ? true : 'auto'}
      onMouseEnter={handleIntent}
      onFocus={handleIntent}
      onTouchStart={handleIntent}
    />
  )
}

It's the documentation's pattern, extended to focus and touch. Before the intent the value is 'auto' rather than false: with false the App Shell would be lost too. The component is a client one, but it's used from Server Components and only receives text and children. It replaces Link in:

Link Prefetch Reason
EventCard title IntentLink The destination is cached (getEventDetails) and depends on the slug
"Previous" and "Next" in Pagination IntentLink The first pages are cached
Venue name on /venues IntentLink Cached by slug
Header and footer Plain Link Their destinations don't depend on the URL: the App Shell already brings everything
/my-bookings, /dashboard Plain Link What matters isn't cached; true wouldn't add anything
Long dashboard list, "Edit" Plain Link A single route, a single App Shell

Look at the fifth row. prefetch={true} on a page whose content isn't cached spends an execution to get the same skeleton. Cache first, then prefetch.

From /events, the card doesn't open the event page but the intercepted quick view (02-05): the prefetch is that route's, and it works the same way.

Sometimes you know where the person will go without there being a link: after the second step of a wizard, or when a search has a single result. That's what router.prefetch is for:

// Example only
const router = useRouter()

useEffect(() => {
  if (results.length === 1) router.prefetch(`/events/${results[0].slug}`)
}, [results, router])

Use it sparingly. For almost everything, a visible Link does the same and is accessible as well.

2.2. Keeping work out of the prefetch

The opposite problem exists too: content that's cached but expensive to compute, which isn't worth generating for links nobody will open. Next.js 16.4 adds two functions to next/cache that defer whatever is below them:

Function What follows is rendered…
await prefetch() In the per-link prefetch or in the navigation, not in the App Shell
await navigation() Only in the navigation
// Example only: related events wait for the click even though they're cached
import { navigation } from 'next/cache'

export async function RelatedEvents({ params }: Pick<Props, 'params'>) {
  await navigation()
  const { slug } = await params
  const events = await listRelatedEvents(slug)
  // …
}

The component must be inside a <Suspense>, and they can't be called inside 'use cache'. Unlike connection(), they don't make anything dynamic: if the page is prerendered, the content stays in it. Our related events are an indexed, cheap query, so we leave them as they are.

  1. Seeing what's visible

The word "instant" has a precise meaning here: when you click, the browser can paint something of the destination without waiting for the server. Next.js checks this in development on its own. If a page forces a wait, the warning appears with the three ways out you know from 01-04.

That validation is controlled per segment with instant, stable since 16.3:

export const instant = true   // Requires navigations up to here not to block
export const instant = false  // Accepts that they block: it only silences the warning

Every page is already validated by default, so true is rarely needed: it's for insisting on a page whose layout is excluded. Neither value changes how the page is generated.

That there's something to paint doesn't guarantee it's good. A full-page skeleton passes the validation and is a poor experience. To judge it, use the Navigation Inspector from 04-04: Next.js indicator, Navigation Inspector, Pause on navigations.

  1. With the pause active, reload the jazz-night event page. You see the shell: title, date, poster, header. The availability, booking and session are missing.
  2. Go back to the home page and click the card. You see what the prefetch had.
  3. Click Resume and watch what changes. If something moves, go back to 10-01.

A load and a navigation can give different results, because when navigating only the boundaries below the shared layout count. Always check both. In development there's no prefetching, and the inspector simulates what would happen; the final confirmation is done in production, and in 10-04 we'll turn it into a test.

To see the real traffic: npm run build && npm run start, network tab, filter by _rsc. When the home page loads you'll see the App Shell prefetches; when you hover over a card, that event page's; when you click, only what was missing.

  1. Lazy loading components

Next.js splits the code by route automatically: entering the home page doesn't download the dashboard form. Within a route, however, everything its Client Components import arrives with it, whether it's used or not. next/dynamic moves it into a separate file that's requested when it renders:

// Example only: components/venue-map.tsx
'use client'

import dynamic from 'next/dynamic'
import { useState } from 'react'

// The map library reads window when imported: it can't be prerendered
const MapView = dynamic(() => import('@/components/map').then((mod) => mod.MapView), {
  ssr: false,
  loading: () => <p>Loading the map…</p>,
})

export function VenueMap({ address }: { address: string }) {
  const [visible, setVisible] = useState(false)

  return (
    <div className="min-h-80">
      {visible ? (
        <MapView address={address} />
      ) : (
        <button type="button" onClick={() => setVisible(true)}>View on the map</button>
      )}
    </div>
  )
}
  • The condition is what saves. A lazy component that's always shown doesn't delay its download until it's needed, because it's needed right away: it only splits it off, and often all it achieves is appearing later. Lazy loading is for what might not be used.
  • ssr: false is only allowed in a Client Component. In a server one it's an error. Its proper use is the one from 03-04: a library that touches window when imported. For a component that only makes sense in the browser we already have use(browser()) (03-02).
  • From a Server Component it doesn't split anything. The documentation warns that when you dynamically import a Client Component from a server one, automatic code splitting doesn't happen yet. The dynamic call goes on the client side.
  • Reserve the space (min-h-80), or you'll have CLS again.
  • This would need CSP changes: the map images come from another domain.

React.lazy with <Suspense> does the same; next/dynamic is that combination with a couple of extra options. And Server Components don't need any of this: their code isn't downloaded.

4.1. Deferring a library

Very often the heavy part isn't a component but a function used on a click. An import() inside the handler is enough:

// Example only: a QR code to take the event page to your phone (npm install qrcode)
async function showQrCode() {
  const { toDataURL } = await import('qrcode')
  setImage(await toDataURL(url))
}

The library is downloaded the first time someone asks for it. Before writing this, the usual question: can't the server do it? A QR code for a fixed address is HTML or an image generated once, in a cached Server Component, without a single byte of JavaScript. It's the most effective optimization, and the official guide recommends it for anything that only turns data into UI: code highlighting, Markdown, static charts, date formatting.

  1. Third-party scripts

A foreign script is the worst possible candidate: you don't control its weight, it runs on your page with your permissions and it may change tomorrow. next/script doesn't prevent any of that; it decides when it gets in the way:

strategy When For what
afterInteractive (default) After hydration starts Analytics, tag managers
lazyOnload When the browser is idle, after everything else Help chat, social buttons
beforeInteractive Before Next.js's code. Only in the root layout Consent manager, bot detection
worker In a worker. Experimental and not supported in the App Router Nothing, for now
// Example only: loaded in the dashboard and nowhere else
import Script from 'next/script'

<Script src="https://help.example.com/chat.js" strategy="lazyOnload" />

It goes in the narrowest layout that needs it, and Next.js loads it only once even when navigating between its pages. onLoad, onReady and onError require a Client Component.

AgendaViva has none, and that's a decision. Adding the first one forces three things: widening script-src and connect-src in the CSP, which means that provider will be able to run whatever it wants on our pages (08-05); asking for consent if it sets cookies or identifies people; and measuring INP again. For basic analytics we already have our own metrics, with no third parties.

  1. Looking inside the bundle

next build no longer prints sizes (05-01). The tool is Turbopack's built-in analyzer:

# Opens an interface in the browser. The default port is 4000
npx next analyze --port 4100

# Save a snapshot without opening anything, for comparison
npx next analyze --output --snapshot before

# The same graph, as JSON lines, for a script
npx next analyze export --snapshot before > before.jsonl

We change the port because 4000 is used by scripts/weather-api.mjs. In earlier versions the command was called next experimental-analyze, and with Webpack you use the @next/bundle-analyzer package. next analyze builds, so it needs the database running if the build needs it; snapshots are saved in .next/diagnostics/analyze, and export exists since 16.4.

The screen is a treemap of rectangles whose area is the size. You can filter by route, by environment (client or server) and by type. Clicking a module shows its import chain, that is, why it's there. A working method:

  1. Choose a route and the client environment.
  2. Look for what you shouldn't see. In AgendaViva: zod, drizzle-orm, pg, nothing from lib/data.
  3. Look at the three largest rectangles that aren't React or Next.js. Today, swr on the event pages.
  4. Follow the chain of whatever doesn't belong up to the 'use client' that drags it in.

Two common surprises in step 2. A module with server functions and a constant the browser uses: you import the constant and everything comes along. That's why EVENT_LIMITS lives in lib/schemas/limits.ts, with no dependencies, and not next to eventSchema. And a Client Component that imports a type without import type from a module that also runs something.

6.1. Barrel files

A barrel is an index.ts that re-exports lots of things:

// Example only: components/index.ts
export * from './submit-button'
export * from './theme-select'
export * from './live-availability' // Drags in swr

Importing a button from @/components forces the whole barrel to be resolved. The bundler removes what isn't used if it can prove that importing it has no side effects, and it can't always do so. With 'use client' it's worse: every boundary in the barrel counts. The solution in your own code is not to have them: we always import from the file.

For libraries with hundreds of exports, such as icon libraries, there's optimizePackageImports, which loads only the modules used:

// Example only: next.config.ts
experimental: {
  optimizePackageImports: ['my-icon-library'],
},

The option is still experimental. Before adding one, check the list Next.js already handles on its own: it includes lucide-react, date-fns, lodash-es, @mui/material, recharts and quite a few more.

6.2. The server side

What Server Components and Route Handlers use is bundled too. It doesn't affect visitors, but it does affect the cold start on a serverless platform and the size of the Docker image. Some libraries don't get along with it, especially those that load their own binaries or files at runtime:

// Example only: loaded with require from node_modules, unbundled
serverExternalPackages: ['some-native-library'],

pg, sharp, pino, argon2 and other well-known ones are on a list that's excluded automatically; there's no need to repeat them.

  1. The budget, in a script

The analyzer explains, but it doesn't warn. For a change that doubles the home page's JavaScript to make noise, it's enough to request the page and add up what it links to:

// scripts/budget.mjs — with the production server running
import { gzipSync } from 'node:zlib'

const BASE = process.env.BASE_URL ?? 'http://localhost:3000'

// Compressed KB. Replace them with your first measurement plus 10%
const LIMITS = {
  '/': 180,
  '/events': 190,
  '/events/jazz-night': 195,
  '/sign-in': 175,
}

async function sizeOf(path) {
  const html = await (await fetch(new URL(path, BASE))).text()
  const sources = [...html.matchAll(/<script\b[^>]*\bsrc="(\/_next\/static\/[^"]+)"[^>]*>/g)]
    .filter(([tag]) => !/nomodule/i.test(tag)) // Only for old browsers
    .map(([, src]) => src.replaceAll('&amp;', '&'))

  const sizes = await Promise.all(
    [...new Set(sources)].map(async (src) => {
      const response = await fetch(new URL(src, BASE))
      return gzipSync(Buffer.from(await response.arrayBuffer())).length
    }),
  )
  return Math.round(sizes.reduce((sum, size) => sum + size, 0) / 1024)
}

for (const [path, limit] of Object.entries(LIMITS)) {
  const size = await sizeOf(path)
  const exceeds = size === 0 || size > limit // Zero means nothing was found
  console.log(`${exceeds ? 'FAIL' : 'ok  '}  ${path.padEnd(28)} ${size} KB of ${limit}`)
  if (exceeds) process.exitCode = 1
}
{
  "scripts": {
    "budget": "node scripts/budget.mjs",
    "analyze": "next analyze --port 4100"
  }
}

The limits in the example are a starting point: measure yours and write them down. It counts what the HTML requests on load, which is what competes with the LCP; what's deferred and what's prefetched are left out. fetch decompresses on its own, which is why it compresses again to measure what actually travels. And the zero case matters: if the shape of the HTML changes one day, the script must fail, not congratulate us.

When it fails, there are three honest answers: remove what's not needed, defer it, or raise the limit and explain why in the same change. In 11-06 it will run in CI.

For new dependencies, the question comes earlier: how much does it weigh (Bundlephobia or bundlejs will tell you), how much of it will we use, does it work on the server, and what would we have to write so as not to need it.

Common Mistakes and Tips

  • prefetch={false} to save. With partial prefetching, the App Shell is shared and costs almost nothing.
  • prefetch={true} on every card. One server execution per visible link.
  • Prefetching what isn't cached. It costs and gets you nothing ahead.
  • Checking prefetching in development. It doesn't exist there.
  • Counting visits when rendering. It counts prefetches.
  • dynamic on something that's always shown, or called from a Server Component.
  • ssr: false to "fix" a hydration error. It hides the cause (03-02).
  • Deferring the main content. It makes LCP worse.
  • Third-party scripts in the root layout for convenience.
  • Your own barrels with client boundaries.
  • Importing a Zod schema into a Client Component for the sake of a constant.
  • Looking at the uncompressed size, or the total for the application, instead of what a route loads.

Exercises

Exercise 1: choosing the prefetch

Say what you'd use on each link and why: (a) forty links to event pages in an archive listing; (b) the "Continue" button of a wizard whose next step is a static page; (c) "Sign out"; (d) a link to /my-bookings in the booking success message; (e) a download of /api/events/jazz-night/calendar; (f) the first result of a search, which 70% of people open.

Solution

  • (a) IntentLink: one App Shell for all forty and the content when intent is shown.
  • (b) Plain Link. If the destination is static and doesn't depend on the URL, the App Shell contains all of it.
  • (c) None: it's a form with an action. A link that signed you out would run when prefetched.
  • (d) Plain Link. The content is personal and uncached: true would bring the same skeleton.
  • (e) An <a>, not a Link. It's a Route Handler that returns a file; there's no route to render on the client.
  • (f) prefetch={true} on that one, because the probability makes the execution worthwhile, and IntentLink on the rest. Provided the destination is cached.

Exercise 2: finding the culprit

The analyzer shows zod on the client for /dashboard/events/new. The chain is: event-form.tsx → lib/schemas/event.ts → zod. The form uses EVENT_LIMITS, which someone re-exported from event.ts, and the type z.infer<typeof eventSchema>. Fix it. How would you stop it from happening again?

Solution

// event-form.tsx
import type { EventData } from '@/lib/types'
import { EVENT_LIMITS } from '@/lib/schemas/limits'

The constant is imported from its dependency-free module and the type with import type, which disappears at build time. The re-export in event.ts is also removed.

To keep it from happening again there are several safety nets: the route's budget (/dashboard/events/new requires a session, so the script would need to send a cookie; a 10-04 test can do that), ESLint's no-restricted-imports rule for components/** and _components/**, or the most drastic one: import 'server-only' in lib/schemas/event.ts. The last one breaks the build with the import chain in the message, and it's only possible because we decided not to validate with Zod in the browser (06-03).

Exercise 3: reviewing a slow page

A colleague has added an occupancy chart to the dashboard. List what you'd change.

// app/(dashboard)/dashboard/(overview)/page.tsx
'use client'

import * as Icons from 'icon-library'
import Script from 'next/script'
import dynamic from 'next/dynamic'
import { SubmitButton, Chart } from '@/components'

const Header = dynamic(() => import('./header'), { ssr: false })

export default function DashboardPage() {
  return (
    <>
      <Header />
      <Script src="https://charts.example.com/v3.js" strategy="beforeInteractive" />
      <Icons.BarChart />
      <Chart data={[12, 40, 31]} />
    </>
  )
}

Solution

  • 'use client' on the page turns everything it imports into client code, and the page loses direct access to the data.
  • import * as prevents discarding the unused icons, and a whole library for one drawing isn't worth it: an inline SVG.
  • beforeInteractive outside the root layout isn't allowed, and for a chart it's the opposite of the priority it deserves.
  • A dependency from someone else's CDN is left out of the bundle, out of pinned versions and out of the CSP. If it's needed, it gets installed.
  • dynamic with ssr: false on the header delays the first thing you see and leaves it out of the HTML.
  • The @/components barrel drags in everything else.

And the underlying question: three bars are a few SVG or CSS rectangles. A Server Component draws them with the data from getOccupancy() and downloads nothing. If the chart had to be interactive, it would be an island, imported from its own file and, if it sits under a tab, lazy-loaded.

Conclusion

A Link prefetches its route's App Shell, which is cheap and shared; prefetch={true} adds a URL's cached content and is kept for when there's intent. The Navigation Inspector shows what appears instantly. In code, what isn't sent beats what's deferred, and what's deferred beats what's loaded just in case; next analyze tells you who's taking up the space and a script holds the limit.

These lessons have left checks done by hand: opening the inspector, looking at the network, going through the application. They're valuable, and nobody repeats them on every change. It's time to automate. We start with the foundation, the functions and components that can be tested on their own, in Unit and Component Testing with Vitest.

© Copyright 2026. All rights reserved