Unverified Commit 4cae0943 authored by Joseph's avatar Joseph Committed by GitHub

docs: cache components - introduction (#85196)

parent 56136287
...@@ -269,7 +269,7 @@ export default async function Page({ searchParams }) { ...@@ -269,7 +269,7 @@ export default async function Page({ searchParams }) {
} }
``` ```
Using `searchParams` opts your page into [**dynamic rendering**](/docs/app/getting-started/partial-prerendering#dynamic-rendering) because it requires a incoming request to read the search parameters from. Using `searchParams` opts your page into [**dynamic rendering**](/docs/app/guides/caching#dynamic-rendering) because it requires a incoming request to read the search parameters from.
Client Components can read search params using the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook. Client Components can read search params using the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook.
......
...@@ -102,7 +102,7 @@ export default function LikeButton({ likes }) { ...@@ -102,7 +102,7 @@ export default function LikeButton({ likes }) {
On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks, by individual route segments ([layouts and pages](/docs/app/getting-started/layouts-and-pages)): On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks, by individual route segments ([layouts and pages](/docs/app/getting-started/layouts-and-pages)):
- **Server Components** are rendered into a special data format called the React Server Component Payload (RSC Payload). - **Server Components** are rendered into a special data format called the React Server Component Payload (RSC Payload).
- **Client Components** and the RSC Payload are used to [prerender](/docs/app/getting-started/partial-prerendering#how-does-partial-prerendering-work) HTML. - **Client Components** and the RSC Payload are used to [pre-render](/docs/app/guides/caching#rendering-strategies) HTML.
> **What is the React Server Component Payload (RSC)?** > **What is the React Server Component Payload (RSC)?**
> >
......
This diff is collapsed.
---
title: Partial Prerendering
description: Learn how to use Partial Prerendering and combine the benefits of static and dynamic rendering.
version: experimental
related:
title: Next Steps
description: Learn more about the config option for Partial Prerendering.
links:
- app/api-reference/config/next-config-js/ppr
---
Partial Prerendering (PPR) is a rendering strategy that allows you to combine static and dynamic content in the same route. This improves the initial page performance while still supporting personalized, dynamic data.
<Image
alt="Partially Prerendered Product Page showing static nav and product information, and dynamic cart and recommended products"
srcLight="/learn/light/thinking-in-ppr.png"
srcDark="/learn/dark/thinking-in-ppr.png"
width="1600"
height="632"
/>
When a user visits a route:
- The server sends a **shell** containing the static content, ensuring a fast initial load.
- The shell leaves **holes** for the dynamic content that will load in asynchronously.
- The dynamic holes are **streamed in parallel**, reducing the overall load time of the page.
> **🎥 Watch:** Why PPR and how it works → [YouTube (10 minutes)](https://www.youtube.com/watch?v=MTcPrTIBkpA).
## How does Partial Prerendering work?
To understand Partial Prerendering, it helps to be familiar with the rendering strategies available in Next.js.
### Static Rendering
With Static Rendering, HTML is generated ahead of time—either at build time or through [revalidation](/docs/app/guides/incremental-static-regeneration). The result is cached and shared across users and requests.
In Partial Prerendering, Next.js prerenders a **static shell** for a route. This can include the layout and any other components that don't depend on request-time data.
### Dynamic Rendering
With Dynamic Rendering, HTML is generated at **request time**. This allows you to serve personalized content based on request-time data.
A component becomes dynamic if it uses the following APIs:
- [`cookies`](/docs/app/api-reference/functions/cookies)
- [`headers`](/docs/app/api-reference/functions/headers)
- [`connection`](/docs/app/api-reference/functions/connection)
- [`draftMode`](/docs/app/api-reference/functions/draft-mode)
- [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional)
- [`unstable_noStore`](/docs/app/api-reference/functions/unstable_noStore)
- [`fetch`](/docs/app/api-reference/functions/fetch) with `{ cache: 'no-store' }`
In Partial Prerendering, using these APIs throws a special React error that informs Next.js the component cannot be statically rendered, causing a build error. You can use a [Suspense](#suspense) boundary to wrap your component to defer rendering until runtime.
### Suspense
React [Suspense](https://react.dev/reference/react/Suspense) is used to defer rendering parts of your application until some condition is met.
In Partial Prerendering, Suspense is used to mark **dynamic boundaries** in your component tree.
At build time, Next.js prerenders the static content and the `fallback` UI. The dynamic content is **postponed** until the user requests the route.
Wrapping a component in Suspense doesn't make the component itself dynamic (your API usage does), but rather Suspense is used as a boundary that encapsulates dynamic content and enable [streaming](#streaming)
```jsx filename="app/page.js"
import { Suspense } from 'react'
import StaticComponent from './StaticComponent'
import DynamicComponent from './DynamicComponent'
import Fallback from './Fallback'
export const experimental_ppr = true
export default function Page() {
return (
<>
<StaticComponent />
<Suspense fallback={<Fallback />}>
<DynamicComponent />
</Suspense>
</>
)
}
```
### Streaming
Streaming splits the route into chunks and progressively streams them to the client as they become ready. This allows the user to see parts of the page immediately, before the entire content has finished rendering.
<Image
alt="Diagram showing partially rendered page on the client, with loading UI for chunks that are being streamed."
srcLight="/docs/light/server-rendering-with-streaming.png"
srcDark="/docs/dark/server-rendering-with-streaming.png"
width="1600"
height="785"
/>
In Partial Prerendering, dynamic components wrapped in Suspense start streaming from the server in parallel.
<Image
alt="Diagram showing parallelization of route segments during streaming, showing data fetching, rendering, and hydration of individual chunks."
srcLight="/docs/light/sequential-parallel-data-fetching.png"
srcDark="/docs/dark/sequential-parallel-data-fetching.png"
width="1600"
height="525"
/>
To reduce network overhead, the full response—including static HTML and streamed dynamic parts—is sent in a **single HTTP request**. This avoids extra roundtrips and improves both initial load and overall performance.
## Enabling Partial Prerendering
You can enable PPR by adding the [`ppr`](https://rc.nextjs.org/docs/app/api-reference/next-config-js/ppr) option to your `next.config.ts` file:
```ts filename="next.config.ts" highlight={5} switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
ppr: 'incremental',
},
}
export default nextConfig
```
```js filename="next.config.js" highlight={4} switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
ppr: 'incremental',
},
}
```
The `'incremental'` value allows you to adopt PPR for specific routes:
```tsx filename="/app/dashboard/layout.tsx" switcher
export const experimental_ppr = true
export default function Layout({ children }: { children: React.ReactNode }) {
// ...
}
```
```jsx filename="/app/dashboard/layout.jsx" switcher
export const experimental_ppr = true
export default function Layout({ children }) {
// ...
}
```
Routes that don't have `experimental_ppr` will default to `false` and will not be prerendered using PPR. You need to explicitly opt-in to PPR for each route.
> **Good to know**:
>
> - `experimental_ppr` will apply to all children of the route segment, including nested layouts and pages. You don't have to add it to every file, only the top segment of a route.
> - To disable PPR for children segments, you can set `experimental_ppr` to `false` in the child segment.
## Examples
### Dynamic APIs
When using Dynamic APIs that require looking at the incoming request, Next.js will opt into dynamic rendering for the route. To continue using PPR, wrap the component with Suspense. For example, the `<User />` component is dynamic because it uses the `cookies` API:
```jsx filename="app/user.js" switcher
import { cookies } from 'next/headers'
export async function User() {
const session = (await cookies()).get('session')?.value
return '...'
}
```
```tsx filename="app/user.tsx" switcher
import { cookies } from 'next/headers'
export async function User() {
const session = (await cookies()).get('session')?.value
return '...'
}
```
The `<User />` component will be streamed while any other content inside `<Page />` will be prerendered and become part of the static shell.
```tsx filename="app/page.tsx" switcher
import { Suspense } from 'react'
import { User, AvatarSkeleton } from './user'
export const experimental_ppr = true
export default function Page() {
return (
<section>
<h1>This will be prerendered</h1>
<Suspense fallback={<AvatarSkeleton />}>
<User />
</Suspense>
</section>
)
}
```
```jsx filename="app/page.js" switcher
import { Suspense } from 'react'
import { User, AvatarSkeleton } from './user'
export const experimental_ppr = true
export default function Page() {
return (
<section>
<h1>This will be prerendered</h1>
<Suspense fallback={<AvatarSkeleton />}>
<User />
</Suspense>
</section>
)
}
```
### Passing dynamic props
Components only opt into dynamic rendering when the value is accessed. For example, if you are reading `searchParams` from a `<Page />` component, you can forward this value to another component as a prop:
```tsx filename="app/page.tsx" switcher
import { Table, TableSkeleton } from './table'
import { Suspense } from 'react'
export default function Page({
searchParams,
}: {
searchParams: Promise<{ sort: string }>
}) {
return (
<section>
<h1>This will be prerendered</h1>
<Suspense fallback={<TableSkeleton />}>
<Table searchParams={searchParams} />
</Suspense>
</section>
)
}
```
```jsx filename="app/page.js" switcher
import { Table, TableSkeleton } from './table'
import { Suspense } from 'react'
export default function Page({ searchParams }) {
return (
<section>
<h1>This will be prerendered</h1>
<Suspense fallback={<TableSkeleton />}>
<Table searchParams={searchParams} />
</Suspense>
</section>
)
}
```
Inside of the table component, accessing the value from `searchParams` will make the component dynamic while the rest of the page will be prerendered.
```tsx filename="app/table.tsx" switcher
export async function Table({
searchParams,
}: {
searchParams: Promise<{ sort: string }>
}) {
const sort = (await searchParams).sort === 'true'
return '...'
}
```
```jsx filename="app/table.js" switcher
export async function Table({ searchParams }) {
const sort = (await searchParams).sort === 'true'
return '...'
}
```
...@@ -57,7 +57,7 @@ export default async function Page() { ...@@ -57,7 +57,7 @@ export default async function Page() {
> **Good to know:** > **Good to know:**
> >
> - `fetch` responses are not cached by default. However, Next.js will [prerender](/docs/app/getting-started/partial-prerendering#static-rendering) the route and the output will be cached for improved performance. If you'd like to opt into [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering), use the `{ cache: 'no-store' }` option. See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch). > - `fetch` responses are not cached by default. However, Next.js will [pre-render](/docs/app/guides/caching#static-rendering) the route and the output will be cached for improved performance. If you'd like to opt into [dynamic rendering](/docs/app/guides/caching#dynamic-rendering), use the `{ cache: 'no-store' }` option. See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch).
> - During development, you can log `fetch` calls for better visibility and debugging. See the [`logging` API reference](/docs/app/api-reference/config/next-config-js/logging). > - During development, you can log `fetch` calls for better visibility and debugging. See the [`logging` API reference](/docs/app/api-reference/config/next-config-js/logging).
#### With an ORM or database #### With an ORM or database
...@@ -273,7 +273,7 @@ export const getPost = cache(async (id) => { ...@@ -273,7 +273,7 @@ export const getPost = cache(async (id) => {
> **Warning:** The content below assumes the [`cacheComponents` config option](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled in your application. The flag was introduced in Next.js 15 canary. > **Warning:** The content below assumes the [`cacheComponents` config option](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled in your application. The flag was introduced in Next.js 15 canary.
When using `async/await` in Server Components, Next.js will opt into [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering). This means the data will be fetched and rendered on the server for every user request. If there are any slow data requests, the whole route will be blocked from rendering. When you fetch data in Server Components, the data is fetched and rendered on the server for each request. If you have any slow data requests, the whole route will be blocked from rendering until all the data is fetched.
To improve the initial load time and user experience, you can use streaming to break up the page's HTML into smaller chunks and progressively send those chunks from the server to the client. To improve the initial load time and user experience, you can use streaming to break up the page's HTML into smaller chunks and progressively send those chunks from the server to the client.
......
...@@ -38,7 +38,7 @@ export default async function Page() { ...@@ -38,7 +38,7 @@ export default async function Page() {
} }
``` ```
> **Good to know**: Although `fetch` requests are not cached by default, Next.js will [prerender](/docs/app/getting-started/partial-prerendering#static-rendering) routes that have `fetch` requests and cache the HTML. If you want to guarantee a route is [dynamic](/docs/app/getting-started/partial-prerendering#dynamic-rendering), use the [`connection` API](/docs/app/api-reference/functions/connection). > **Good to know**: Although `fetch` requests are not cached by default, Next.js will [pre-render](/docs/app/guides/caching#static-rendering) routes that have `fetch` requests and cache the HTML. If you want to guarantee a route is [dynamic](/docs/app/guides/caching#dynamic-rendering), use the [`connection` API](/docs/app/api-reference/functions/connection).
To revalidate the data returned by a `fetch` request, you can use the `next.revalidate` option. To revalidate the data returned by a `fetch` request, you can use the `next.revalidate` option.
......
...@@ -33,6 +33,32 @@ Caching behavior changes depending on whether the route is statically or dynamic ...@@ -33,6 +33,32 @@ Caching behavior changes depending on whether the route is statically or dynamic
Fetch caching is **not** supported in `proxy`. Any fetches done inside of your `proxy` will be uncached. Fetch caching is **not** supported in `proxy`. Any fetches done inside of your `proxy` will be uncached.
## Rendering Strategies
To understand how caching works in Next.js, it's helpful to understand the rendering strategies available. The rendering strategy determines when your route's HTML is generated, which directly impacts what can be cached.
### Static Rendering
With Static Rendering, routes are rendered at **build time** or in the background after [data revalidation](/docs/app/guides/incremental-static-regeneration). The result is cached and can be reused across requests. Static routes are fully cached in the [Full Route Cache](#full-route-cache).
### Dynamic Rendering
With Dynamic Rendering, routes are rendered at **request time**. This happens when your route uses request-specific information like cookies, headers, or search params.
A route becomes dynamic when it uses any of these APIs:
- [`cookies`](/docs/app/api-reference/functions/cookies)
- [`headers`](/docs/app/api-reference/functions/headers)
- [`connection`](/docs/app/api-reference/functions/connection)
- [`draftMode`](/docs/app/api-reference/functions/draft-mode)
- [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional)
- [`unstable_noStore`](/docs/app/api-reference/functions/unstable_noStore)
- [`fetch`](/docs/app/api-reference/functions/fetch) with `{ cache: 'no-store' }`
Dynamic routes are not cached in the Full Route Cache, but can still use the [Data Cache](#data-cache) for data requests.
> **Good to know**: You can use [Cache Components](/docs/app/getting-started/cache-components) to mix static and dynamic rendering within the same route.
## Request Memoization ## Request Memoization
Next.js extends the [`fetch` API](#fetch) to automatically **memoize** requests that have the same URL and options. This means you can call a fetch function for the same data in multiple places in a React component tree while only executing it once. Next.js extends the [`fetch` API](#fetch) to automatically **memoize** requests that have the same URL and options. This means you can call a fetch function for the same data in multiple places in a React component tree while only executing it once.
...@@ -293,7 +319,7 @@ This diagram shows the difference between statically and dynamically rendered ro ...@@ -293,7 +319,7 @@ This diagram shows the difference between statically and dynamically rendered ro
height="1314" height="1314"
/> />
Learn more about [static and dynamic rendering](/docs/app/getting-started/partial-prerendering#static-rendering). Learn more about [static and dynamic rendering](#rendering-strategies).
### Duration ### Duration
...@@ -335,7 +361,7 @@ With the Router Cache: ...@@ -335,7 +361,7 @@ With the Router Cache:
The cache is stored in the browser's temporary memory. Two factors determine how long the router cache lasts: The cache is stored in the browser's temporary memory. Two factors determine how long the router cache lasts:
- **Session**: The cache persists across navigation. However, it's cleared on page refresh. - **Session**: The cache persists across navigation. However, it's cleared on page refresh.
- **Automatic Invalidation Period**: The cache of layouts and loading states is automatically invalidated after a specific time. The duration depends on how the resource was [prefetched](/docs/app/api-reference/components/link#prefetch), and if the resource was [statically generated](/docs/app/getting-started/partial-prerendering#static-rendering): - **Automatic Invalidation Period**: The cache of layouts and loading states is automatically invalidated after a specific time. The duration depends on how the resource was [prefetched](/docs/app/api-reference/components/link#prefetch), and if the resource was [statically generated](#static-rendering):
- **Default Prefetching** (`prefetch={null}` or unspecified): not cached for dynamic pages, 5 minutes for static pages. - **Default Prefetching** (`prefetch={null}` or unspecified): not cached for dynamic pages, 5 minutes for static pages.
- **Full Prefetching** (`prefetch={true}` or `router.prefetch`): 5 minutes for both static & dynamic pages. - **Full Prefetching** (`prefetch={true}` or `router.prefetch`): 5 minutes for both static & dynamic pages.
...@@ -423,8 +449,8 @@ Data returned from `fetch` is _not_ automatically cached in the Data Cache. ...@@ -423,8 +449,8 @@ Data returned from `fetch` is _not_ automatically cached in the Data Cache.
By default, when no `cache` or `next.revalidate` options are provided: By default, when no `cache` or `next.revalidate` options are provided:
- [Dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering): Fetch runs on every request and always returns fresh data. - [Dynamic rendering](#dynamic-rendering): Fetch runs on every request and always returns fresh data.
- [Static rendering](/docs/app/getting-started/partial-prerendering#static-rendering): Fetched data is stored in the [Data Cache](#data-cache), and the rendered output in the [Full Route Cache](#full-route-cache). Next.js serves this cached result until the path is revalidated. - [Static rendering](#static-rendering): Fetched data is stored in the [Data Cache](#data-cache), and the rendered output in the [Full Route Cache](#full-route-cache). Next.js serves this cached result until the path is revalidated.
See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch) for more options. See the [`fetch` API Reference](/docs/app/api-reference/functions/fetch) for more options.
......
...@@ -35,7 +35,7 @@ If an attacker wanted to load a script into your page, they'd need to guess the ...@@ -35,7 +35,7 @@ If an attacker wanted to load a script into your page, they'd need to guess the
[Proxy](/docs/app/api-reference/file-conventions/proxy) enables you to add headers and generate nonces before the page renders. [Proxy](/docs/app/api-reference/file-conventions/proxy) enables you to add headers and generate nonces before the page renders.
Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) to add nonces**. Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/guides/caching#dynamic-rendering) to add nonces**.
For example: For example:
......
...@@ -9,7 +9,7 @@ related: ...@@ -9,7 +9,7 @@ related:
- app/api-reference/functions/draft-mode - app/api-reference/functions/draft-mode
--- ---
**Draft Mode** allows you to preview draft content from your headless CMS in your Next.js application. This is useful for static pages that are generated at build time as it allows you to switch to [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) and see the draft changes without having to rebuild your entire site. **Draft Mode** allows you to preview draft content from your headless CMS in your Next.js application. This is useful for static pages that are generated at build time as it allows you to switch to [dynamic rendering](/docs/app/guides/caching#dynamic-rendering) and see the draft changes without having to rebuild your entire site.
This page walks through how to enable and use Draft Mode. This page walks through how to enable and use Draft Mode.
......
...@@ -277,7 +277,7 @@ export default async function Page() { ...@@ -277,7 +277,7 @@ export default async function Page() {
} }
``` ```
We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering). We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to [dynamic rendering](/docs/app/guides/caching#dynamic-rendering).
### On-demand revalidation with `revalidatePath` ### On-demand revalidation with `revalidatePath`
...@@ -573,7 +573,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can ...@@ -573,7 +573,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can
- ISR is only supported when using the Node.js runtime (default). - ISR is only supported when using the Node.js runtime (default).
- ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports).
- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/guides/caching#data-cache). - If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/guides/caching#data-cache).
- If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/guides/caching#dynamic-rendering).
- Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. - Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`.
</AppOnly> </AppOnly>
......
...@@ -473,7 +473,7 @@ In addition, the new `useRouter` hook has the following changes: ...@@ -473,7 +473,7 @@ In addition, the new `useRouter` hook has the following changes:
- The `locale`, `locales`, `defaultLocales`, `domainLocales` values have been removed because built-in i18n Next.js features are no longer necessary in the `app` directory. [Learn more about i18n](/docs/app/guides/internationalization). - The `locale`, `locales`, `defaultLocales`, `domainLocales` values have been removed because built-in i18n Next.js features are no longer necessary in the `app` directory. [Learn more about i18n](/docs/app/guides/internationalization).
- `basePath` has been removed. The alternative will not be part of `useRouter`. It has not yet been implemented. - `basePath` has been removed. The alternative will not be part of `useRouter`. It has not yet been implemented.
- `asPath` has been removed because the concept of `as` has been removed from the new router. - `asPath` has been removed because the concept of `as` has been removed from the new router.
- `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/getting-started/partial-prerendering#static-rendering), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) hook will skip the prerendering step and instead be rendered on the client at runtime. - `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/guides/caching#static-rendering), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) hook will skip the prerendering step and instead be rendered on the client at runtime.
- `route` has been removed. `usePathname` or `useSelectedLayoutSegments()` provide an alternative. - `route` has been removed. `usePathname` or `useSelectedLayoutSegments()` provide an alternative.
[View the `useRouter()` API reference](/docs/app/api-reference/functions/use-router). [View the `useRouter()` API reference](/docs/app/api-reference/functions/use-router).
......
...@@ -23,11 +23,11 @@ When navigating to the new page, there's no full page reload or browser loading ...@@ -23,11 +23,11 @@ When navigating to the new page, there's no full page reload or browser loading
## Prefetching static vs. dynamic routes ## Prefetching static vs. dynamic routes
| | **Static page** | **Dynamic page** | | | **Static page** | **Dynamic page** |
| ----------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------- | | ----------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------- |
| **Prefetched** | Yes, full route | No, unless [`loading.js`](/docs/app/api-reference/file-conventions/loading) | | **Prefetched** | Yes, full route | No, unless [`loading.js`](/docs/app/api-reference/file-conventions/loading) |
| [**Client Cache TTL**](/docs/app/guides/caching#full-route-cache) | 5 min (default) | Off, unless [enabled](/docs/app/api-reference/config/next-config-js/staleTimes) | | [**Client Cache TTL**](/docs/app/guides/caching#full-route-cache) | 5 min (default) | Off, unless [enabled](/docs/app/api-reference/config/next-config-js/staleTimes) |
| **Server roundtrip on click** | No | Yes, streamed after [shell](/docs/app/getting-started/partial-prerendering#how-does-partial-prerendering-work) | | **Server roundtrip on click** | No | Yes, streamed after [shell](/docs/app/getting-started/cache-components) |
> **Good to know:** During the initial navigation, the browser fetches the HTML, JavaScript, and React Server Components (RSC) Payload. For subsequent navigations, the browser will fetch the RSC Payload for Server Components and JS bundle for Client Components. > **Good to know:** During the initial navigation, the browser fetches the HTML, JavaScript, and React Server Components (RSC) Payload. For subsequent navigations, the browser will fetch the RSC Payload for Server Components and JS bundle for Client Components.
......
...@@ -17,7 +17,7 @@ These Next.js optimizations are enabled by default and require no configuration: ...@@ -17,7 +17,7 @@ These Next.js optimizations are enabled by default and require no configuration:
- **[Server Components](/docs/app/getting-started/server-and-client-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/getting-started/server-and-client-components) as needed for interactivity. - **[Server Components](/docs/app/getting-started/server-and-client-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/getting-started/server-and-client-components) as needed for interactivity.
- **[Code-splitting](/docs/app/getting-started/linking-and-navigating#how-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Code-splitting](/docs/app/getting-started/linking-and-navigating#how-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate.
- **[Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate.
- **[Static Rendering](/docs/app/getting-started/partial-prerendering#static-rendering):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} - **[Static Rendering](/docs/app/guides/caching#static-rendering):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/guides/caching#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */}
- **[Caching](/docs/app/guides/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. - **[Caching](/docs/app/guides/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate.
</AppOnly> </AppOnly>
...@@ -44,7 +44,7 @@ While building your application, we recommend using the following features to en ...@@ -44,7 +44,7 @@ While building your application, we recommend using the following features to en
- **[`<Link>` component](/docs/app/api-reference/components/link):** Use the `<Link>` component for [client-side navigation and prefetching](/docs/app/getting-started/linking-and-navigating#how-navigation-works). - **[`<Link>` component](/docs/app/api-reference/components/link):** Use the `<Link>` component for [client-side navigation and prefetching](/docs/app/getting-started/linking-and-navigating#how-navigation-works).
- **[Error Handling](/docs/app/getting-started/error-handling):** Gracefully handle [catch-all errors](/docs/app/getting-started/error-handling) and [404 errors](/docs/app/api-reference/file-conventions/not-found) in production by creating custom error pages. - **[Error Handling](/docs/app/getting-started/error-handling):** Gracefully handle [catch-all errors](/docs/app/getting-started/error-handling) and [404 errors](/docs/app/api-reference/file-conventions/not-found) in production by creating custom error pages.
- **[Client and Server Components](/docs/app/getting-started/server-and-client-components#examples):** Follow the recommended composition patterns for Server and Client Components, and check the placement of your [`"use client"` boundaries](/docs/app/getting-started/server-and-client-components#examples#moving-client-components-down-the-tree) to avoid unnecessarily increasing your client-side JavaScript bundle. - **[Client and Server Components](/docs/app/getting-started/server-and-client-components#examples):** Follow the recommended composition patterns for Server and Client Components, and check the placement of your [`"use client"` boundaries](/docs/app/getting-started/server-and-client-components#examples#moving-client-components-down-the-tree) to avoid unnecessarily increasing your client-side JavaScript bundle.
- **[Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering):** Be aware that Dynamic APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop will opt the entire route into [Dynamic Rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) (or your whole application if used in the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout)). Ensure Dynamic API usage is intentional and wrap them in `<Suspense>` boundaries where appropriate. - **[Dynamic APIs](/docs/app/guides/caching#dynamic-rendering):** Be aware that Dynamic APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop will opt the entire route into [Dynamic Rendering](/docs/app/guides/caching#dynamic-rendering) (or your whole application if used in the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout)). Ensure Dynamic API usage is intentional and wrap them in `<Suspense>` boundaries where appropriate.
> **Good to know**: [Partial Prerendering (experimental)](/blog/next-14#partial-prerendering-preview) will allow parts of a route to be dynamic without opting the whole route into dynamic rendering. > **Good to know**: [Partial Prerendering (experimental)](/blog/next-14#partial-prerendering-preview) will allow parts of a route to be dynamic without opting the whole route into dynamic rendering.
......
...@@ -208,9 +208,9 @@ module.exports = { ...@@ -208,9 +208,9 @@ module.exports = {
} }
``` ```
## Partial Prerendering ## Cache Components
[Partial Prerendering (experimental)](/docs/app/getting-started/partial-prerendering) works by default with Next.js and is not a CDN-only feature. This includes deployment as a Node.js server (through `next start`) and when used with a Docker container. [Cache Components](/docs/app/getting-started/cache-components) works by default with Next.js and is not a CDN-only feature. This includes deployment as a Node.js server (through `next start`) and when used with a Docker container.
## Usage with CDNs ## Usage with CDNs
......
...@@ -105,7 +105,7 @@ The return value of the cacheable function must be serializable. This ensures th ...@@ -105,7 +105,7 @@ The return value of the cacheable function must be serializable. This ensures th
When used at the top of a [layout](/docs/app/api-reference/file-conventions/layout) or [page](/docs/app/api-reference/file-conventions/page), the route segment will be prerendered, allowing it to later be [revalidated](#during-revalidation). When used at the top of a [layout](/docs/app/api-reference/file-conventions/layout) or [page](/docs/app/api-reference/file-conventions/page), the route segment will be prerendered, allowing it to later be [revalidated](#during-revalidation).
This means `use cache` cannot be used with [request-time APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) like `cookies` or `headers`. This means `use cache` cannot be used with [runtime data](/docs/app/getting-started/cache-components#1-suspense-for-runtime-data) like `cookies` or `headers`.
> **Note:** If you need to cache content that depends on cookies, headers, or search params, use [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private) instead. > **Note:** If you need to cache content that depends on cookies, headers, or search params, use [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private) instead.
...@@ -187,7 +187,7 @@ export default function Page() { ...@@ -187,7 +187,7 @@ export default function Page() {
> **Good to know**: > **Good to know**:
> >
> - If `use cache` is added only to the `layout` or the `page`, only that route segment and any components imported into it will be cached. > - If `use cache` is added only to the `layout` or the `page`, only that route segment and any components imported into it will be cached.
> - If any of the nested children in the route use [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering), then the route will opt out of prerendering. > - If any of the nested children in the route use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering), then the route will opt out of pre-rendering.
### Caching a component's output with `use cache` ### Caching a component's output with `use cache`
......
...@@ -166,7 +166,7 @@ export default function Icon() { ...@@ -166,7 +166,7 @@ export default function Icon() {
> **Good to know**: > **Good to know**:
> >
> - By default, generated icons are [**statically optimized**](/docs/app/getting-started/partial-prerendering#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering#dynamic-apis) or uncached data. > - By default, generated icons are [**statically optimized**](/docs/app/guides/caching#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) or uncached data.
> - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
> - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead. > - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead.
> - App icons are special Route Handlers that are cached by default unless they use a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > - App icons are special Route Handlers that are cached by default unless they use a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option.
......
...@@ -88,7 +88,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi ...@@ -88,7 +88,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi
> **Good to know**: > **Good to know**:
> >
> - By default, generated images are [**statically optimized**](/docs/app/getting-started/partial-prerendering#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering#dynamic-apis) or uncached data. > - By default, generated images are [**statically optimized**](/docs/app/guides/caching#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) or uncached data.
> - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option.
...@@ -330,7 +330,7 @@ export default function Image() {} ...@@ -330,7 +330,7 @@ export default function Image() {}
This example uses the `params` object and external data to generate the image. This example uses the `params` object and external data to generate the image.
> **Good to know**: > **Good to know**:
> By default, this generated image will be [statically optimized](/docs/app/getting-started/partial-prerendering#static-rendering). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior. > By default, this generated image will be [statically optimized](/docs/app/guides/caching#static-rendering). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher ```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
......
...@@ -149,7 +149,7 @@ export default async function Page(props: PageProps<'/[locale]'>) { ...@@ -149,7 +149,7 @@ export default async function Page(props: PageProps<'/[locale]'>) {
### With `generateStaticParams` ### With `generateStaticParams`
The [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) function can be used to [statically generate](/docs/app/getting-started/partial-prerendering#static-rendering) routes at build time instead of on-demand at request time. The [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) function can be used to [statically generate](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
export async function generateStaticParams() { export async function generateStaticParams() {
......
...@@ -115,7 +115,7 @@ export default function Page({ searchParams }) { ...@@ -115,7 +115,7 @@ export default function Page({ searchParams }) {
- Since the `searchParams` prop is a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access the values. - Since the `searchParams` prop is a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access the values.
- In version 14 and earlier, `searchParams` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `searchParams` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- `searchParams` is a **[Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering)** at request time. - `searchParams` is a **[Dynamic API](/docs/app/guides/caching#dynamic-rendering)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/guides/caching#dynamic-rendering)** at request time.
- `searchParams` is a plain JavaScript object, not a `URLSearchParams` instance. - `searchParams` is a plain JavaScript object, not a `URLSearchParams` instance.
### Page Props Helper ### Page Props Helper
......
...@@ -66,7 +66,7 @@ export default function Layout({ children, team, analytics }) { ...@@ -66,7 +66,7 @@ export default function Layout({ children, team, analytics }) {
} }
``` ```
However, slots are **not** route segments and do not affect the URL structure. For example, for `/@analytics/views`, the URL will be `/views` since `@analytics` is a slot. Slots are combined with the regular [Page](/docs/app/api-reference/file-conventions/page) component to form the final page associated with the route segment. Because of this, you cannot have separate [static](/docs/app/getting-started/partial-prerendering#static-rendering) and [dynamic](/docs/app/getting-started/partial-prerendering#dynamic-rendering) slots at the same route segment level. If one slot is dynamic, all slots at that level must be dynamic. However, slots are **not** route segments and do not affect the URL structure. For example, for `/@analytics/views`, the URL will be `/views` since `@analytics` is a slot. Slots are combined with the regular [Page](/docs/app/api-reference/file-conventions/page) component to form the final page associated with the route segment. Because of this, you cannot have separate [static](/docs/app/guides/caching#static-rendering) and [dynamic](/docs/app/guides/caching#dynamic-rendering) slots at the same route segment level. If one slot is dynamic, all slots at that level must be dynamic.
> **Good to know**: > **Good to know**:
> >
......
...@@ -40,11 +40,11 @@ export const dynamic = 'auto' ...@@ -40,11 +40,11 @@ export const dynamic = 'auto'
> **Good to know**: The new model in the `app` directory favors granular caching control at the `fetch` request level over the binary all-or-nothing model of `getServerSideProps` and `getStaticProps` at the page-level in the `pages` directory. The `dynamic` option is a way to opt back in to the previous model as a convenience and provides a simpler migration path. > **Good to know**: The new model in the `app` directory favors granular caching control at the `fetch` request level over the binary all-or-nothing model of `getServerSideProps` and `getStaticProps` at the page-level in the `pages` directory. The `dynamic` option is a way to opt back in to the previous model as a convenience and provides a simpler migration path.
- **`'auto'`** (default): The default option to cache as much as possible without preventing any components from opting into dynamic behavior. - **`'auto'`** (default): The default option to cache as much as possible without preventing any components from opting into dynamic behavior.
- **`'force-dynamic'`**: Force [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering), which will result in routes being rendered for each user at request time. This option is equivalent to: - **`'force-dynamic'`**: Force [dynamic rendering](/docs/app/guides/caching#dynamic-rendering), which will result in routes being rendered for each user at request time. This option is equivalent to:
- Setting the option of every `fetch()` request in a layout or page to `{ cache: 'no-store', next: { revalidate: 0 } }`. - Setting the option of every `fetch()` request in a layout or page to `{ cache: 'no-store', next: { revalidate: 0 } }`.
- Setting the segment config to `export const fetchCache = 'force-no-store'` - Setting the segment config to `export const fetchCache = 'force-no-store'`
- **`'error'`**: Force static rendering and cache the data of a layout or page by causing an error if any components use [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) or uncached data. This option is equivalent to: - **`'error'`**: Force static rendering and cache the data of a layout or page by causing an error if any components use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) or uncached data. This option is equivalent to:
- `getStaticProps()` in the `pages` directory. - `getStaticProps()` in the `pages` directory.
- Setting the option of every `fetch()` request in a layout or page to `{ cache: 'force-cache' }`. - Setting the option of every `fetch()` request in a layout or page to `{ cache: 'force-cache' }`.
- Setting the segment config to `fetchCache = 'only-cache'`. - Setting the segment config to `fetchCache = 'only-cache'`.
...@@ -89,8 +89,8 @@ export const revalidate = false ...@@ -89,8 +89,8 @@ export const revalidate = false
// false | 0 | number // false | 0 | number
``` ```
- **`false`** (default): The default heuristic to cache any `fetch` requests that set their `cache` option to `'force-cache'` or are discovered before a [Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering#dynamic-apis) is used. Semantically equivalent to `revalidate: Infinity` which effectively means the resource should be cached indefinitely. It is still possible for individual `fetch` requests to use `cache: 'no-store'` or `revalidate: 0` to avoid being cached and make the route dynamically rendered. Or set `revalidate` to a positive number lower than the route default to increase the revalidation frequency of a route. - **`false`** (default): The default heuristic to cache any `fetch` requests that set their `cache` option to `'force-cache'` or are discovered before a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) is used. Semantically equivalent to `revalidate: Infinity` which effectively means the resource should be cached indefinitely. It is still possible for individual `fetch` requests to use `cache: 'no-store'` or `revalidate: 0` to avoid being cached and make the route dynamically rendered. Or set `revalidate` to a positive number lower than the route default to increase the revalidation frequency of a route.
- **`0`**: Ensure a layout or page is always [dynamically rendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering) even if no Dynamic APIs or uncached data fetches are discovered. This option changes the default of `fetch` requests that do not set a `cache` option to `'no-store'` but leaves `fetch` requests that opt into `'force-cache'` or use a positive `revalidate` as is. - **`0`**: Ensure a layout or page is always [dynamically rendered](/docs/app/guides/caching#dynamic-rendering) even if no Dynamic APIs or uncached data fetches are discovered. This option changes the default of `fetch` requests that do not set a `cache` option to `'no-store'` but leaves `fetch` requests that opt into `'force-cache'` or use a positive `revalidate` as is.
- **`number`**: (in seconds) Set the default revalidation frequency of a layout or page to `n` seconds. - **`number`**: (in seconds) Set the default revalidation frequency of a layout or page to `n` seconds.
> **Good to know**: > **Good to know**:
...@@ -109,7 +109,7 @@ export const revalidate = false ...@@ -109,7 +109,7 @@ export const revalidate = false
<details> <details>
<summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary> <summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary>
By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering#dynamic-apis) are used and **will not cache** `fetch` requests that are discovered **after** Dynamic APIs are used. By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) are used and **will not cache** `fetch` requests that are discovered **after** Dynamic APIs are used.
`fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page. `fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page.
......
...@@ -37,7 +37,7 @@ export default function Layout({ children }) { ...@@ -37,7 +37,7 @@ export default function Layout({ children }) {
} }
``` ```
> **Good to know:** `after` is not a [Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering) and calling it does not cause a route to become dynamic. If it's used within a static page, the callback will execute at build time, or whenever a page is revalidated. > **Good to know:** `after` is not a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) and calling it does not cause a route to become dynamic. If it's used within a static page, the callback will execute at build time, or whenever a page is revalidated.
## Reference ## Reference
...@@ -111,7 +111,7 @@ export async function POST(request) { ...@@ -111,7 +111,7 @@ export async function POST(request) {
} }
``` ```
However, you cannot use these request APIs inside `after` in [Server Components](/docs/app/getting-started/server-and-client-components). This is because Next.js needs to know which part of the tree access the request APIs to support [Partial Prerendering](/docs/app/getting-started/partial-prerendering), but `after` runs after React's rendering lifecycle. However, you cannot use these request APIs inside `after` in [Server Components](/docs/app/getting-started/server-and-client-components). This is because Next.js needs to know which part of the tree access the request APIs to support [Cache Components](/docs/app/getting-started/cache-components), but `after` runs after React's rendering lifecycle.
## Platform Support ## Platform Support
......
...@@ -5,7 +5,7 @@ description: API Reference for the connection function. ...@@ -5,7 +5,7 @@ description: API Reference for the connection function.
The `connection()` function allows you to indicate rendering should wait for an incoming user request before continuing. The `connection()` function allows you to indicate rendering should wait for an incoming user request before continuing.
It's useful when a component doesn’t use [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering), but you want it to be dynamically rendered at runtime and not statically rendered at build time. This usually occurs when you access external information that you intentionally want to change the result of a render, such as `Math.random()` or `new Date()`. It's useful when a component doesn't use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering), but you want it to be dynamically rendered at runtime and not statically rendered at build time. This usually occurs when you access external information that you intentionally want to change the result of a render, such as `Math.random()` or `new Date()`.
```ts filename="app/page.tsx" switcher ```ts filename="app/page.tsx" switcher
import { connection } from 'next/server' import { connection } from 'next/server'
......
...@@ -67,7 +67,7 @@ To learn more about these options, see the [MDN docs](https://developer.mozilla. ...@@ -67,7 +67,7 @@ To learn more about these options, see the [MDN docs](https://developer.mozilla.
- `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access cookies. - `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access cookies.
- In version 14 and earlier, `cookies` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `cookies` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- `cookies` is a [Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering). - `cookies` is a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into [dynamic rendering](/docs/app/guides/caching#dynamic-rendering).
- The `.delete` method can only be called: - The `.delete` method can only be called:
- In a [Server Action](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route). - In a [Server Action](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
- If it belongs to the same domain from which `.set` is called. For wildcard domains, the specific subdomain must be an exact match. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete. - If it belongs to the same domain from which `.set` is called. For wildcard domains, the specific subdomain must be an exact match. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.
......
...@@ -49,7 +49,7 @@ Configure how the request should interact with Next.js [Data Cache](/docs/app/gu ...@@ -49,7 +49,7 @@ Configure how the request should interact with Next.js [Data Cache](/docs/app/gu
fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
``` ```
- **`auto no cache`** (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during `next build` because the route will be statically prerendered. If [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) are detected on the route, Next.js will fetch the resource on every request. - **`auto no cache`** (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during `next build` because the route will be statically prerendered. If [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) are detected on the route, Next.js will fetch the resource on every request.
- **`no-store`**: Next.js fetches the resource from the remote server on every request, even if Dynamic APIs are not detected on the route. - **`no-store`**: Next.js fetches the resource from the remote server on every request, even if Dynamic APIs are not detected on the route.
- **`force-cache`**: Next.js looks for a matching request in its Data Cache. - **`force-cache`**: Next.js looks for a matching request in its Data Cache.
- If there is a match and it is fresh, it will be returned from the cache. - If there is a match and it is fresh, it will be returned from the cache.
......
...@@ -3,7 +3,7 @@ title: generateStaticParams ...@@ -3,7 +3,7 @@ title: generateStaticParams
description: API reference for the generateStaticParams function. description: API reference for the generateStaticParams function.
--- ---
The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/getting-started/partial-prerendering#static-rendering) routes at build time instead of on-demand at request time. The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
// Return a list of `params` to populate the [slug] dynamic segment // Return a list of `params` to populate the [slug] dynamic segment
......
...@@ -45,7 +45,7 @@ export default async function Page() { ...@@ -45,7 +45,7 @@ export default async function Page() {
- `headers` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function. - `headers` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function.
- In version 14 and earlier, `headers` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `headers` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- Since `headers` is read-only, you cannot `set` or `delete` the outgoing request headers. - Since `headers` is read-only, you cannot `set` or `delete` the outgoing request headers.
- `headers` is a [Dynamic API](/docs/app/getting-started/partial-prerendering#dynamic-rendering#dynamic-apis) whose returned values cannot be known ahead of time. Using it in will opt a route into **[dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering)**. - `headers` is a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in will opt a route into **[dynamic rendering](/docs/app/guides/caching#dynamic-rendering)**.
## Examples ## Examples
......
...@@ -112,7 +112,7 @@ export default function Layout({ children }) { ...@@ -112,7 +112,7 @@ export default function Layout({ children }) {
} }
``` ```
> **Good to know**: `<NavigationEvents>` is wrapped in a [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/getting-started/partial-prerendering#static-rendering). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior). > **Good to know**: `<NavigationEvents>` is wrapped in a [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/guides/caching#static-rendering). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior).
### Disabling scroll to top ### Disabling scroll to top
......
...@@ -79,7 +79,7 @@ const searchParams = useSearchParams() ...@@ -79,7 +79,7 @@ const searchParams = useSearchParams()
### Static Rendering ### Static Rendering
If a route is [statically rendered](/docs/app/getting-started/partial-prerendering#static-rendering), calling `useSearchParams` will cause the Client Component tree up to the closest [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) to be client-side rendered. If a route is [statically rendered](/docs/app/guides/caching#static-rendering), calling `useSearchParams` will cause the Client Component tree up to the closest [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) to be client-side rendered.
This allows a part of the route to be statically rendered while the dynamic part that uses `useSearchParams` is client-side rendered. This allows a part of the route to be statically rendered while the dynamic part that uses `useSearchParams` is client-side rendered.
...@@ -176,14 +176,14 @@ export default function Page() { ...@@ -176,14 +176,14 @@ export default function Page() {
> **Good to know**: > **Good to know**:
> >
> - In development, routes are rendered on-demand, so `useSearchParams` doesn't suspend and things may appear to work without `Suspense`. > - In development, routes are rendered on-demand, so `useSearchParams` doesn't suspend and things may appear to work without `Suspense`.
> - During production builds, a [static page](/docs/app/getting-started/partial-prerendering#static-rendering) that calls `useSearchParams` from a Client Component must be wrapped in a `Suspense` boundary, otherwise the build fails with the [Missing Suspense boundary with useSearchParams](/docs/messages/missing-suspense-with-csr-bailout) error. > - During production builds, a [static page](/docs/app/guides/caching#static-rendering) that calls `useSearchParams` from a Client Component must be wrapped in a `Suspense` boundary, otherwise the build fails with the [Missing Suspense boundary with useSearchParams](/docs/messages/missing-suspense-with-csr-bailout) error.
> - If you intend the route to be dynamically rendered, prefer using the [`connection`](/docs/app/api-reference/functions/connection) function first in a Server Component to wait for an incoming request, this excludes everything below from prerendering. See what makes a route dynamic in the [Dynamic Rendering guide](/docs/app/getting-started/partial-prerendering#dynamic-rendering). > - If you intend the route to be dynamically rendered, prefer using the [`connection`](/docs/app/api-reference/functions/connection) function first in a Server Component to wait for an incoming request, this excludes everything below from prerendering. See what makes a route dynamic in the [Dynamic Rendering guide](/docs/app/guides/caching#dynamic-rendering).
> - If you're already in a Server Component Page, consider using the [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) and passing the values to Client Components. > - If you're already in a Server Component Page, consider using the [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) and passing the values to Client Components.
> - You can also pass the Page [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) directly to a Client Component and unwrap it with React's `use()`. Although this will suspend, so the Client Component should be wrapped with a `Suspense` boundary. > - You can also pass the Page [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) directly to a Client Component and unwrap it with React's `use()`. Although this will suspend, so the Client Component should be wrapped with a `Suspense` boundary.
### Dynamic Rendering ### Dynamic Rendering
If a route is [dynamically rendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component. If a route is [dynamically rendered](/docs/app/guides/caching#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
For example: For example:
......
...@@ -22,7 +22,7 @@ Setting `devIndicators` to `false` will hide the indicator, however Next.js will ...@@ -22,7 +22,7 @@ Setting `devIndicators` to `false` will hide the indicator, however Next.js will
If you expect a route to be static and the indicator has marked it as dynamic, it's likely the route has opted out of static rendering. If you expect a route to be static and the indicator has marked it as dynamic, it's likely the route has opted out of static rendering.
You can confirm if a route is [static](/docs/app/getting-started/partial-prerendering#static-rendering) or [dynamic](/docs/app/getting-started/partial-prerendering#dynamic-rendering) by building your application using `next build --debug`, and checking the output in your terminal. Static (or prerendered) routes will display a `○` symbol, whereas dynamic routes will display a `ƒ` symbol. For example: You can confirm if a route is [static](/docs/app/guides/caching#static-rendering) or [dynamic](/docs/app/guides/caching#dynamic-rendering) by building your application using `next build --debug`, and checking the output in your terminal. Static (or prerendered) routes will display a `○` symbol, whereas dynamic routes will display a `ƒ` symbol. For example:
```bash filename="Build Output" ```bash filename="Build Output"
Route (app) Route (app)
...@@ -37,7 +37,7 @@ Route (app) ...@@ -37,7 +37,7 @@ Route (app)
There are two reasons a route might opt out of static rendering: There are two reasons a route might opt out of static rendering:
- The presence of [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) which rely on runtime information. - The presence of [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) which rely on runtime information.
- An [uncached data request](/docs/app/getting-started/fetching-data), like a call to an ORM or database driver. - An [uncached data request](/docs/app/getting-started/fetching-data), like a call to an ORM or database driver.
Check your route for any of these conditions, and if you are not able to statically render the route, then consider using [`loading.js`](/docs/app/api-reference/file-conventions/loading) or [`<Suspense />`](https://react.dev/reference/react/Suspense) to leverage [streaming](/docs/app/getting-started/linking-and-navigating#streaming). Check your route for any of these conditions, and if you are not able to statically render the route, then consider using [`loading.js`](/docs/app/api-reference/file-conventions/loading) or [`<Suspense />`](https://react.dev/reference/react/Suspense) to leverage [streaming](/docs/app/getting-started/linking-and-navigating#streaming).
......
---
title: ppr
description: Learn how to enable Partial Prerendering in Next.js.
version: canary
related:
title: Learn more about Partial Prerendering
links:
- app/getting-started/partial-prerendering
---
Partial Prerendering (PPR) enables you to combine static and dynamic components together in the same route. Learn more about [PPR](/docs/app/getting-started/partial-prerendering).
## Using Partial Prerendering
### Incremental Adoption (Version 15)
In Next.js 15, you can incrementally adopt Partial Prerendering in [layouts](/docs/app/api-reference/file-conventions/layout) and [pages](/docs/app/api-reference/file-conventions/page) by setting the [`ppr`](/docs/app/api-reference/config/next-config-js/ppr) option in `next.config.js` to `incremental`, and exporting the `experimental_ppr` [route config option](/docs/app/api-reference/file-conventions/route-segment-config) at the top of the file:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
ppr: 'incremental',
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
ppr: 'incremental',
},
}
module.exports = nextConfig
```
```tsx filename="app/page.tsx" switcher
import { Suspense } from "react"
import { StaticComponent, DynamicComponent, Fallback } from "@/app/ui"
export const experimental_ppr = true
export default function Page() {
return {
<>
<StaticComponent />
<Suspense fallback={<Fallback />}>
<DynamicComponent />
</Suspense>
</>
};
}
```
```jsx filename="app/page.js" switcher
import { Suspense } from "react"
import { StaticComponent, DynamicComponent, Fallback } from "@/app/ui"
export const experimental_ppr = true
export default function Page() {
return {
<>
<StaticComponent />
<Suspense fallback={<Fallback />}>
<DynamicComponent />
</Suspense>
</>
};
}
```
> **Good to know**:
>
> - Routes that don't have `experimental_ppr` will default to `false` and will not be prerendered using PPR. You need to explicitly opt-in to PPR for each route.
> - `experimental_ppr` will apply to all children of the route segment, including nested layouts and pages. You don't have to add it to every file, only the top segment of a route.
> - To disable PPR for children segments, you can set `experimental_ppr` to `false` in the child segment.
| Version | Changes |
| --------- | ------------------------------------------- |
| `v15.0.0` | experimental `incremental` value introduced |
| `v14.0.0` | experimental `ppr` introduced |
...@@ -19,5 +19,5 @@ To resolve this issue, you have two main options: ...@@ -19,5 +19,5 @@ To resolve this issue, you have two main options:
## Useful Links ## Useful Links
- [Static and Dynamic Rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) - Learn more about the differences between static and dynamic rendering in Next.js. - [Static and Dynamic Rendering](/docs/app/guides/caching#rendering-strategies) - Learn more about the differences between static and dynamic rendering in Next.js.
- [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) - Understand more about the usage of dynamic server functions in your Next.js application. - [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) - Understand more about the usage of dynamic server functions in your Next.js application.
...@@ -177,4 +177,4 @@ This configuration option will be removed in a future major version. ...@@ -177,4 +177,4 @@ This configuration option will be removed in a future major version.
- [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) - [`useSearchParams`](/docs/app/api-reference/functions/use-search-params)
- [`connection`](/docs/app/api-reference/functions/connection) - [`connection`](/docs/app/api-reference/functions/connection)
- [Dynamic Rendering guide](/docs/app/getting-started/partial-prerendering#dynamic-rendering) - [Dynamic Rendering guide](/docs/app/guides/caching#dynamic-rendering)
...@@ -5,7 +5,7 @@ description: Learn more about why accessing certain APIs synchronously now warns ...@@ -5,7 +5,7 @@ description: Learn more about why accessing certain APIs synchronously now warns
## Why This Warning Occurred ## Why This Warning Occurred
Somewhere in your code you used an API that opts into [dynamic rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering). Somewhere in your code you used an API that opts into [dynamic rendering](/docs/app/guides/caching#dynamic-rendering).
Dynamic APIs are: Dynamic APIs are:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment