Using`searchParams`optsyourpageinto[**dynamicrendering**](/docs/app/getting-started/partial-prerendering#dynamic-rendering) because it requires a incoming request to read the search parameters from.
Using`searchParams`optsyourpageinto[**dynamicrendering**](/docs/app/guides/caching#dynamic-rendering) because it requires a incoming request to read the search parameters from.
Ontheserver,Next.jsusesReact'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)):
Ontheserver,Next.jsusesReact'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)?**
- [`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'tmakethecomponentitselfdynamic(yourAPIusagedoes),butratherSuspenseisusedasaboundarythatencapsulatesdynamiccontentandenable[streaming](#streaming)
Routesthatdon'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'thavetoaddittoeveryfile,onlythetopsegmentofaroute.
@@ -57,7 +57,7 @@ export default async function Page() {
...
@@ -57,7 +57,7 @@ export default async function Page() {
>**Goodtoknow:**
>**Goodtoknow:**
>
>
>-`fetch`responsesarenotcachedbydefault.However,Next.jswill[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`responsesarenotcachedbydefault.However,Next.jswill[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).
Whenusing`async/await`inServerComponents,Next.jswilloptinto[dynamicrendering](/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.
Toimprovetheinitialloadtimeanduserexperience,youcanusestreamingtobreakupthepage's HTML into smaller chunks and progressively send those chunks from the server to the client.
Toimprovetheinitialloadtimeanduserexperience,youcanusestreamingtobreakupthepage'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() {
}
}
```
```
>**Goodtoknow**:Although`fetch`requestsarenotcachedbydefault,Next.jswill[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).
>**Goodtoknow**:Although`fetch`requestsarenotcachedbydefault,Next.jswill[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).
@@ -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'shelpfultounderstandtherenderingstrategiesavailable.Therenderingstrategydetermineswhenyourroute'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:
- [`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
Thecacheisstoredinthebrowser's temporary memory. Two factors determine how long the router cache lasts:
Thecacheisstoredinthebrowser's temporary memory. Two factors determine how long the router cache lasts:
- **Session**: The cache persists across navigation. However, it'sclearedonpagerefresh.
- **Session**: The cache persists across navigation. However, it'sclearedonpagerefresh.
-**AutomaticInvalidationPeriod**:Thecacheoflayoutsandloadingstatesisautomaticallyinvalidatedafteraspecifictime.Thedurationdependsonhowtheresourcewas[prefetched](/docs/app/api-reference/components/link#prefetch), and if the resource was [statically generated](/docs/app/getting-started/partial-prerendering#static-rendering):
-**AutomaticInvalidationPeriod**:Thecacheoflayoutsandloadingstatesisautomaticallyinvalidatedafteraspecifictime.Thedurationdependsonhowtheresourcewas[prefetched](/docs/app/api-reference/components/link#prefetch), and if the resource was [statically generated](#static-rendering):
-[Dynamicrendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering): Fetch runs on every request and always returns fresh data.
-[Dynamicrendering](#dynamic-rendering): Fetch runs on every request and always returns fresh data.
-[Staticrendering](/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.
-[Staticrendering](#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.
Everytimeapageisviewed,afreshnonceshouldbegenerated.Thismeansthatyou**mustuse[dynamicrendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) to add nonces**.
Everytimeapageisviewed,afreshnonceshouldbegenerated.Thismeansthatyou**mustuse[dynamicrendering](/docs/app/guides/caching#dynamic-rendering) to add nonces**.
**DraftMode**allowsyoutopreviewdraftcontentfromyourheadlessCMSinyourNext.jsapplication.Thisisusefulforstaticpagesthataregeneratedatbuildtimeasitallowsyoutoswitchto[dynamicrendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) and see the draft changes without having to rebuild your entire site.
**DraftMode**allowsyoutopreviewdraftcontentfromyourheadlessCMSinyourNext.jsapplication.Thisisusefulforstaticpagesthataregeneratedatbuildtimeasitallowsyoutoswitchto[dynamicrendering](/docs/app/guides/caching#dynamic-rendering) and see the draft changes without having to rebuild your entire site.
@@ -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
-Proxywon'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`.
-Proxywon'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`.
@@ -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).
| **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.
[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.
@@ -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 [`'usecache: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 [`'usecache: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.
@@ -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.
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.
- Since the `searchParams` prop is a promise. You must use `async/await` or React's[`use`](https://react.dev/reference/react/use)functiontoaccessthevalues.
- Since the `searchParams` prop is a promise. You must use `async/await` or React's[`use`](https://react.dev/reference/react/use)functiontoaccessthevalues.
-`searchParams`isa**[DynamicAPI](/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`isa**[DynamicAPI](/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.
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**: 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.
<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 }) {
}
}
```
```
>**Goodtoknow:**`after`isnota[DynamicAPI](/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.
>**Goodtoknow:**`after`isnota[DynamicAPI](/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) {
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'tuse[DynamicAPIs](/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()`.
@@ -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)functiontoaccesscookies.
- `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's[`use`](https://react.dev/reference/react/use)functiontoaccesscookies.
-`cookies`isa[DynamicAPI](/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`isa[DynamicAPI](/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).
-**`auto no cache`**(default):Next.jsfetchestheresourcefromtheremoteserveroneveryrequestindevelopment,butwillfetchonceduring`next build`becausetheroutewillbestaticallyprerendered.If[DynamicAPIs](/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.jsfetchestheresourcefromtheremoteserveroneveryrequestindevelopment,butwillfetchonceduring`next build`becausetheroutewillbestaticallyprerendered.If[DynamicAPIs](/docs/app/guides/caching#dynamic-rendering) are detected on the route, Next.js will fetch the resource on every request.
The`generateStaticParams`functioncanbeusedincombinationwith[dynamicroutesegments](/docs/app/api-reference/file-conventions/dynamic-routes)to[**staticallygenerate**](/docs/app/getting-started/partial-prerendering#static-rendering) routes at build time instead of on-demand at request time.
The`generateStaticParams`functioncanbeusedincombinationwith[dynamicroutesegments](/docs/app/api-reference/file-conventions/dynamic-routes)to[**staticallygenerate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time.
- 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)**.
@@ -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).
Ifarouteis[staticallyrendered](/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.
Ifarouteis[staticallyrendered](/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.
@@ -176,14 +176,14 @@ export default function Page() {
...
@@ -176,14 +176,14 @@ export default function Page() {
>**Goodtoknow**:
>**Goodtoknow**:
>
>
>-Indevelopment,routesarerenderedon-demand,so`useSearchParams`doesn't suspend and things may appear to work without `Suspense`.
>-Indevelopment,routesarerenderedon-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'realreadyinaServerComponentPage,considerusingthe[`searchParams`prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) and passing the values to Client Components.
> - If you'realreadyinaServerComponentPage,considerusingthe[`searchParams`prop](/docs/app/api-reference/file-conventions/page#searchparams-optional) and passing the values to Client Components.
>-YoucanalsopassthePage[`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.
>-YoucanalsopassthePage[`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
Ifarouteis[dynamicallyrendered](/docs/app/getting-started/partial-prerendering#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
Ifarouteis[dynamicallyrendered](/docs/app/guides/caching#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
@@ -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).
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.
@@ -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.