Unverified Commit 93c861d6 authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

Docs: Next.js 15 updates (#65603)

React 19
- [x] React Compiler
- [x] Check all examples for new API usage e.g.`useActionState`, `use`
- [x] Review Server Actions page and link to React docs.


Next.js 15

- [x] PPR incremental adoption and placeholder page - for SEO
- [x] `next/after`
- [x] Package bundling
- [x] Upgrade guide
- [x] Clarify new `fetch` behavior
- [x] Route handlers - dynamic 
- [x] Client-side router cache
- [x] Add "Good to know" about metadata route handlers being cached

15 and beyond
- [x] Remove recommendations for `revalidate = low value` 
- [x] Review and consolidate data fetching section
  - [ ] Client-side data fetching patterns 
    - [ ] Streaming data pattern with React `use`
    - [ ] Seeding initial data from the server

Redirects and blog post: https://github.com/vercel/front/pull/32249

---------
Co-authored-by: 's avatarAhmed Abdelbaset <A7med3bdulBaset@gmail.com>
Co-authored-by: 's avatarAnthony Shew <anthonyshew@gmail.com>
Co-authored-by: 's avatarMichael Novotny <manovotny@gmail.com>
Co-authored-by: 's avatarEthan Arrowood <ethan@arrowood.dev>
Co-authored-by: 's avatarStephDietz <steph.dietz@vercel.com>
Co-authored-by: 's avatarStephanie Dietz <49788645+StephDietz@users.noreply.github.com>
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 59ce87e5
...@@ -368,11 +368,11 @@ See the [`<Link>` API reference](/docs/app/api-reference/components/link) for mo ...@@ -368,11 +368,11 @@ See the [`<Link>` API reference](/docs/app/api-reference/components/link) for mo
### 3. Caching ### 3. Caching
Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/caching#router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache.
This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred. This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred.
Learn more about how the [Router Cache](/docs/app/building-your-application/caching#router-cache) works and how to configure it. Learn more about how the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) works and how to configure it.
### 4. Partial Rendering ### 4. Partial Rendering
...@@ -396,7 +396,7 @@ Browsers perform a "hard navigation" when navigating between pages. The Next.js ...@@ -396,7 +396,7 @@ Browsers perform a "hard navigation" when navigating between pages. The Next.js
### 6. Back and Forward Navigation ### 6. Back and Forward Navigation
By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/caching#router-cache). By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache).
### 7. Routing between `pages/` and `app/` ### 7. Routing between `pages/` and `app/`
......
...@@ -32,7 +32,7 @@ export async function GET(request: Request) {} ...@@ -32,7 +32,7 @@ export async function GET(request: Request) {}
export async function GET(request) {} export async function GET(request) {}
``` ```
Route Handlers can be nested inside the `app` directory, similar to `page.js` and `layout.js`. But there **cannot** be a `route.js` file at the same route segment level as `page.js`. Route Handlers can be nested anywhere inside the `app` directory, similar to `page.js` and `layout.js`. But there **cannot** be a `route.js` file at the same route segment level as `page.js`.
### Supported HTTP Methods ### Supported HTTP Methods
...@@ -40,18 +40,16 @@ The following [HTTP methods](https://developer.mozilla.org/docs/Web/HTTP/Methods ...@@ -40,18 +40,16 @@ The following [HTTP methods](https://developer.mozilla.org/docs/Web/HTTP/Methods
### Extended `NextRequest` and `NextResponse` APIs ### Extended `NextRequest` and `NextResponse` APIs
In addition to supporting native [Request](https://developer.mozilla.org/docs/Web/API/Request) and [Response](https://developer.mozilla.org/docs/Web/API/Response). Next.js extends them with In addition to supporting the native [Request](https://developer.mozilla.org/docs/Web/API/Request) and [Response](https://developer.mozilla.org/docs/Web/API/Response) APIs, Next.js extends them with [`NextRequest`](/docs/app/api-reference/functions/next-request) and [`NextResponse`](/docs/app/api-reference/functions/next-response) to provide convenient helpers for advanced use cases.
[`NextRequest`](/docs/app/api-reference/functions/next-request) and [`NextResponse`](/docs/app/api-reference/functions/next-response) to provide convenient helpers for advanced use cases.
## Behavior ## Behavior
### Caching ### Caching
Route Handlers are dynamic by default as of Next.js v15. To opt-in to caching for `GET` requests, you can use the following config: Route Handlers are not cached by default. You can, however, opt into caching for `GET` methods. To do so, use a [route config option](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) such as `export const dynamic = 'force-static'` in your Route Handler file.
```ts filename="app/items/route.ts" switcher ```ts filename="app/items/route.ts" switcher
// opt in to caching the route handler export const dynamic = 'force-static'
export const dynamic = 'force-static' // or 'error'
export async function GET() { export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', { const res = await fetch('https://data.mongodb-api.com/...', {
...@@ -67,6 +65,8 @@ export async function GET() { ...@@ -67,6 +65,8 @@ export async function GET() {
``` ```
```js filename="app/items/route.js" switcher ```js filename="app/items/route.js" switcher
export const dynamic = 'force-static'
export async function GET() { export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', { const res = await fetch('https://data.mongodb-api.com/...', {
headers: { headers: {
...@@ -80,7 +80,9 @@ export async function GET() { ...@@ -80,7 +80,9 @@ export async function GET() {
} }
``` ```
> **TypeScript Warning:** `Response.json()` is only valid from TypeScript 5.2. If you use a lower TypeScript version, you can use [`NextResponse.json()`](/docs/app/api-reference/functions/next-response#json) for typed responses instead. ### Special Route Handlers
Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) remain static by default unless they use dynamic functions or dynamic config options.
### Route Resolution ### Route Resolution
...@@ -113,7 +115,7 @@ The following examples show how to combine Route Handlers with other Next.js API ...@@ -113,7 +115,7 @@ The following examples show how to combine Route Handlers with other Next.js API
### Revalidating Cached Data ### Revalidating Cached Data
You can [revalidate cached data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) option: You can [revalidate cached data](/docs/app/building-your-application/data-fetching/caching-and-revalidating#revalidating-data) using the [`next.revalidate`](/docs/app/building-your-application/data-fetching/caching-and-revalidating#revalidating-data) option:
```ts filename="app/items/route.ts" switcher ```ts filename="app/items/route.ts" switcher
export async function GET() { export async function GET() {
......
---
title: Caching and Revalidating
nav_title: Caching and Revalidating
description: Learn how to cache and revalidate data in your Next.js application.
---
## Caching
Caching is the process of storing data to reduce the number of requests made to the server. Next.js provides a built-in [Data Cache](/docs/app/building-your-application/caching) for individual data requests, giving you granular control of caching behavior.
### `fetch` requests
By default, `fetch` requests fetch fresh data at runtime.
To cache an individual `fetch` request, you can use the `cache: 'force-cache'` option:
```js
// 'force-cache' is the default, and can be omitted
fetch('https://...', { cache: 'force-cache' })
```
To opt out of caching for individual `fetch` requests, you can use the `cache: 'no-store'` option:
```js filename="layout.js | page.js"
fetch('https://...', { cache: 'no-store' })
```
> **Advanced**: If you have multiple `fetch` requests in a layout or page segment, you can configure the caching behavior of all data requests in the segment using the `const dynamic = 'force-dynamic'` or `const fetchCache = 'force-no-store'` [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config).
### Data fetching libraries and ORMs
Whether a data request is cached will depend on the default semantics of your Data Fetching Library, Database Client, or ORM.
To cache specific requests, you can use the [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) API:
```tsx filename="@/app/lib/data.ts switcher highlight={6}
import { unstable_cache as cache } from 'next/cache'
export async function getPosts() {
cache()
try {
// Fetch Data
} catch (error) {}
}
```
```jsx filename="@/app/lib/data.js switcher highlight={6}
import { unstable_cache as cache } from 'next/cache'
export async function getPosts() {
cache()
try {
// Fetch Data
} catch (error) {}
}
```
To opt specific requests out of caching, you can use the [`unstable_noStore`](/docs/app/api-reference/functions/unstable_noStore) API:
```tsx filename="@/app/lib/data.ts switcher highlight={6}
import { unstable_noStore as noStore } from 'next/cache'
export async function getTransactions() {
// Prevent the response from being cached.
// This is equivalent to in fetch(..., {cache: 'no-store'}).
noStore()
try {
// Fetch Data
} catch (error) {}
}
```
```jsx filename="@/app/lib/data.js switcher highlight={6}
import { unstable_noStore as noStore } from 'next/cache'
export async function getTransactions() {
// Prevent the response from being cached.
// This is equivalent to in fetch(..., {cache: 'no-store'}).
noStore()
try {
// Fetch Data
} catch (error) {}
}
```
## Revalidating data
Revalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information while still benefiting from the speed of static rendering.
Cached data can be revalidated in two ways:
- **Time-based revalidation**: Automatically revalidate data after a certain amount of time has passed. This is useful for data that changes infrequently and freshness is not as critical.
- **On-demand revalidation**: Manually revalidate data based on an event (e.g. form submission). On-demand revalidation can use a tag-based or path-based approach to revalidate groups of data at once. This is useful when you want to ensure the latest data is shown as soon as possible (e.g. when content from your headless CMS is updated).
### Time-based revalidation
To revalidate data at a timed interval, you can use the `next.revalidate` option of `fetch` to set the cache lifetime of a resource (in seconds).
```js
fetch('https://...', { next: { revalidate: 3600 } }) // revalidate at most every hour
```
Alternatively, to revalidate all requests in a route segment, you can use the [Segment Config Options](/docs/app/api-reference/file-conventions/route-segment-config).
```jsx filename="layout.js | page.js"
export const revalidate = 3600 // revalidate at most every hour
```
Learn [how time-based revalidation works](/docs/app/building-your-application/caching#revalidating-1)
> **Good to know:**
>
> - If you have multiple fetch requests in a statically rendered route, and each has a different revalidation frequency. The lowest time will be used for all requests.
> - For dynamically rendered routes, each `fetch` request will be revalidated independently.
> - To save server resources, we recommend setting a high revalidation time whenever possible. For instance, 1 hour instead of 1 second. If you need real-time data, consider switching to [dynamic rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) or client-side data fetching.
### On-demand revalidation
Data can be revalidated on-demand with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) and [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) APIs.
Use `revalidatePath` in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) or [Route Handler](/docs/app/building-your-application/routing/route-handlers) to revalidate data for specific routes:
```tsx filename="@/app/actions.tsx switcher
import { revalidatePath } from 'next/cache'
export default async createPost() {
try {
// Mutate data
revalidatePath('/posts')
} catch(error) {}
}
```
```jsx filename="@/app/actions.js switcher
import { revalidatePath } from 'next/cache'
export default async createPost() {
try {
// Mutate data
revalidatePath('/posts')
} catch(error) {}
}
```
Use `revalidateTag` to revalidate `fetch` requests across routes.
1. When using `fetch`, you have the option to tag cache entries with one or more tags.
2. Then, you can call `revalidateTag` to revalidate all entries associated with that tag.
For example, the following `fetch` request adds the cache tag `collection`:
```tsx filename="app/page.tsx" switcher
export default async function Page() {
const res = await fetch('https://...', { next: { tags: ['collection'] } })
const data = await res.json()
// ...
}
```
```jsx filename="app/page.js" switcher
export default async function Page() {
const res = await fetch('https://...', { next: { tags: ['collection'] } })
const data = await res.json()
// ...
}
```
You can then revalidate this `fetch` call tagged with `collection` by calling `revalidateTag`:
```ts filename="@/app/actions.ts" switcher
'use server'
import { revalidateTag } from 'next/cache'
export default async function action() {
revalidateTag('collection')
}
```
```js filename="@/app/actions.js" switcher
'use server'
import { revalidateTag } from 'next/cache'
export default async function action() {
revalidateTag('collection')
}
```
Learn [how on-demand revalidation works](/docs/app/building-your-application/caching#on-demand-revalidation).
### Error handling and revalidation
If an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data.
---
title: Partial Prerendering (Experimental)
description: Learn how to combine the benefits of static and dynamic rendering with Partial Prerendering.
---
> Partial Prerendering is an **experimental** feature and subject to change.
Partial Prerendering (PPR) is a rendering strategy that combines the benefits of static and dynamic rendering on the same route. With PPR, you can wrap any [dynamic](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) components in a [Suspense](https://react.dev/reference/react/Suspense) boundary. When a new request comes in, Next.js will immediately serve a static HTML shell from the cache, then render and [stream](/docs/app/building-your-application/rendering/server-components#streaming) the dynamic parts in the same HTTP request.
<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"
/>
> **🎥 Watch:** Why PPR and how it works → [YouTube (10 minutes)](https://www.youtube.com/watch?v=MTcPrTIBkpA).
## Incremental Adoption (Version 15)
In Next.js 15, you can incrementally adopt Partial Prerendering in [layouts](/docs/app/building-your-application/routing/layouts-and-templates) and [pages](/docs/app/building-your-application/routing/pages) by setting the [`ppr`](/docs/app/api-reference/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:
```js filename="next.config.js"
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.
## Enabling PPR (Version 14)
For version 14, you can enable it by adding the [`ppr`](/docs/app/api-reference/next-config-js/ppr) option to your `next.config.js` file. This will apply to all routes in your application:
```js filename="next.config.js"
const nextConfig = {
experimental: {
ppr: true,
},
}
module.exports = nextConfig
```
...@@ -64,7 +64,7 @@ There are three subsets of server rendering: Static, Dynamic, and Streaming. ...@@ -64,7 +64,7 @@ There are three subsets of server rendering: Static, Dynamic, and Streaming.
{/* Static Rendering Diagram */} {/* Static Rendering Diagram */}
With Static Rendering, routes are rendered at **build time**, or in the background after [data revalidation](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data). The result is cached and can be pushed to a [Content Delivery Network (CDN)](https://developer.mozilla.org/docs/Glossary/CDN). This optimization allows you to share the result of the rendering work between users and server requests. With Static Rendering, routes are rendered at **build time**, or in the background after [data revalidation](/docs/app/building-your-application/data-fetching/caching-and-revalidating#revalidating-data). The result is cached and can be pushed to a [Content Delivery Network (CDN)](https://developer.mozilla.org/docs/Glossary/CDN). This optimization allows you to share the result of the rendering work between users and server requests.
Static rendering is useful when a route has data that is not personalized to the user and can be known at build time, such as a static blog post or a product page. Static rendering is useful when a route has data that is not personalized to the user and can be known at build time, such as a static blog post or a product page.
...@@ -86,7 +86,7 @@ Dynamic rendering is useful when a route has data that is personalized to the us ...@@ -86,7 +86,7 @@ Dynamic rendering is useful when a route has data that is personalized to the us
#### Switching to Dynamic Rendering #### Switching to Dynamic Rendering
During rendering, if a [dynamic function](#dynamic-functions) or [uncached data request](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching) is discovered, Next.js will switch to dynamically rendering the whole route. This table summarizes how dynamic functions and data caching affect whether a route is statically or dynamically rendered: During rendering, if a [dynamic function](#dynamic-functions) or [uncached data request](/docs/app/building-your-application/data-fetching/caching-and-revalidating) is discovered, Next.js will switch to dynamically rendering the whole route. This table summarizes how dynamic functions and data caching affect whether a route is statically or dynamically rendered:
| Dynamic Functions | Data | Route | | Dynamic Functions | Data | Route |
| ----------------- | ---------- | -------------------- | | ----------------- | ---------- | -------------------- |
...@@ -97,14 +97,17 @@ During rendering, if a [dynamic function](#dynamic-functions) or [uncached data ...@@ -97,14 +97,17 @@ During rendering, if a [dynamic function](#dynamic-functions) or [uncached data
In the table above, for a route to be fully static, all data must be cached. However, you can have a dynamically rendered route that uses both cached and uncached data fetches. In the table above, for a route to be fully static, all data must be cached. However, you can have a dynamically rendered route that uses both cached and uncached data fetches.
As a developer, you do not need to choose between static and dynamic rendering as Next.js will automatically choose the best rendering strategy for each route based on the features and APIs used. Instead, you choose when to [cache or revalidate specific data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating), and you may choose to [stream](#streaming) parts of your UI. As a developer, you do not need to choose between static and dynamic rendering as Next.js will automatically choose the best rendering strategy for each route based on the features and APIs used. Instead, you choose when to [cache or revalidate specific data](/docs/app/building-your-application/data-fetching/caching-and-revalidating), and you may choose to [stream](#streaming) parts of your UI.
#### Dynamic Functions #### Dynamic Functions
Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are: Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic APIs are:
- **[`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers)**: Using these in a Server Component will opt the whole route into dynamic rendering at request time. - [`cookies()`](/docs/app/api-reference/functions/cookies)
- **[`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)**: Using the `searchParams` prop on a [Page](/docs/app/api-reference/file-conventions/page) will opt the page into dynamic rendering at request time. - [`headers()`](/docs/app/api-reference/functions/headers)
- [`unstable_noStore()`](/docs/app/api-reference/functions/unstable_noStore)
- [`unstable_after()`](/docs/app/api-reference/functions/unstable_after):
- [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional)
Using any of these functions will opt the whole route into dynamic rendering at request time. Using any of these functions will opt the whole route into dynamic rendering at request time.
......
...@@ -32,7 +32,7 @@ Here are some common patterns when working with Server Components: ...@@ -32,7 +32,7 @@ Here are some common patterns when working with Server Components:
When fetching data on the server, there may be cases where you need to share data across different components. For example, you may have a layout and a page that depend on the same data. When fetching data on the server, there may be cases where you need to share data across different components. For example, you may have a layout and a page that depend on the same data.
Instead of using [React Context](https://react.dev/learn/passing-data-deeply-with-context) (which is not available on the server) or passing data as props, you can use [`fetch`](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch) or React's `cache` function to fetch the same data in the components that need it, without worrying about making duplicate requests for the same data. This is because React extends `fetch` to automatically memoize data requests, and the `cache` function can be used when `fetch` is not available. Instead of using [React Context](https://react.dev/learn/passing-data-deeply-with-context) (which is not available on the server) or passing data as props, you can use [`fetch`](/docs/app/building-your-application/data-fetching/caching-and-revalidating#fetch-requests) or React's `cache` function to fetch the same data in the components that need it, without worrying about making duplicate requests for the same data. This is because React extends `fetch` to automatically memoize data requests, and the `cache` function can be used when `fetch` is not available.
Learn more about [memoization](/docs/app/building-your-application/caching#request-memoization) in React. Learn more about [memoization](/docs/app/building-your-application/caching#request-memoization) in React.
...@@ -404,7 +404,7 @@ export default function Layout({ children }) { ...@@ -404,7 +404,7 @@ export default function Layout({ children }) {
If you fetch data in a Server Component, you may want to pass data down as props to Client Components. Props passed from the Server to Client Components need to be [serializable](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values) by React. If you fetch data in a Server Component, you may want to pass data down as props to Client Components. Props passed from the Server to Client Components need to be [serializable](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values) by React.
If your Client Components depend on data that is not serializable, you can [fetch data on the client with a third party library](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-client-with-third-party-libraries) or on the server via a [Route Handler](/docs/app/building-your-application/routing/route-handlers). If your Client Components depend on data that is not serializable, you can [fetch data on the client with a third party library](/docs/app/building-your-application/data-fetching/caching-and-revalidating#data-fetching-libraries-and-orms) or on the server via a [Route Handler](/docs/app/building-your-application/routing/route-handlers).
## Interleaving Server and Client Components ## Interleaving Server and Client Components
......
...@@ -17,7 +17,7 @@ Here's a high-level overview of the different caching mechanisms and their purpo ...@@ -17,7 +17,7 @@ Here's a high-level overview of the different caching mechanisms and their purpo
| [Request Memoization](#request-memoization) | Return values of functions | Server | Re-use data in a React Component tree | Per-request lifecycle | | [Request Memoization](#request-memoization) | Return values of functions | Server | Re-use data in a React Component tree | Per-request lifecycle |
| [Data Cache](#data-cache) | Data | Server | Store data across user requests and deployments | Persistent (can be revalidated) | | [Data Cache](#data-cache) | Data | Server | Store data across user requests and deployments | Persistent (can be revalidated) |
| [Full Route Cache](#full-route-cache) | HTML and RSC payload | Server | Reduce rendering cost and improve performance | Persistent (can be revalidated) | | [Full Route Cache](#full-route-cache) | HTML and RSC payload | Server | Reduce rendering cost and improve performance | Persistent (can be revalidated) |
| [Router Cache](#router-cache) | RSC Payload | Client | Reduce server requests on navigation | User session or time-based | | [Router Cache](#client-side-router-cache) | RSC Payload | Client | Reduce server requests on navigation | User session or time-based |
By default, Next.js will cache as much as possible to improve performance and reduce cost. This means routes are **statically rendered** and data requests are **cached** unless you opt out. The diagram below shows the default caching behavior: when a route is statically rendered at build time and when a static route is first visited. By default, Next.js will cache as much as possible to improve performance and reduce cost. This means routes are **statically rendered** and data requests are **cached** unless you opt out. The diagram below shows the default caching behavior: when a route is statically rendered at build time and when a static route is first visited.
...@@ -283,7 +283,7 @@ At request time, on the client: ...@@ -283,7 +283,7 @@ At request time, on the client:
### 4. Next.js Caching on the Client (Router Cache) ### 4. Next.js Caching on the Client (Router Cache)
The React Server Component Payload is stored in the client-side [Router Cache](#router-cache) - a separate in-memory cache, split by individual route segment. This Router Cache is used to improve the navigation experience by storing previously visited routes and prefetching future routes. The React Server Component Payload is stored in the client-side [Router Cache](#client-side-router-cache) - a separate in-memory cache, split by individual route segment. This Router Cache is used to improve the navigation experience by storing previously visited routes and prefetching future routes.
### 5. Subsequent Navigations ### 5. Subsequent Navigations
...@@ -326,50 +326,34 @@ You can opt out of the Full Route Cache, or in other words, dynamically render c ...@@ -326,50 +326,34 @@ You can opt out of the Full Route Cache, or in other words, dynamically render c
- **Using the `dynamic = 'force-dynamic'` or `revalidate = 0` route segment config options**: This will skip the Full Route Cache and the Data Cache. Meaning components will be rendered and data fetched on every incoming request to the server. The Router Cache will still apply as it's a client-side cache. - **Using the `dynamic = 'force-dynamic'` or `revalidate = 0` route segment config options**: This will skip the Full Route Cache and the Data Cache. Meaning components will be rendered and data fetched on every incoming request to the server. The Router Cache will still apply as it's a client-side cache.
- **Opting out of the [Data Cache](#data-cache)**: If a route has a `fetch` request that is not cached, this will opt the route out of the Full Route Cache. The data for the specific `fetch` request will be fetched for every incoming request. Other `fetch` requests that do not opt out of caching will still be cached in the Data Cache. This allows for a hybrid of cached and uncached data. - **Opting out of the [Data Cache](#data-cache)**: If a route has a `fetch` request that is not cached, this will opt the route out of the Full Route Cache. The data for the specific `fetch` request will be fetched for every incoming request. Other `fetch` requests that do not opt out of caching will still be cached in the Data Cache. This allows for a hybrid of cached and uncached data.
## Router Cache ## Client-side Router Cache
> **Related Terms:** Next.js has an in-memory client-side router cache that stores the RSC payload of route segments, split by layouts, loading states, and pages.
>
> You may see the Router Cache being referred to as **Client-side Cache** or **Prefetch Cache**. While **Prefetch Cache** refers to the prefetched route segments, **Client-side Cache** refers to the whole Router cache, which includes both visited and prefetched segments.
> This cache specifically applies to Next.js and Server Components, and is different to the browser's [bfcache](https://web.dev/bfcache/), though it has a similar result.
Next.js has an in-memory client-side cache that stores the React Server Component Payload, split by individual route segments, for the duration of a user session. This is called the Router Cache.
**How the Router Cache Works**
<Image When a user navigates between routes, Next.js caches the visited route segments and [prefetches](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the routes the user is likely to navigate to.This results in instant back/forward navigation, no full-page reload between navigations, and preservation of React state and browser state.
alt="How the Router cache works for static and dynamic routes, showing MISS and HIT for initial and subsequent navigations."
srcLight="/docs/light/router-cache.png"
srcDark="/docs/dark/router-cache.png"
width="1600"
height="1375"
/>
As a user navigates between routes, Next.js caches visited route segments and [prefetches](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the routes the user is likely to navigate to (based on `<Link>` components in their viewport). With the Router Cache:
This results in an improved navigation experience for the user: - **Layouts** are cached and reused on navigation ([partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering)).
- **Loading states** are cached and reused on navigation for [instant navigation](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states).
- **Pages** are not cached by default, but are reused during browser backward and forward navigation. You can enable caching for page segments by using the experimental [`staleTimes`](/docs/app/api-reference/next-config-js/staleTimes) config option.
- Instant backward/forward navigation because visited routes are cached and fast navigation to new routes because of prefetching and [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering). {/* TODO: Update diagram to match v15 behavior */}
- No full-page reload between navigations, and React state and browser state are preserved.
> **Difference between the Router Cache and Full Route Cache**: > **Good to know:** This cache specifically applies to Next.js and Server Components, and is different to the browser's [bfcache](https://web.dev/bfcache/), though it has a similar result.
>
> The Router Cache temporarily stores the React Server Component Payload in the browser for the duration of a user session, whereas the Full Route Cache persistently stores the React Server Component Payload and HTML on the server across multiple user requests.
>
> While the Full Route Cache only caches statically rendered routes, the Router Cache applies to both statically and dynamically rendered routes.
### Duration ### Duration
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 an individual segment is automatically invalidated after a specific time. The duration depends on how the resource was [prefetched](/docs/app/api-reference/components/link#prefetch): - **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):
- **Default Prefetching** (`prefetch={null}` or unspecified): 0 seconds - **Default Prefetching** (`prefetch={null}` or unspecified): 0 seconds
- **Full Prefetching**: (`prefetch={true}` or `router.prefetch`): 5 minutes - **Full Prefetching**: (`prefetch={true}` or `router.prefetch`): 5 minutes
While a page refresh will clear **all** cached segments, the automatic invalidation period only affects the individual segment from the time it was prefetched. While a page refresh will clear **all** cached segments, the automatic invalidation period only affects the individual segment from the time it was prefetched.
> **Note**: There is [experimental support](/docs/app/api-reference/next-config-js/staleTimes) for configuring these values, available as of [v14.2.0](https://github.com/vercel/next.js/releases/tag/v14.2.0). > **Good to know**: The experimental [`staleTimes`](/docs/app/api-reference/next-config-js/staleTimes) config option can be used to enable caching of page segments.
### Invalidation ### Invalidation
...@@ -382,9 +366,9 @@ There are two ways you can invalidate the Router Cache: ...@@ -382,9 +366,9 @@ There are two ways you can invalidate the Router Cache:
### Opting out ### Opting out
It's not possible to opt out of the Router Cache. However, you can invalidate it by calling [`router.refresh`](/docs/app/api-reference/functions/use-router), [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath), or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) (see above). This will clear the cache and make a new request to the server, ensuring the latest data is shown. As of Next.js 15, page segments are opted out by default.
You can also opt out of **prefetching** by setting the `prefetch` prop of the `<Link>` component to `false`. However, this will still temporarily store the route segments for 30s to allow instant navigation between nested segments, such as tab bars, or back and forward navigation. Visited routes will still be cached. > **Good to know:** You can also opt out of [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) by setting the `prefetch` prop of the `<Link>` component to `false`.
## Cache Interactions ## Cache Interactions
...@@ -397,8 +381,8 @@ When configuring the different caching mechanisms, it's important to understand ...@@ -397,8 +381,8 @@ When configuring the different caching mechanisms, it's important to understand
### Data Cache and Client-side Router cache ### Data Cache and Client-side Router cache
- Revalidating the Data Cache in a [Route Handler](/docs/app/building-your-application/routing/route-handlers) **will not** immediately invalidate the Router Cache as the Route Handler isn't tied to a specific route. This means Router Cache will continue to serve the previous payload until a hard refresh, or the automatic invalidation period has elapsed.
- To immediately invalidate the Data Cache and Router cache, you can use [`revalidatePath`](#revalidatepath) or [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). - To immediately invalidate the Data Cache and Router cache, you can use [`revalidatePath`](#revalidatepath) or [`revalidateTag`](#fetch-optionsnexttags-and-revalidatetag) in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions-and-mutations).
- Revalidating the Data Cache in a [Route Handler](/docs/app/building-your-application/routing/route-handlers) **will not** immediately invalidate the Router Cache as the Route Handler isn't tied to a specific route. This means Router Cache will continue to serve the previous payload until a hard refresh, or the automatic invalidation period has elapsed.
## APIs ## APIs
......
---
title: Bundle Analyzer
description: Analyze the size of your JavaScript bundles using the @next/bundle-analyzer plugin.
related:
description: Learn more about optimizing your application for production.
links:
- app/building-your-application/deploying/production-checklist
---
[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your JavaScript modules. It generates a visual report of the size of each module and their dependencies. You can use the information to remove large dependencies, split your code, or only load some parts when needed, reducing the amount of data transferred to the client.
## Installation
Install the plugin by running the following command:
```bash
npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer
```
Then, add the bundle analyzer's settings to your `next.config.js`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {}
const withBundleAnalyzer = require('@next/bundle-analyzer')()
module.exports =
process.env.ANALYZE === 'true' ? withBundleAnalyzer(nextConfig) : nextConfig
```
## Analyzing your bundles
Run the following command to analyze your bundles:
```bash
ANALYZE=true npm run build
# or
ANALYZE=true yarn build
# or
ANALYZE=true pnpm build
```
The report will open three new tabs in your browser, which you can inspect. Doing this regularly while you develop and before deploying your site can help you identify large bundles earlier, and architect your application to be more performant.
---
title: Optimizing Package Bundling
nav_title: Package Bundling
description: Learn how to optimize your application's server and client bundles.
related:
description: Learn more about optimizing your application for production.
links:
- app/building-your-application/deploying/production-checklist
---
Bundling external packages can significantly improve the performance of your application. <AppOnly>By default, packages imported inside Server Components and Route Handlers are automatically bundled by Next.js. This page will guide you through how to analyze and further optimize package bundling.</AppOnly> <PagesOnly>By default, packages imported into your application are not bundled. This can impact performance or might not work if external packages are not pre-bundled, for example, if imported from a monorepo or `node_modules`. This page will guide you through how to analyze and configure package bundling.</PagesOnly>
## Analyzing JavaScript bundles
[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your application bundles. It generates a visual report of the size of each package and their dependencies. You can use the information to remove large dependencies, split, or [lazy-load](/docs/app/building-your-application/optimizing/lazy-loading) your code.
### Installation
Install the plugin by running the following command:
```bash
npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer
```
Then, add the bundle analyzer's settings to your `next.config.js`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {}
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer(nextConfig)
```
### Generating a report
Run the following command to analyze your bundles:
```bash
ANALYZE=true npm run build
# or
ANALYZE=true yarn build
# or
ANALYZE=true pnpm build
```
The report will open three new tabs in your browser, which you can inspect. Periodically evaluating your application's bundles can help you maintain application performance over time.
## Optimizing package imports
Some packages, such as icon libraries, can export hundreds of modules, which can cause performance issues in development and production.
You can optimize how these packages are imported by adding the [`optimizePackageImports`](/docs/app/api-reference/next-config-js/optimizePackageImports) option to your `next.config.js`. This option will only load the modules you _actually_ use, while still giving you the convenience of writing import statements with many named exports.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
optimizePackageImports: ['icon-library'],
},
}
module.exports = nextConfig
```
Next.js also optimizes some libraries automatically, thus they do not need to be included in the optimizePackageImports list. See the [full list](https://nextjs.org/docs/app/api-reference/next-config-js/optimizePackageImports).
<PagesOnly>
## Bundling specific packages
To bundle specific packages, you can use the [`transpilePackages`](/docs/app/api-reference/next-config-js/transpilePackages) option in your `next.config.js`. This option is useful for bundling external packages that are not pre-bundled, for example, in a monorepo or imported from `node_modules`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['package-name'],
}
module.exports = nextConfig
```
## Bundling all packages
To automatically bundle all packages (default behavior in the App Router), you can use the [`bundlePagesRouterDependencies`](/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies) option in your `next.config.js`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
bundlePagesRouterDependencies: true,
}
module.exports = nextConfig
```
## Opting specific packages out of bundling
If you have the [`bundlePagesRouterDependencies`](/docs/pages/api-reference/next-config-js/bundlePagesRouterDependencies) option enabled, you can opt specific packages out of automatic bundling using the [`serverExternalPackages`](/docs/pages/api-reference/next-config-js/serverExternalPackages) option in your `next.config.js`:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
// Automatically bundle external packages in the Pages Router:
bundlePagesRouterDependencies: true,
// Opt specific packages out of bundling for both App and Pages Router:
serverExternalPackages: ['package-name'],
}
module.exports = nextConfig
```
</PagesOnly>
<AppOnly>
## Opting specific packages out of bundling
Since packages imported inside Server Components and Route Handlers are automatically bundled by Next.js, you can opt specific packages out of bundling using the [`serverExternalPackages`](/docs/app/api-reference/next-config-js/serverExternalPackages) option in your `next.config.js`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
serverExternalPackages: ['package-name'],
}
module.exports = nextConfig
```
Next.js includes a list of popular packages that currently are working on compatibility and automatically opt-ed out. See the [full list](/docs/app/api-reference/next-config-js/serverExternalPackages).
</AppOnly>
...@@ -5,12 +5,9 @@ description: Optimize the performance of third-party libraries in your applicati ...@@ -5,12 +5,9 @@ description: Optimize the performance of third-party libraries in your applicati
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
**`@next/third-parties`** is a library that provides a collection of components and utilities that **`@next/third-parties`** is a library that provides a collection of components and utilities that improve the performance and developer experience of loading popular third-party libraries in your Next.js application.
improve the performance and developer experience of loading popular third-party libraries in your
Next.js application.
All third-party integrations provided by `@next/third-parties` have been optimized for performance All third-party integrations provided by `@next/third-parties` have been optimized for performance and ease of use.
and ease of use.
## Getting Started ## Getting Started
...@@ -30,14 +27,11 @@ All supported third-party libraries from Google can be imported from `@next/thir ...@@ -30,14 +27,11 @@ All supported third-party libraries from Google can be imported from `@next/thir
### Google Tag Manager ### Google Tag Manager
The `GoogleTagManager` component can be used to instantiate a [Google Tag The `GoogleTagManager` component can be used to instantiate a [Google Tag Manager](https://developers.google.com/tag-platform/tag-manager) container to your page. By default, it fetches the original inline script after hydration occurs on the page.
Manager](https://developers.google.com/tag-platform/tag-manager) container to your
page. By default, it fetches the original inline script after hydration occurs on the page.
<AppOnly> <AppOnly>
To load Google Tag Manager for all routes, include the component directly in your root layout and To load Google Tag Manager for all routes, include the component directly in your root layout and pass in your GTM container ID:
pass in your GTM container ID:
```tsx filename="app/layout.tsx" switcher ```tsx filename="app/layout.tsx" switcher
import { GoogleTagManager } from '@next/third-parties/google' import { GoogleTagManager } from '@next/third-parties/google'
......
...@@ -11,7 +11,7 @@ Let's explore some strategies and techniques to optimize memory and address comm ...@@ -11,7 +11,7 @@ Let's explore some strategies and techniques to optimize memory and address comm
Applications with a large amount of dependencies will use more memory. Applications with a large amount of dependencies will use more memory.
The [Bundle Analyzer](/docs/app/building-your-application/optimizing/bundle-analyzer) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. The [Bundle Analyzer](/docs/app/building-your-application/optimizing/package-bundling#analyzing-javascript-bundles) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage.
## Try `experimental.webpackMemoryOptimizations` ## Try `experimental.webpackMemoryOptimizations`
......
...@@ -131,9 +131,9 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) { ...@@ -131,9 +131,9 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) {
The Next.js App Router has **enhanced type safety**. This includes: The Next.js App Router has **enhanced type safety**. This includes:
1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types. 1. **No serialization of data between fetching function and page**: You can `fetch` directly in components, layouts, and pages on the server. This data _does not_ need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since `app` uses Server Components by default, we can use values like `Date`, `Map`, `Set`, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types.
2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) in the App Router, this is no longer an issue. 2. **Streamlined data flow between components**: With the removal of `_app` in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual `pages` and `_app` were difficult to type and could introduce confusing bugs. With [colocated data fetching](/docs/app/building-your-application/data-fetching/caching-and-revalidating) in the App Router, this is no longer an issue.
[Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection. [Data Fetching in Next.js](/docs/app/building-your-application/data-fetching/caching-and-revalidating) now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.
We're able to type the response data as you would expect with normal TypeScript. For example: We're able to type the response data as you would expect with normal TypeScript. For example:
......
...@@ -29,7 +29,7 @@ The examples on this page walk through basic username and password auth for educ ...@@ -29,7 +29,7 @@ The examples on this page walk through basic username and password auth for educ
### Sign-up and login functionality ### Sign-up and login functionality
You can use the [`<form>`](https://react.dev/reference/react-dom/components/form) element with React's [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations), [`useFormStatus()`](https://react.dev/reference/react-dom/hooks/useFormStatus), and [`useActionState()`](https://react.dev/reference/react/useActionState) to capture user credentials, validate form fields, and call your Authentication Provider's API or database. You can use the [`<form>`](https://react.dev/reference/react-dom/components/form) element with React's [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and [`useActionState()`](https://react.dev/reference/react/useActionState) to capture user credentials, validate form fields, and call your Authentication Provider's API or database.
Since Server Actions always execute on the server, they provide a secure environment for handling authentication logic. Since Server Actions always execute on the server, they provide a secure environment for handling authentication logic.
...@@ -200,9 +200,9 @@ export async function signup(state, formData) { ...@@ -200,9 +200,9 @@ export async function signup(state, formData) {
} }
``` ```
Back in your `<SignupForm />`, you can use React's `useActionState()` hook to display validation errors to the user: Back in your `<SignupForm />`, you can use React's `useActionState()` hook to display validation errors and a pending state while the form is submitting:
```tsx filename="app/ui/signup-form.tsx" switcher highlight={7,15,21,27-36} ```tsx filename="app/ui/signup-form.tsx" switcher highlight={7,15,21,27-39}
'use client' 'use client'
import { useActionState } from 'react' import { useActionState } from 'react'
...@@ -239,13 +239,15 @@ export function SignupForm() { ...@@ -239,13 +239,15 @@ export function SignupForm() {
</ul> </ul>
</div> </div>
)} )}
<SignupButton /> <button aria-disabled={pending} type="submit">
{pending ? 'Submitting...' : 'Sign up'}
</button>
</form> </form>
) )
} }
``` ```
```jsx filename="app/ui/signup-form.js" switcher highlight={7,15,21,27-36} ```jsx filename="app/ui/signup-form.js" switcher highlight={7,15,21,27-39}
'use client' 'use client'
import { useActionState } from 'react' import { useActionState } from 'react'
...@@ -282,49 +284,15 @@ export function SignupForm() { ...@@ -282,49 +284,15 @@ export function SignupForm() {
</ul> </ul>
</div> </div>
)} )}
<SignupButton /> <button aria-disabled={pending} type="submit">
{pending ? 'Submitting...' : 'Sign up'}
</button>
</form> </form>
) )
} }
``` ```
You can also use the `useFormStatus()` hook to handle the pending state on form submission: > **Good to know:** Alternatively, you can use the [`useFormStatus`](https://react.dev/reference/react-dom/hooks/useFormStatus) hook to display the pending state.
```tsx filename="app/ui/signup-form.tsx" highlight={6} switcher
'use client'
import { useActionState } from 'react'
import { useFormStatus } from 'react-dom'
export function SignupButton() {
const { pending } = useFormStatus()
return (
<button aria-disabled={pending} type="submit">
{pending ? 'Submitting...' : 'Sign up'}
</button>
)
}
```
```jsx filename="app/ui/signup-form.js" highlight={6} switcher
'use client'
import { useActionState } from 'react'
import { useFormStatus } from 'react-dom'
export function SignupButton() {
const { pending } = useFormStatus()
return (
<button aria-disabled={pending} type="submit">
{pending ? 'Submitting...' : 'Sign up'}
</button>
)
}
```
> **Good to know:** `useFormStatus()` must be called from a component that is rendered inside a `<form>`. See the [React Docs](https://react.dev/reference/react-dom/hooks/useFormStatus#usage) for more information.
#### 3. Create a user or check user credentials #### 3. Create a user or check user credentials
......
...@@ -60,10 +60,10 @@ While building your application, we recommend using the following features to en ...@@ -60,10 +60,10 @@ While building your application, we recommend using the following features to en
<AppOnly> <AppOnly>
- **[Server Components](/docs/app/building-your-application/data-fetching/patterns#fetching-data-on-the-server):** Leverage the benefits of fetching data on the server using Server Components. - **[Server Components](/docs/app/building-your-application/data-fetching/fetching#should-i-fetch-data-on-the-server-or-the-client):** Leverage the benefits of fetching data on the server using Server Components.
- **[Route Handlers](/docs/app/building-your-application/routing/route-handlers):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request. - **[Route Handlers](/docs/app/building-your-application/routing/route-handlers):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request.
- **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched.
- **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/patterns#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/patterns#preloading-data) where appropriate. - **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/fetching#preloading-data) where appropriate.
- **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). - **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache).
- **[Static Images](/docs/app/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images. - **[Static Images](/docs/app/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images.
...@@ -95,7 +95,7 @@ While building your application, we recommend using the following features to en ...@@ -95,7 +95,7 @@ While building your application, we recommend using the following features to en
<AppOnly> <AppOnly>
- **[Tainting](/docs/app/building-your-application/data-fetching/patterns#preventing-sensitive-data-from-being-exposed-to-the-client):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values. - **[Tainting](/docs/app/building-your-application/data-fetching/fetching#preventing-sensitive-data-from-being-exposed-to-the-client):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values.
- **[Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations#authentication-and-authorization):** Ensure users are authorized to call Server Actions. Review the the recommended [security practices](/blog/security-nextjs-server-components-actions). - **[Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations#authentication-and-authorization):** Ensure users are authorized to call Server Actions. Review the the recommended [security practices](/blog/security-nextjs-server-components-actions).
</AppOnly> </AppOnly>
...@@ -139,7 +139,7 @@ Before going to production, you can run `next build` to build your application l ...@@ -139,7 +139,7 @@ Before going to production, you can run `next build` to build your application l
### Analyzing bundles ### Analyzing bundles
Use the [`@next/bundle-analyzer` plugin](/docs/app/building-your-application/optimizing/bundle-analyzer) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance. Use the [`@next/bundle-analyzer` plugin](/docs/app/building-your-application/optimizing/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance.
Additionally, the following tools can you understand the impact of adding new dependencies to your application: Additionally, the following tools can you understand the impact of adding new dependencies to your application:
......
...@@ -290,7 +290,7 @@ Features that require a Node.js server, or dynamic logic that cannot be computed ...@@ -290,7 +290,7 @@ Features that require a Node.js server, or dynamic logic that cannot be computed
- [Redirects](/docs/app/api-reference/next-config-js/redirects) - [Redirects](/docs/app/api-reference/next-config-js/redirects)
- [Headers](/docs/app/api-reference/next-config-js/headers) - [Headers](/docs/app/api-reference/next-config-js/headers)
- [Middleware](/docs/app/building-your-application/routing/middleware) - [Middleware](/docs/app/building-your-application/routing/middleware)
- [Incremental Static Regeneration](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) - [Incremental Static Regeneration](/docs/app/building-your-application/data-fetching/caching-and-revalidating)
- [Image Optimization](/docs/app/building-your-application/optimizing/images) with the default `loader` - [Image Optimization](/docs/app/building-your-application/optimizing/images) with the default `loader`
- [Draft Mode](/docs/app/building-your-application/configuring/draft-mode) - [Draft Mode](/docs/app/building-your-application/configuring/draft-mode)
......
---
title: Version 15
description: Upgrade your Next.js Application from Version 14 to 15.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
## Upgrading from 14 to 15
To update to Next.js version 15, run the following command using your preferred package manager:
```bash filename="Terminal"
npm i next@rc react@rc react-dom@rc eslint-config-next@rc
```
```bash filename="Terminal"
yarn add next@rc react@rc react-dom@rc eslint-config-next@rc
```
```bash filename="Terminal"
pnpm up next@rc react@rc react-dom@rc eslint-config-next@rc
```
```bash filename="Terminal"
bun add next@rc react@rc react-dom@rc eslint-config-next@rc
```
> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions.
## Minimum React version
- The minimum `react` and `react-dom` is now 19.
## `fetch` requests
[`fetch` requests](/docs/app/api-reference/functions/fetch) are no longer cached by default.
To opt specific `fetch` requests into caching, you can pass the `cache: 'force-cache'` option.
```js filename="app/layout.js"
export default async function RootLayout() {
const a = await fetch('https://...') // Not Cached
const b = await fetch('https://...', { cache: 'force-cache' }) // Cached
// ...
}
```
To opt all `fetch` requests in a layout or page into caching, you can use the `export const fetchCache = 'default-cache'` [segment config option](/docs/app/api-reference/file-conventions/route-segment-config). If individual `fetch` requests specify a `cache` option, that will be used instead.
```js filename="app/layout.js"
// Since this is the root layout, all fetch requests in the app
// that don't set their own cache option will be cached.
export const fetchCache = 'default-cache'
export default async function RootLayout() {
const a = await fetch('https://...') // Cached
const b = await fetch('https://...', { cache: 'no-store' }) // Not cached
// ...
}
```
## Route Handlers
`GET` functions in [Route Handlers](/docs/app/api-reference/file-conventions/route) are no longer cached by default. To opt `GET` methods into caching, you can use a [route config option](/docs/app/api-reference/file-conventions/route-segment-config) such as `export dynamic = 'force-static'` in your Route Handler file.
```js filename="app/api/route.js
export dynamic = 'force-static'
export async function GET() {}
```
## Client-side Router Cache
When navigating between pages via `<Link>` or `useRouter`, [page](/docs/app/api-reference/file-conventions/page) segments are no longer reused from the client-side router cache. However, they are still reused during browser backward and forward navigation and for shared layouts.
To opt page segments into caching, you can use the [`staleTimes`](/docs/app/api-reference/next-config-js/staleTimes) config option:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
staleTimes: {
dynamic: 30,
static: 180,
},
},
}
module.exports = nextConfig
```
[Layouts](/docs/app/api-reference/file-conventions/layout) and [loading states](/docs/app/api-reference/file-conventions/loading) are still cached and reused on navigation.
## `next/font`
The `@next/font` package has been removed in favor of the built-in [`next/font`](/docs/app/api-reference/components/font). A [codemod is available](/docs/app/building-your-application/upgrading/codemods#built-in-next-font) to safely and automatically rename your imports.
```js filename="app/layout.js"
// Before
import { Inter } from '@next/font/google'
// After
import { Inter } from 'next/font/google'
```
## bundlePagesRouterDependencies
`experimental.bundlePagesExternals` is now stable and renamed to `bundlePagesRouterDependencies`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
// Before
experimental: {
bundlePagesExternals: true,
},
// After
bundlePagesRouterDependencies: true,
}
module.exports = nextConfig
```
## serverExternalPackages
`experimental.serverComponentsExternalPackages` is now stable and renamed to `serverExternalPackages`.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
// Before
experimental: {
serverComponentsExternalPackages: ['package-name'],
},
// After
serverExternalPackages: ['package-name'],
}
module.exports = nextConfig
```
## Speed Insights
Auto instrumentation for Speed Insights was removed in Next.js 15.
To continue using Speed Insights, follow the [Vercel Speed Insights Quickstart](https://vercel.com/docs/speed-insights/quickstart) guide.
...@@ -385,7 +385,7 @@ export default function HomePage({ recentPosts }) { ...@@ -385,7 +385,7 @@ export default function HomePage({ recentPosts }) {
- Create a new `app/page.tsx` file inside the `app` directory. This is a Server Component by default. - Create a new `app/page.tsx` file inside the `app` directory. This is a Server Component by default.
- Import the `home-page.tsx` Client Component into the page. - Import the `home-page.tsx` Client Component into the page.
- If you were fetching data in `pages/index.js`, move the data fetching logic directly into the Server Component using the new [data fetching APIs](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). See the [data fetching upgrade guide](#step-6-migrating-data-fetching-methods) for more details. - If you were fetching data in `pages/index.js`, move the data fetching logic directly into the Server Component using the new [data fetching APIs](/docs/app/building-your-application/data-fetching/caching-and-revalidating). See the [data fetching upgrade guide](#step-6-migrating-data-fetching-methods) for more details.
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
// Import your Client Component // Import your Client Component
...@@ -550,7 +550,7 @@ export default function Dashboard({ projects }) { ...@@ -550,7 +550,7 @@ export default function Dashboard({ projects }) {
In the `app` directory, we can colocate our data fetching inside our React components using [Server Components](/docs/app/building-your-application/rendering/server-components). This allows us to send less JavaScript to the client, while maintaining the rendered HTML from the server. In the `app` directory, we can colocate our data fetching inside our React components using [Server Components](/docs/app/building-your-application/rendering/server-components). This allows us to send less JavaScript to the client, while maintaining the rendered HTML from the server.
By setting the `cache` option to `no-store`, we can indicate that the fetched data should [never be cached](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). This is similar to `getServerSideProps` in the `pages` directory. By setting the `cache` option to `no-store`, we can indicate that the fetched data should [never be cached](/docs/app/building-your-application/data-fetching/caching-and-revalidating). This is similar to `getServerSideProps` in the `pages` directory.
```tsx filename="app/dashboard/page.tsx" switcher ```tsx filename="app/dashboard/page.tsx" switcher
// `app` directory // `app` directory
...@@ -870,7 +870,7 @@ export async function GET(request: Request) {} ...@@ -870,7 +870,7 @@ export async function GET(request: Request) {}
export async function GET(request) {} export async function GET(request) {}
``` ```
> **Good to know**: If you previously used API routes to call an external API from the client, you can now use [Server Components](/docs/app/building-your-application/rendering/server-components) instead to securely fetch data. Learn more about [data fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). > **Good to know**: If you previously used API routes to call an external API from the client, you can now use [Server Components](/docs/app/building-your-application/rendering/server-components) instead to securely fetch data. Learn more about [data fetching](/docs/app/building-your-application/data-fetching/caching-and-revalidating).
### Step 7: Styling ### Step 7: Styling
......
...@@ -169,6 +169,7 @@ export default function Icon() { ...@@ -169,6 +169,7 @@ export default function Icon() {
> - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) or uncached data. > - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) 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 is cached by default unless it uses a [dynamic function](/docs/app/building-your-application/caching#dynamic-functions) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.
### Props ### Props
......
...@@ -9,3 +9,5 @@ This section of the docs covers **Metadata file conventions**. File-based metada ...@@ -9,3 +9,5 @@ This section of the docs covers **Metadata file conventions**. File-based metada
Each file convention can be defined using a static file (e.g. `opengraph-image.jpg`), or a dynamic variant that uses code to generate the file (e.g. `opengraph-image.js`). Each file convention can be defined using a static file (e.g. `opengraph-image.jpg`), or a dynamic variant that uses code to generate the file (e.g. `opengraph-image.js`).
Once a file is defined, Next.js will automatically serve the file (with hashes in production for caching) and update the relevant head elements with the correct metadata, such as the asset's URL, file type, and image size. Once a file is defined, Next.js will automatically serve the file (with hashes in production for caching) and update the relevant head elements with the correct metadata, such as the asset's URL, file type, and image size.
> **Good to know**: Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) are cached by default.
...@@ -21,6 +21,8 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif ...@@ -21,6 +21,8 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif
Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object). Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object).
> Good to know: `manifest.js` is special Route Handlers that is cached by default unless it uses a [dynamic function](/docs/app/building-your-application/caching#dynamic-functions) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.
```ts filename="app/manifest.ts" switcher ```ts filename="app/manifest.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -86,6 +86,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi ...@@ -86,6 +86,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi
> >
> - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) or uncached data. > - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [dynamic functions](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) 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 function](/docs/app/building-your-application/caching#dynamic-functions) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.
The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`. The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`.
......
...@@ -19,6 +19,8 @@ Sitemap: https://acme.com/sitemap.xml ...@@ -19,6 +19,8 @@ Sitemap: https://acme.com/sitemap.xml
Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object). Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object).
> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [dynamic function](/docs/app/building-your-application/caching#dynamic-functions) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.
```ts filename="app/robots.ts" switcher ```ts filename="app/robots.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -41,6 +41,8 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th ...@@ -41,6 +41,8 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th
You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available. You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available.
> **Good to know**: `sitemap.js` is a special Route Handlers that is cached by default unless it uses a [dynamic function](/docs/app/building-your-application/caching#dynamic-functions) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.
```ts filename="app/sitemap.ts" switcher ```ts filename="app/sitemap.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -7,6 +7,7 @@ The Route Segment options allows you to configure the behavior of a [Page](/docs ...@@ -7,6 +7,7 @@ The Route Segment options allows you to configure the behavior of a [Page](/docs
| Option | Type | Default | | Option | Type | Default |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| [`experimental_ppr`](#dynamic) | `'true' \| 'false'` |
| [`dynamic`](#dynamic) | `'auto' \| 'force-dynamic' \| 'error' \| 'force-static'` | `'auto'` | | [`dynamic`](#dynamic) | `'auto' \| 'force-dynamic' \| 'error' \| 'force-static'` | `'auto'` |
| [`dynamicParams`](#dynamicparams) | `boolean` | `true` | | [`dynamicParams`](#dynamicparams) | `boolean` | `true` |
| [`revalidate`](#revalidate) | `false \| 0 \| number` | `false` | | [`revalidate`](#revalidate) | `false \| 0 \| number` | `false` |
...@@ -17,6 +18,20 @@ The Route Segment options allows you to configure the behavior of a [Page](/docs ...@@ -17,6 +18,20 @@ The Route Segment options allows you to configure the behavior of a [Page](/docs
## Options ## Options
### `experimental_ppr`
Enable [Partial Prerendering (PPR)](/docs/app/building-your-application/rendering/partial-prerendering) for a layout or page.
```tsx filename="layout.tsx | page.tsx " switcher
export const experimental_ppr = true
// true | false
```
```jsx filename="layout.js | page.js " switcher
export const experimental_ppr = true
// true | false
```
### `dynamic` ### `dynamic`
Change the dynamic behavior of a layout or page to fully static or fully dynamic. Change the dynamic behavior of a layout or page to fully static or fully dynamic.
......
...@@ -3,7 +3,7 @@ title: fetch ...@@ -3,7 +3,7 @@ title: fetch
description: API reference for the extended fetch function. description: API reference for the extended fetch function.
--- ---
Next.js extends the native [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching semantics. Next.js extends the native [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching and revalidation semantics.
In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent HTTP cache. In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent HTTP cache.
...@@ -63,15 +63,12 @@ Configure how the request should interact with Next.js [Data Cache](/docs/app/bu ...@@ -63,15 +63,12 @@ Configure how the request should interact with Next.js [Data Cache](/docs/app/bu
fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
``` ```
- **`force-cache`** (default) - Next.js looks for a matching request in its Data Cache. - **`no-store`** (default): Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource.
- **`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.
- If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource. - If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.
- **`no-store`** - Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource.
> **Good to know**: > **Good to know**: The `no-cache` option behaves the same way as `no-store` in Next.js.
>
> - If you don't provide a `cache` option, Next.js will default to `force-cache`, unless a [dynamic function](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-functions) such as `cookies()` is used, in which case it will default to `no-store`.
> - The `no-cache` option behaves the same way as `no-store` in Next.js.
### `options.next.revalidate` ### `options.next.revalidate`
...@@ -89,8 +86,8 @@ Set the cache lifetime of a resource (in seconds). ...@@ -89,8 +86,8 @@ Set the cache lifetime of a resource (in seconds).
> >
> - If an individual `fetch()` request sets a `revalidate` number lower than the [default `revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) of a route, the whole route revalidation interval will be decreased. > - If an individual `fetch()` request sets a `revalidate` number lower than the [default `revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) of a route, the whole route revalidation interval will be decreased.
> - If two fetch requests with the same URL in the same route have different `revalidate` values, the lower value will be used. > - If two fetch requests with the same URL in the same route have different `revalidate` values, the lower value will be used.
> - As a convenience, it is not necessary to set the `cache` option if `revalidate` is set to a number since `0` implies `cache: 'no-store'` and a positive value implies `cache: 'force-cache'`. > - As a convenience, it is not necessary to set the `cache` option if `revalidate` is set to a number.
> - Conflicting options such as `{ revalidate: 0, cache: 'force-cache' }` or `{ revalidate: 10, cache: 'no-store' }` will cause an error. > - Conflicting options such as `{ revalidate: 3600, cache: 'no-store' }` will cause an error.
### `options.next.tags` ### `options.next.tags`
...@@ -102,6 +99,7 @@ Set the cache tags of a resource. Data can then be revalidated on-demand using [ ...@@ -102,6 +99,7 @@ Set the cache tags of a resource. Data can then be revalidated on-demand using [
## Version History ## Version History
| Version | Changes | | Version | Changes |
| --------- | ------------------- | | --------- | ----------------------------------------------------------------------- |
| `v13.0.0` | `fetch` introduced. | | `v15.0.0` | Default `cache` option was changed from `'force-cache'` to `'no-store'` |
| `v13.0.0` | `fetch` introduced. |
--- ---
title: Metadata Object and generateMetadata Options title: generateMetadata
nav_title: generateMetadata
description: Learn how to add Metadata to your Next.js application for improved search engine optimization (SEO) and web shareability. description: Learn how to add Metadata to your Next.js application for improved search engine optimization (SEO) and web shareability.
related: related:
title: Next Steps title: Next Steps
......
...@@ -60,7 +60,7 @@ const headersList = headers() ...@@ -60,7 +60,7 @@ const headersList = headers()
#### Usage with Data Fetching #### Usage with Data Fetching
`headers()` can be used in combination with [Suspense for Data Fetching](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating). `headers()` can be used in combination with [Suspense for Data Fetching](/docs/app/building-your-application/data-fetching/caching-and-revalidating).
```jsx filename="app/page.js" ```jsx filename="app/page.js"
import { Suspense } from 'react' import { Suspense } from 'react'
......
...@@ -33,7 +33,7 @@ The `type` parameter has no effect when used in Server Components. ...@@ -33,7 +33,7 @@ The `type` parameter has no effect when used in Server Components.
## Returns ## Returns
`permanentRedirect` does not return any value. `permanentRedirect` does not return a value.
## Example ## Example
......
...@@ -36,7 +36,7 @@ The `type` parameter has no effect when used in Server Components. ...@@ -36,7 +36,7 @@ The `type` parameter has no effect when used in Server Components.
## Returns ## Returns
`redirect` does not return any value. `redirect` does not return a value.
## Example ## Example
......
...@@ -9,7 +9,7 @@ description: API Reference for the revalidatePath function. ...@@ -9,7 +9,7 @@ description: API Reference for the revalidatePath function.
> >
> - `revalidatePath` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). > - `revalidatePath` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).
> - `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. > - `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.
> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#router-cache). This behavior is temporary and will be updated in the future to apply only to the specific path. > - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). This behavior is temporary and will be updated in the future to apply only to the specific path.
> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache). > - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache).
## Parameters ## Parameters
...@@ -23,7 +23,7 @@ revalidatePath(path: string, type?: 'page' | 'layout'): void; ...@@ -23,7 +23,7 @@ revalidatePath(path: string, type?: 'page' | 'layout'): void;
## Returns ## Returns
`revalidatePath` does not return any value. `revalidatePath` does not return a value.
## Examples ## Examples
......
...@@ -26,7 +26,7 @@ fetch(url, { next: { tags: [...] } }); ...@@ -26,7 +26,7 @@ fetch(url, { next: { tags: [...] } });
## Returns ## Returns
`revalidateTag` does not return any value. `revalidateTag` does not return a value.
## Examples ## Examples
......
---
title: unstable_after (Experimental)
description: API Reference for the unstable_after function.
---
> This API is **experimental** and subject to change.
`unstable_after()` allows you to schedule work to be executed after a response is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics.
It can be used in [Server Components](/docs/app/building-your-application/rendering/server-components) (including [`generateMetadata`](https://nextjs.org/docs/app/api-reference/functions/generate-metadata)), [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations), [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Middleware](/docs/app/building-your-application/routing/middleware).
To use `unstable_after()`, you need to enable it using the `experimental.after` config in the `next.config.js` file:
```js filename="next.config.js"
const nextConfig = {
experimental: {
after: true,
},
}
module.exports = nextConfig
```
```tsx filename="app/layout.tsx switcher
import { unstable_after as after } from 'next/server'
import { log } from '@/app/utils'
export default function Layout({ children }: { children: React.ReactNode }) {
after(() => {
// Execute after the layout is rendered and sent to the user
log()
})
return <>{children}</>
}
```
```jsx filename="app/layout.js switcher
import { unstable_after as after } from 'next/server'
import { log } from '@/app/utils'
export default function Layout({ children }) {
after(() => {
// Execute after the layout is rendered and sent to the user
log()
})
return <>{children}</>
}
```
> **Good to know**:
>
> - `unstable_after()` will be executed even if the response didn't complete successfully. Including when an error is thrown or when `notFound()` or `redirect()` is called.
> - `unstable_after()` is a [dynamic function](/docs/app/building-your-application/rendering/server-components#dynamic-functions) that will opt a route into dynamic rendering. This behavior can be overridden with the [`export dynamic = "force-static"`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) segment config.
> - You can use React `cache` to deduplicate functions called inside `unstable_after()`.
> - [`cookies()`](/docs/app/api-reference/functions/cookies) cannot be set inside `unstable_after()` since the response has already been sent.
### Parameters
- A function that will be executed after the response is finished.
### Returns
- `unstable_after()` does not return a value.
--- ---
title: unstable_cache title: unstable_cache (Experimental)
description: API Reference for the unstable_cache function. description: API Reference for the unstable_cache function.
--- ---
......
--- ---
title: unstable_noStore title: unstable_noStore (Experimental)
description: API Reference for the unstable_noStore function. description: API Reference for the unstable_noStore function.
--- ---
......
...@@ -4,7 +4,7 @@ nav_title: cacheHandler ...@@ -4,7 +4,7 @@ nav_title: cacheHandler
description: Configure the Next.js cache used for storing and revalidating data to use any external service like Redis, Memcached, or others. description: Configure the Next.js cache used for storing and revalidating data to use any external service like Redis, Memcached, or others.
--- ---
In Next.js, the [default cache handler](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) for the Pages and App Router uses the filesystem cache. This requires no configuration, however, you can customize the cache handler by using the `cacheHandler` field in `next.config.js`. In Next.js, the [default cache handler](/docs/app/building-your-application/data-fetching/caching-and-revalidating) for the Pages and App Router uses the filesystem cache. This requires no configuration, however, you can customize the cache handler by using the `cacheHandler` field in `next.config.js`.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
...@@ -43,7 +43,7 @@ Returns `Promise<void>`. ...@@ -43,7 +43,7 @@ Returns `Promise<void>`.
| --------- | -------- | ---------------------------- | | --------- | -------- | ---------------------------- |
| `tag` | `string` | The cache tag to revalidate. | | `tag` | `string` | The cache tag to revalidate. |
Returns `Promise<void>`. Learn more about [revalidating data](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) or the [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) function. Returns `Promise<void>`. Learn more about [revalidating data](/docs/app/building-your-application/data-fetching/caching-and-revalidating) or the [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) function.
**Good to know:** **Good to know:**
......
--- ---
title: Partial Prerendering (experimental) title: Partial Prerendering (Experimental)
nav_title: ppr (Experimental)
description: Learn how to enable Partial Prerendering (experimental) in Next.js 14. description: Learn how to enable Partial Prerendering (experimental) in Next.js 14.
--- ---
> **Warning**: Partial Prerendering is an experimental feature and is currently **not suitable for production environments**. > Partial Prerendering is an **experimental** feature and subject to change.
Partial Prerendering is an experimental feature that allows static portions of a route to be prerendered and served from the cache with dynamic holes streamed in, all in a single HTTP request. Partial Prerendering is an experimental feature that allows static portions of a route to be prerendered and served from the cache with dynamic holes streamed in, all in a single HTTP request.
Partial Prerendering is available in `next@canary`: Incremental support is available in Next.js 15, allowing you to opt-in to Partial Prerendering for specific routes and layouts.
```bash filename="Terminal" To enable Partial Prerendering, set the experimental `ppr` flag to `incremental`:
npm install next@canary
```
You can enable Partial Prerendering by setting the experimental `ppr` flag:
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: { experimental: {
ppr: true, ppr: 'incremental',
}, },
} }
module.exports = nextConfig module.exports = nextConfig
``` ```
## Options
- `incremental`: Allows you to incrementally opt-in layouts and pages, and should be used with the [`experimental_ppr`](/docs/app/api-reference/file-conventions/route-segment-config#experimental_ppr) route config option.
- `true`: Enables Partial Prerendering for all routes in your application.
We recommend using `incremental` first. Once all the routes in your application have PPR enabled, it’ll be considered safe for you to set the `ppr` value to `true`, and enable it for the entire app and all future routes.
> **Good to know:** > **Good to know:**
> >
> - When using `incremental`, routes that don't have `experimental_ppr` will default to `false` and will not be prerendered using Partial Prerendering. You need to explicitly opt-in to Partial Prerendering for each route.
> - Partial Prerendering does not yet apply to client-side navigations. We are actively working on this. > - Partial Prerendering does not yet apply to client-side navigations. We are actively working on this.
> - Partial Prerendering is designed for the [Node.js runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) only. Using the subset of the Node.js runtime is not needed when you can instantly serve the static shell. > - Partial Prerendering is designed for the [Node.js runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) only. Using the Edge Runtime is not needed when you can instantly serve the static shell.
Learn more about Partial Prerendering in the [Next.js Learn course](/learn/dashboard-app/partial-prerendering). Learn more about Partial Prerendering in the [Next.js Learn course](/learn/dashboard-app/partial-prerendering).
---
title: reactCompiler (Experimental)
description: Enable the React Compiler to automatically optimize component rendering.
---
> This feature is **experimental** and may change in future releases.
Next.js 15 introduced experimental support for the [React Compiler](https://react.dev/learn/react-compiler). The compiler improves performance by automatically optimizing component rendering. This reduces the amount of manual memoization developers have to do through APIs such as `useMemo` and `useCallback`.
To use it, upgrade to Next.js 15, install the `babel-plugin-react-compiler`:
```bash filename="Terminal"
npm install babel-plugin-react-compiler
```
Then, add `experimental.reactCompiler` option in `next.config.js`:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
reactCompiler: true,
},
}
module.exports = nextConfig
```
Optionally, you can configure the compiler to run in "opt-in" mode as follows:
```tsx filename="next.config.ts"
const nextConfig = {
experimental: {
reactCompiler: {
compilationMode: 'annotation',
},
},
}
module.exports = nextConfig
```
> **Note:** The React Compiler is currently only possible to use in Next.js through a Babel plugin. This will opt-out of Next.js's default [Rust-based compiler](/docs/architecture/nextjs-compiler), which could result in slower build times. We are working on support for the React Compiler as our default compiler.
Learn more about the [React Compiler](https://react.dev/learn/react-compiler), and the [available Next.js config options](https://react.dev/learn/react-compiler#usage-with-nextjs).
...@@ -74,3 +74,7 @@ Next.js includes a [short list of popular packages](https://github.com/vercel/ne ...@@ -74,3 +74,7 @@ Next.js includes a [short list of popular packages](https://github.com/vercel/ne
- `webpack` - `webpack`
- `websocket` - `websocket`
- `zeromq` - `zeromq`
| Version | Changes |
| --------- | -------------------------------------------------------------------------------------------------------------- |
| `v15.0.0` | Moved from experimental to stable. Renamed from `serverComponentsExternalPackages` to `serverExternalPackages` |
--- ---
title: StaleTimes (experimental) title: staleTimes (Experimental)
description: Learn how to override the invalidation time of the Client Router Cache. description: Learn how to override the invalidation time of the Client Router Cache.
--- ---
> **Warning**: The `staleTimes` configuration is an experimental feature. This configuration strategy will likely change in the future. > **Warning**: The `staleTimes` configuration is an experimental feature. This configuration strategy will likely change in the future.
`staleTimes` is an experimental feature that allows configuring the [invalidation period](/docs/app/building-your-application/caching#duration-3) of the client router cache. `staleTimes` is an experimental feature that enables caching of page segments in the [client-side router cache](/docs/app/building-your-application/caching#client-side-router-cache).
This configuration option is available as of [v14.2.0](https://github.com/vercel/next.js/releases/tag/v14.2.0). You can enable this experimental feature and provide custom revalidation times by setting the experimental `staleTimes` flag:
You can enable this experimental feature & provide custom revalidation times by setting the experimental `staleTimes` flag:
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
...@@ -35,8 +33,15 @@ The `static` and `dynamic` properties correspond with the time period (in second ...@@ -35,8 +33,15 @@ The `static` and `dynamic` properties correspond with the time period (in second
> **Good to know:** > **Good to know:**
> >
> - [Loading boundaries](/docs/app/api-reference/file-conventions/loading) are considered reusable for the `static` period defined in this configuration. > - [Loading boundaries](/docs/app/api-reference/file-conventions/loading) are considered reusable for the `static` period defined in this configuration.
> - This doesn't disable [partial rendering support](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), **meaning shared layouts won't automatically be refetched every navigation, only the new segment data.** > - This doesn't affect [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), **meaning shared layouts won't automatically be refetched on every navigation, only the page segment that changes.**
> - This doesn't change [back/forward caching](/docs/app/building-your-application/caching#router-cache) behavior to prevent layout shift & to prevent losing the browser scroll position. > - This doesn't change [back/forward caching](/docs/app/building-your-application/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position.
> - The different properties of this config refer to variable levels of "liveness" and are unrelated to whether the segment itself is opting into static or dynamic rendering. In other words, the current `static` default of 5 minutes suggests that data feels static by virtue of it being revalidated infrequently. > - The different properties of this config refer to variable levels of "liveness" and are unrelated to whether the segment itself is opting into static or dynamic rendering. In other words, the current `static` default of 5 minutes suggests that data feels static by virtue of it being revalidated infrequently.
You can learn more about the Client Router Cache [here](/docs/app/building-your-application/caching#router-cache). You can learn more about the Client Router Cache [here](/docs/app/building-your-application/caching#client-side-router-cache).
### Version History
| Version | Changes |
| --------- | ------------------------------------------------------------------ |
| `v15.0.0` | `staleTimes` enables and configures the duration for page segments |
| `v14.2.0` | experimental `staleTimes` introduced |
...@@ -10,7 +10,7 @@ Next.js can automatically transpile and bundle dependencies from local packages ...@@ -10,7 +10,7 @@ Next.js can automatically transpile and bundle dependencies from local packages
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
transpilePackages: ['@acme/ui', 'lodash-es'], transpilePackages: ['package-name'],
} }
module.exports = nextConfig module.exports = nextConfig
......
...@@ -65,7 +65,7 @@ Yes. You can view [Next.js Commerce](https://vercel.com/templates/next.js/nextjs ...@@ -65,7 +65,7 @@ Yes. You can view [Next.js Commerce](https://vercel.com/templates/next.js/nextjs
## Learn More ## Learn More
- [Routing Fundamentals](/docs/app/building-your-application/routing) - [Routing Fundamentals](/docs/app/building-your-application/routing)
- [Data Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) - [Data Fetching, Caching, and Revalidating](/docs/app/building-your-application/data-fetching/caching-and-revalidating)
- [Forms and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) - [Forms and Mutations](/docs/app/building-your-application/data-fetching/server-actions-and-mutations)
- [Caching](/docs/app/building-your-application/caching) - [Caching](/docs/app/building-your-application/caching)
- [Rendering Fundamentals](/docs/app/building-your-application/rendering) - [Rendering Fundamentals](/docs/app/building-your-application/rendering)
......
...@@ -14,7 +14,7 @@ description: Next.js supports API Routes, which allow you to build your API with ...@@ -14,7 +14,7 @@ description: Next.js supports API Routes, which allow you to build your API with
</details> </details>
> **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead of API Routes. > **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/building-your-application/data-fetching/caching-and-revalidating) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead of API Routes.
API routes provide a solution to build a **public API** with Next.js. API routes provide a solution to build a **public API** with Next.js.
......
--- ---
title: Bundle Analyzer title: Optimizing Bundling
description: Analyze the size of your JavaScript bundles using the @next/bundle-analyzer plugin. nav_title: Bundling
source: app/building-your-application/optimizing/bundle-analyzer description: Learn how to optimize your application's server and client bundles.
source: app/building-your-application/optimizing/package-bundling
related: related:
description: Learn more about optimizing your application for production. description: Learn more about optimizing your application for production.
links: links:
......
...@@ -15,3 +15,9 @@ module.exports = nextConfig ...@@ -15,3 +15,9 @@ module.exports = nextConfig
``` ```
Explicitly opt-out certain packages from being bundled using the [`serverExternalPackages`](/docs/pages/api-reference/next-config-js/serverExternalPackages) option. Explicitly opt-out certain packages from being bundled using the [`serverExternalPackages`](/docs/pages/api-reference/next-config-js/serverExternalPackages) option.
## Version History
| Version | Changes |
| --------- | --------------------------------------------------------------------------------------------------------- |
| `v15.0.0` | Moved from experimental to stable. Renamed from `bundlePagesExternals` to `bundlePagesRouterDependencies` |
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