@@ -83,7 +83,7 @@ export default function CategoryLayout(props: LayoutProps<'/[category]'>) {
}
```
Notice that `CategoryLayout` does not `await props.params` itself. Instead, it passes the `params` promise to `CategoryHeader` inside `<Suspense>`. The `await` happens inside the boundary, so for unknown categories Next.js can still generate the App Shell.
Notice that `CategoryLayout` does not `await props.params` itself. Instead, it passes the `params` promise to `CategoryHeader` inside `<Suspense>`. The `await` happens inside the boundary, so for unknown categories Next.js can still generate the App Shell. Keep the read inside the boundary even for the categories `generateStaticParams` covers. A statically known param still belongs to one URL, so awaiting it above the Suspense boundary would tie this layout'sAppShelltothatURL.See[Instantnavigation](/docs/app/guides/instant-navigation)forstructuringroutesthisway.
@@ -50,7 +50,7 @@ With Cache Components, **caching directives** (`"use cache"` and its variants) a
> **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. With [runtime prefetching](/docs/app/guides/runtime-prefetching), the information is available and such a fallback becomes part of the instant UI. Cached values like timestamps or data fetches can sit directly inside the fallback.
Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. See [App Shells](/docs/app/guides/runtime-prefetching#app-shells) for how to enable them and how they pair with runtime prefetching.
Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. [Runtime prefetching](/docs/app/guides/runtime-prefetching) builds on it, resolving a link'sURLdataontop.
@@ -205,13 +205,15 @@ Next.js maintains a small task queue, which prefetches in the following order:
The scheduler prioritizes likely navigations while minimizing unused downloads.
### Partial Prerendering (PPR)
### Cache Components
When PPR is enabled, a page is divided into a [static shell](/docs/app/guides/streaming#the-static-shell) and a streamed dynamic section:
With [Cache Components](/docs/app/getting-started/caching) enabled, the prefetching strategy uses an [App Shell](/docs/app/glossary#app-shell) to make client navigations instant:
- The shell, which can be prefetched, streams immediately
- Uncached data streams when ready
- Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches
- The App Shell holds the route's static and session output.
- Uncached data streams in when ready.
- Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches.
A link can also resolve its URL data (`searchParams`, `params`) at prefetch time. See [Runtime prefetching](/docs/app/guides/runtime-prefetching).
Therouterprefetchesan[AppShell](/docs/app/glossary#app-shell) per route as visible `<Link>` components enter the viewport. Runtime prefetching lets the prefetch also include content that depends on the request: cookies, headers, `searchParams`, and `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). On a direct visit, the `<Suspense>` boundaries around runtime data render their fallbacks and the content streams in. Uncached reads stay behind their fallback boundaries either way.
Prefetchingdownloadsaroute's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip.
Thisguideassumesyou've structured your route for instant navigation. If you haven't,startwiththe[Instantnavigationguide](/docs/app/guides/instant-navigation)tovalidatetheroute's caching structure first. Runtime prefetching costs a per-link server invocation. It only pays off when there'scontentpasttheAppShellworthresolvingbeforetheclick.
The regular App Router prefetches a route all or nothing: the full route when it'sstatic,andnothingforadynamicroutewithouta[`loading.js`](/docs/app/api-reference/file-conventions/loading).
[CacheComponents](/docs/app/getting-started/caching)takesadifferentapproachandproducesan[**AppShell**](/docs/app/glossary#app-shell) for every route. The shell contains the route's static output, and for a route that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) (session data), it can also contain UI gated behind that session data.
Theshellcannotcarrydatathatvariesperlink:[`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional), the route's [URL data](/docs/app/glossary#url-data). **Runtime prefetching** resolves that URL data at prefetch time, ready before the click rather than streaming in after it.
Italsoassumesyourrouteisalreadystructuredforinstantnavigation.Ifitisn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first.
Runtime prefetching takes two opt-ins: links to the route use `<Link prefetch={true}>`, and the destination route sets [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime).
```tsx filename="app/layout.tsx"
A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`:
```tsx filename="app/page.tsx"
import Link from 'next/link'
export default function RootLayout({ children }: LayoutProps<'/'>) {
export default function Home() {
return (
<html>
<body>
<nav>
<Link href="/courses">Courses</Link>
</nav>
{children}
</body>
</html>
<nav>
<Link href="/search?q=react" prefetch={true}>
React
</Link>
<Link href="/search?q=next" prefetch={true}>
Next.js
</Link>
</nav>
)
}
```
```tsx filename="app/courses/page.tsx"
The destination renders a static heading and a `<Results>` list whose contents depend on the query. Each query is cached, computed once and reused.
```tsx filename="app/search/page.tsx"
import { Suspense } from 'react'
export const prefetch = 'allow-runtime'
export default function CoursesPage() {
export default function SearchPage({ searchParams }: PageProps<'/search'>) {
return (
<>
<h1>Courses</h1>
<Suspense fallback={<BadgeFallback />}>
<EnrolledBadge /> {/* reads the session cookie */}
</Suspense>
<FeaturedCourses /> {/* 'use cache' */}
<Suspense fallback={<Loading />}>
<LiveEnrollment /> {/* uncached, fresh per request */}
Without `prefetch = 'allow-runtime'`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in.
When[`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch)issetontheroute,therouterprefetchesaprerenderof`/courses`thatincludesrequestdata,beyondwhat's in the App Shell. `<EnrolledBadge>` resolves because the session cookie is available at prefetch time. `<LiveEnrollment>` still sits behind its fallback because no prerender can know its current value. After the click, only `<LiveEnrollment>` streams in.
With [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) on the route, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link'sURL,knownatprefetchtime,andthecached`search(q)`fillsinfromthere.Ontheclick,theresultsrenderimmediately,withnofallback.
The prerender advances through anything that'sstaticorcached,thenstopsatuncachedreadsandfallsbacktothesurrounding`<Suspense>`boundary.Theboundaryisalreadyinplacefromyour**instant-navvalidation**.
@@ -99,11 +134,14 @@ export default function DashboardLayout({
}
```
`<UserNav>`readsacookie,thenlooksupdatabasedonit.Thechallengeisthat`"use cache"`can't read `cookies()` inside the cached function. Two patterns handle this: **extract and pass** when the lookup result is shared across many users, and `"use cache: private"` when it'stiedtoaspecificuser.
ThecookieitselfissessiondatatheAppShellalreadyknows.But`"use cache"`can't read `cookies()` inside the cached function, so two patterns bridge it:
- **Extract and pass** when the lookup result is shared across many sessions.
- **`"use cache: private"`** when it is tied to one.
Read the cookie outside the cached function and pass the value in as an argument. The `cookies()` call stays outside the cache scope, the argument crosses the boundary, and the cached function has a deterministic signature. The cache entry is keyed on that argument, and sessions that share the value share the entry.
On a direct visit, `<UserNav>` shows its fallback until the lookup resolves. On navigation, the App Shell has already resolved it, because the team cookie is session data the shell can read. Because sessions on the same team share the cache entry, traffic to the underlying data scales with team count, not session count.
Anything without a caching directive still streams in after navigation. A shell holds only what can be prepared ahead of the navigation, not the whole page. It advances only as far as the caching structure allows.
When the lookup is tied to a single session, use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private). It assigns a cache lifetime to a function that reads cookies, headers, or other runtime data directly. Results are cached in the browser only, scoped to that session.
```tsx filename="app/dashboard/user-nav.tsx"
import { cookies } from 'next/headers'
...
...
@@ -151,55 +189,32 @@ async function getUser() {
}
```
`cookies()`livesinsidethecachedfunction,whichonlyworksunder`"use cache: private"`.Thisisalsothepatternwhenyoucan't extract the runtime data from the outside: auth helpers that check `Date.now()` against a token'sexpiry,orsessionhelpersthatreadcookiesdeepinsidetheirowncode,can't be wrapped at the call site.
Here `cookies()` lives inside the cached function, which only works under `"use cache: private"`. This is also the pattern when you can'textracttheruntimedatafromtheoutside:authhelpersthatcheck`Date.now()`againstatoken's expiry, or session helpers that read cookies deep inside their own code, can'tbewrappedatthecallsite.
Everything inside the scope shares the same lifetime, so colocate `"use cache: private"` as close to the runtime data access as possible.
- A useful chunk of the page depends on request data: cookies, headers, the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params)
- That chunk has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
Skipitwhentheprefetchcan't produce a better UI than the App Shell. Each visible `<Link>` to a route with `'allow-runtime'` wakes a server, and that cost only pays off if more of the page is ready before the click:
- The route has little or no URL-data dependency. The App Shell already makes the navigation instant.
- The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way.
- The route is rarely navigated to. You pay per visible link, regardless of click-through.
The[**AppShell**](/docs/app/glossary#app-shell) closes that gap. It's a per-route prerender, deduped across every link to the same route, generated and prefetched once per route rather than once per visible link.
NlinkstothesamerouteshareoneprefetchedAppShell,sorenderinga`<Link>`iseffectivelyfree.Toprefetchmorethantheshell(includingrequestdatalikecookies,headers,params,and`searchParams`),optthedestinationinto[`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime) and use `<Link prefetch={true}>` on the link side.
A per-link runtime prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell. That shell is the reliable baseline, and runtime prefetching only layers on top when it arrives in time.
@@ -50,7 +50,7 @@ With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/do
The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this, and the shell is cached per session on the client, not shared across users.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client.
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). If the destination opts into [`prefetch = 'allow-runtime'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#allow-runtime), the prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL.
@@ -12,7 +12,7 @@ The Next.js router introduced in version 13, built on top of React Server Compon
## App Shell
A per-route prerender containing the parts of a page that don't depend on URL-specific data. Routes that read `cookies()` or `headers()` produce a session-personalized variant, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).
A per-route prerender containing the parts of a page that don't depend on URL data. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components).