Unverified Commit 7378b51e authored by Joseph's avatar Joseph Committed by GitHub

Backport/docs fixes 16.3 (#97649)

## Summary

- docs: remove experimental note from runtime prefetching (#96615)
- docs: proxy event argument (#96435)
- docs: correction to dynamicParams migration (#96624)
- docs: quote the dynamicParams build error in a blockquote (#96633)
- docs: use relative doc links in instant-navigation error pages
(#96672)
- docs: document ! exclusion and src/ prefix for --debug-build-paths
(#96703)
- docs: instant navigation quick start with an adoption prompt (#96663)
- docs (Skills): stop assuming app/ at the root and port 3000 (#96696)
- docs: present each Skill as steps in the AI agents guide (#96751)
- docs: update redirected links to current targets (#96723)
- docs: add authentication with Cache Components guide and iron-session
example (#95802)
- docs: link View Transitions skill on skills.sh and clarify the example
prompt (#96863)
- Add a `turbopackChunking` documentation page for pages router (#96698)
- docs: add `export const dynamic = 'force-static'` to Route Handlers
example on Static Exports (#96964)
- docs: runtime prefetching -> optimizing prefetching (#96934)
- Fix typo in Data Access Layer section (#87202)
- docs: rename repo to repository for consistency (#87849)
- docs(mdx): fix package name in .md handling section (#97131)
- docs: fix Link prefetch grammar and Client Components wording (#97132)
- docs: align Cache Components authentication guide title (#97143)
- docs: create client-side fetching guide (#96341)
- docs: clarify client cache freshness after hydration (#97180)
- docs: server client and directives (#96145)
- Update authentication diagram URL (#97320)
- docs: align SPA guide reducer example with React conventions (#97341)
- docs: app router reference accuracy (#97477)
- docs: mention Valibot as validation library option in forms guides
(#97468)
- docs: warn when catching permanentRedirect (#97496)
- [docs] fix: grammar typos in linking and navigating guide (#95544)
- docs: rename Vercel Edge Config to Global Config in redirecting guide
(#97456)
- docs: document metadata pagination field (#95509)
- docs: outlining and lcp (#96942)
- docs: adjust interactive app guide (#97558)
- docs: generateMetadata values should be serializable with use cache
(#97551)
- Fix stale cross-references in skills/ (#97566)
- Improve Cache Components sync IO migration guidance (#97572)
- docs: Explicit cache output description (#97548)
- docs: document deploymentId build ID override and Pages Router skew in
16.2 (#97645)
- docs: drop stale Route Handlers restriction from `use cache: private`
(docs part of #97349)
- docs: clarify beforeInteractive placement for root layouts (#97643)
- docs: Adapters entry page lists its children pages twice (#97677)
- docs: correct the upper stale bound for App Shell exclusion in
cacheLife (#97653)
- Improve Partial Prefetching adoption checks (#97637)
- docs: fix parallelRouteKey parameter name in
useSelectedLayoutSegment(s) (#97710)
- docs(adapters): document assetsHashes and routing.middlewareMatchers
(#96536)
- docs: note that response headers must be set before calling handle()
in a custom server (#97693)
- Document catchError for the Pages Router (#97748)
- docs: fix typos and correctness issues in App Router docs (#97823)
- docs: param access on use-server (#97865)
- docs: clarify revalidateTag profile expire semantics (#97836)

---------
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarClaude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
Co-authored-by: 's avatarSam Poder <sampoder@berkeley.edu>
Co-authored-by: 's avatarMasashi Kawafuji <masashikawafuji@proton.me>
Co-authored-by: 's avatarAkseli Palmer <akseli@toddsden.com>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarJarren <sanjose.jarren@gmail.com>
Co-authored-by: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
Co-authored-by: 's avatarPavan Shinde <pavann97@gmail.com>
Co-authored-by: 's avatarReza Karimzadeh <r.karimzadeh1998@gmail.com>
Co-authored-by: 's avatarFabian Hiller <hillerfabian11@gmail.com>
Co-authored-by: 's avatarDavid Alexandru Ilie <david@davidilie.com>
Co-authored-by: 's avatarSean Beirnes <127370575+seanbeirnes@users.noreply.github.com>
Co-authored-by: 's avatarRich Haines <22930449+molebox@users.noreply.github.com>
Co-authored-by: 's avatarKAM <biukam.w@gmail.com>
Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
Co-authored-by: 's avatarJude Gao <jude.gao@vercel.com>
Co-authored-by: 's avatarSaid Nasser <sdnssr001@gmail.com>
Co-authored-by: 's avatarEddy (Frontend Engineer) <101346918+leejpsd@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 528c1cdf
......@@ -158,7 +158,7 @@ You can continue nesting folders to create nested routes. For example, to create
/>
```tsx filename="app/blog/[slug]/page.tsx" switcher
function generateStaticParams() {}
export function generateStaticParams() {}
export default function Page() {
return <h1>Hello, Blog Post Page!</h1>
......@@ -166,7 +166,7 @@ export default function Page() {
```
```jsx filename="app/blog/[slug]/page.js" switcher
function generateStaticParams() {}
export function generateStaticParams() {}
export default function Page() {
return <h1>Hello, Blog Post Page!</h1>
......@@ -247,7 +247,7 @@ export default async function BlogPostPage({ params }) {
Learn more about [Dynamic Segments](/docs/app/api-reference/file-conventions/dynamic-routes) and the [`params`](/docs/app/api-reference/file-conventions/page#params-optional) props.
Nested [layouts within Dynamic Segments](/docs/app/api-reference/file-conventions/layout#params-optional), can also access the `params` props.
Nested [layouts within Dynamic Segments](/docs/app/api-reference/file-conventions/layout#params-optional) can also access the `params` props.
## Rendering with search params
......
......@@ -158,7 +158,7 @@ Next.js avoids this with client-side transitions using the `<Link>` component. I
- Keeping any shared layouts and UI.
- Replacing the current page with the prefetched loading state or a new page if available.
Client-side transitions are what makes a server-rendered apps _feel_ like client-rendered apps. And when paired with [prefetching](#prefetching) and [streaming](#streaming), it enables fast transitions, even for dynamic routes.
Client-side transitions make server-rendered apps _feel_ like client-rendered apps. And when paired with [prefetching](#prefetching) and [streaming](#streaming), they enable fast transitions, even for dynamic routes.
Next.js also handles [scrolling to the top of the page](/docs/app/api-reference/components/link#scroll) during client-side transitions. If content scrolls behind a sticky or fixed header after navigation, you can fix this with CSS [`scroll-padding-top`](/docs/app/api-reference/components/link#scroll-offset-with-sticky-headers).
......
......@@ -6,12 +6,15 @@ related:
description: Learn more about the APIs mentioned in this page.
links:
- app/api-reference/directives/use-client
- app/guides/server-and-client-boundary
---
By default, layouts and pages are [Server Components](https://react.dev/reference/rsc/server-components), which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need interactivity or browser APIs, you can use [Client Components](https://react.dev/reference/rsc/use-client) to layer in functionality.
This page explains how Server and Client Components work in Next.js and when to use them, with examples of how to compose them together in your application.
> **Good to know:** For an explanation of where each component type runs and how the boundary works, see [The Server and Client Boundary](/docs/app/guides/server-and-client-boundary).
## When to use Server and Client Components?
The client and server environments have different capabilities. Server and Client Components allow you to run logic in each environment depending on your use case.
......@@ -20,7 +23,7 @@ Use **Client Components** when you need:
- [State](https://react.dev/learn/managing-state) and [event handlers](https://react.dev/learn/responding-to-events). E.g. `onClick`, `onChange`.
- [Lifecycle logic](https://react.dev/learn/lifecycle-of-reactive-effects). E.g. `useEffect`.
- Browser-only APIs. E.g. `localStorage`, `window`, `Navigator.geolocation`, etc.
- Browser-only APIs. E.g. `localStorage`, `window`, `navigator.geolocation`, etc.
- [Custom hooks](https://react.dev/learn/reusing-logic-with-custom-hooks).
Use **Server Components** when you need:
......@@ -56,12 +59,13 @@ export default async function Page({
}
```
```jsx filename="app/[id]/page.js" highlight={1,12} switcher
```jsx filename="app/[id]/page.js" highlight={1,13} switcher
import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'
export default async function Page({ params }) {
const post = await getPost(params.id)
const { id } = await params
const post = await getPost(id)
return (
<div>
......@@ -106,7 +110,7 @@ On the server, Next.js uses React's APIs to orchestrate rendering. The rendering
> **What is the React Server Component Payload (RSC)?**
>
> The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
> The RSC Payload is a compact, serialized representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
>
> - The rendered result of Server Components
> - Placeholders for where Client Components should be rendered and references to their JavaScript files
......@@ -135,7 +139,7 @@ On subsequent navigations:
### Using Client Components
You can create a Client Component by adding the [`"use client"`](https://react.dev/reference/react/use-client) directive at the top of the file, above your imports.
You can create a Client Component by adding the [`"use client"`](https://react.dev/reference/rsc/use-client) directive at the top of the file, above your imports.
```tsx filename="app/ui/counter.tsx" highlight={1} switcher
'use client'
......@@ -183,7 +187,7 @@ See [Interleaving Server and Client Components](/docs/app/getting-started/server
To reduce the size of your client JavaScript bundles, add `'use client'` to specific interactive components instead of marking large parts of your UI as Client Components.
For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` is interactive and needs to be a Client Component, however, the rest of the layout can remain a Server Component.
For example, the `<Layout>` component contains mostly static elements like a logo and navigation links, but includes an interactive search bar. `<Search />` needs to be a Client Component, while the rest of the layout can stay a Server Component.
```tsx filename="app/layout.tsx" highlight={12} switcher
// Client Component
......@@ -261,12 +265,13 @@ export default async function Page({
}
```
```jsx filename="app/[id]/page.js" highlight={1,7} switcher
```jsx filename="app/[id]/page.js" highlight={1,8} switcher
import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'
export default async function Page({ params }) {
const post = await getPost(params.id)
const { id } = await params
const post = await getPost(id)
return <LikeButton likes={post.likes} />
}
......
......@@ -371,6 +371,8 @@ export default function BlogPage() {
}
```
See [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and coordinating a library cache with the Next.js server and client caches.
## Examples
### Sequential data fetching
......
......@@ -441,7 +441,7 @@ export async function createPost(formData: FormData) {
}
```
```js filename="app/actions.js" switcher
```js filename="app/lib/actions.js" switcher
import { auth } from '@/lib/auth'
import { revalidatePath } from 'next/cache'
......@@ -481,7 +481,7 @@ export async function createPost(formData: FormData) {
}
```
```js filename="app/actions.js" switcher
```js filename="app/lib/actions.js" switcher
'use server'
import { auth } from '@/lib/auth'
......
......@@ -221,14 +221,14 @@ export default function Page() {
To start using CSS Modules, create a new file with the extension `.module.css` and import it into any component inside the `pages` directory:
```css filename="/styles/blog.module.css"
```css filename="styles/blog.module.css"
.blog {
padding: 24px;
}
```
```tsx filename="pages/blog/index.tsx" switcher
import styles from './blog.module.css'
import styles from '@/styles/blog.module.css'
export default function Page() {
return <main className={styles.blog}></main>
......@@ -236,7 +236,7 @@ export default function Page() {
```
```jsx filename="pages/blog/index.js" switcher
import styles from './blog.module.css'
import styles from '@/styles/blog.module.css'
export default function Page() {
return <main className={styles.blog}></main>
......@@ -299,7 +299,7 @@ export default function RootLayout({ children }) {
Import the stylesheet in the `pages/_app.js` file to apply the styles to **every route** in your application:
```tsx filename="pages/_app.js"
```jsx filename="pages/_app.js"
import '@/styles/global.css'
export default function MyApp({ Component, pageProps }) {
......
......@@ -257,7 +257,7 @@ The more specific image will take precedence over any OG images above it in the
The [`ImageResponse` constructor](/docs/app/api-reference/functions/image-response) allows you to generate dynamic images using JSX and CSS. This is useful for OG images that depend on data.
For example, to generate a unique OG image for each blog post, add a `opengraph-image.tsx` file inside the `blog` folder, and import the `ImageResponse` constructor from `next/og`:
For example, to generate a unique OG image for each blog post, add an `opengraph-image.tsx` file inside the `blog/[slug]` folder, and import the `ImageResponse` constructor from `next/og`:
```tsx filename="app/blog/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/og'
......
......@@ -81,7 +81,7 @@ Next.js can be adapted to run on different platforms to support their infrastruc
Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/adapters/testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters).
- [Vercel](https://vercel.com/docs/frameworks/nextjs)
- [Vercel](https://vercel.com/docs/frameworks/full-stack/nextjs)
- [Bun](https://bun.com/docs/guides/ecosystem/nextjs)
Cloudflare and Netlify are working on verified adapters built on the Adapter API. In the meantime, they offer their own Next.js integrations (see below).
......
......@@ -180,7 +180,13 @@ After every edit, verify the page still works at runtime using the next-dev-loop
### `next-cache-components-adoption`
The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill turns on [Cache Components](/docs/app/getting-started/caching) and resolves blocking routes until the app builds.
The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill migrates an app to [Cache Components](/docs/app/getting-started/caching):
1. Turns the flag on and finds the routes that can't prerender.
2. Fixes them one feature at a time, checking in with you before moving on.
3. Confirms a feature against `next dev` and `next build` before leaving it.
You choose whether the work lands as a series of PRs or stays on one branch.
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-adoption
......@@ -194,21 +200,33 @@ Adopt Cache Components in this project using the next-cache-components-adoption
### `next-cache-components-optimizer`
The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill maximizes the meaningful UI available on an exact navigation and guards it with an `@next/playwright` `instant()` test.
The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill takes a target route or set of routes and works toward the UI you want on screen at click time:
1. Writes a failing [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test for the UI you named.
2. Refactors the route until it passes, often by moving a data read below a `<Suspense>` boundary.
3. Commits the passing test with the refactoring, so it catches future regressions.
It needs a route that already builds with [Cache Components](/docs/app/getting-started/caching).
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-optimizer
```
For example, give the agent this prompt:
Then give the agent a prompt like:
```prompt
Make the navigation to `/settings` instant using the next-cache-components-optimizer Skill.
Make the navigation from /settings to /dashboard instant using the next-cache-components-optimizer Skill. The header and the project list should be part of the instant UI.
```
### `next-partial-prefetching-adoption`
The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill turns on [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) and resolves its insights until all routes reuse a shared App Shell.
The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill moves an app onto [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), where links share one App Shell:
1. Audits the existing `<Link prefetch={true}>` calls with you.
2. Turns the flag on and resolves the insights it surfaces.
3. Marks the routes whose URL data might be worth prefetching later.
It needs [Cache Components](/docs/app/getting-started/caching) already adopted.
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-adoption
......
This diff is collapsed.
......@@ -16,14 +16,16 @@ This diagram shows the authentication flow using React and Next.js features:
<Image
alt="Diagram showing the authentication flow with React and Next.js features"
srcLight="/docs/light/authentication-overview.png"
srcDark="/docs/dark/authentication-overview.png"
srcLight="/docs/light/authentication-overview-new.png"
srcDark="/docs/dark/authentication-overview-new.png"
width="1600"
height="1383"
/>
The examples on this page walk through basic username and password auth for educational purposes. While you can implement a custom auth solution, for increased security and simplicity, we recommend using an authentication library. These offer built-in solutions for authentication, session management, and authorization, as well as additional features such as social logins, multi-factor authentication, and role-based access control. You can find a list in the [Auth Libraries](#auth-libraries) section.
> **Good to know:** With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, reading the session and caching per-user data follow specific rules. See [Authentication with Cache Components](/docs/app/guides/authentication-with-cache-components).
## Authentication
<AppOnly>
......@@ -98,7 +100,7 @@ export async function signup(formData) {}
#### 2. Validate form fields on the server
Use the Server Action to validate the form fields on the server. If your authentication provider doesn't provide form validation, you can use a schema validation library like [Zod](https://zod.dev/) or [Yup](https://github.com/jquense/yup).
Use the Server Action to validate the form fields on the server. If your authentication provider doesn't provide form validation, you can use a schema validation library like [Zod](https://zod.dev/), [Valibot](https://valibot.dev/) or [Yup](https://github.com/jquense/yup).
Using Zod as an example, you can define a form schema with appropriate error messages:
......@@ -1363,7 +1365,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across
If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern.
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache).
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a context provider. For that pattern, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider), and use React's [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to keep sensitive session fields from reaching the client.
#### Auth checks in page components
......@@ -1550,60 +1552,6 @@ export async function GET() {
The example above demonstrates a Route Handler with a two-tier security check. It first checks for an active session, and then verifies if the logged-in user is an 'admin'.
## Context Providers
Using context providers for auth works due to [interleaving](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components). However, React `context` is not supported in Server Components, making them only applicable to Client Components.
This works, but any child Server Components will be rendered on the server first, and will not have access to the context provider’s session data:
```tsx filename="app/layout.tsx" switcher
import { ContextProvider } from 'auth-lib'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<ContextProvider>{children}</ContextProvider>
</body>
</html>
)
}
```
```tsx filename="app/ui/profile.tsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
```jsx filename="app/ui/profile.jsx" switcher
'use client'
import { useSession } from "auth-lib";
export default function Profile() {
const { userId } = useSession();
const { data } = useSWR(`/api/user/${userId}`, fetcher)
return (
// ...
);
}
```
If session data is needed in Client Components (e.g. for client-side data fetching), use React’s [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to prevent sensitive session data from being exposed to the client.
For the general pattern of passing server-fetched data through context and reading it with `use()`, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
</AppOnly>
<PagesOnly>
......
......@@ -108,7 +108,7 @@ export const dynamic = 'auto'
<details>
<summary>This is an advanced option that should only be used if you specifically need to override the default behavior.</summary>
By default, Next.js **will cache** any `fetch()` requests that are reachable **before** any Request-time APIs are used and **will not cache** `fetch` requests that are discovered **after** Request-time APIs are used.
A `fetch` request that sets no `cache` option is fetched once during `next build` if it is reachable **before** any Request-time APIs are used, because the route is prerendered up to that point. Requests discovered **after** a Request-time API run on every request.
`fetchCache` allows you to override the default `cache` option of all `fetch` requests in a layout or page.
......
......@@ -74,7 +74,7 @@ These headers can be omitted in specific cases without causing protocol errors.
**When `next-router-prefetch` is present, preserve both the prefetch header and the `_rsc` search parameter.** For prefetch flows, `_rsc` is a required cache-busting discriminator and should be treated as mandatory.
**The `_rsc` search parameter** must be included in the cache key. It distinguishes response variants (HTML vs. RSC, different prefetch types). Ensure your CDN does not strip query parameters from cache keys, as some CDNs do this by default. By default, when a RSC request arrives without the correct `_rsc` value, the server responds with a **307 redirect** to the URL with the correct hash. This behavior can be disabled by setting `experimental.validateRSCRequestHeaders` to `false`. CDNs should follow this redirect. Platforms that compute the hash upstream can rewrite requests to include the correct `_rsc` before forwarding to avoid an extra round trip.
**The `_rsc` search parameter** must be included in the cache key. It distinguishes response variants (HTML vs. RSC, different prefetch types). Ensure your CDN does not strip query parameters from cache keys, as some CDNs do this by default. By default, when an RSC request arrives without the correct `_rsc` value, the server responds with a **307 redirect** to the URL with the correct hash. This behavior can be disabled by setting `experimental.validateRSCRequestHeaders` to `false`. CDNs should follow this redirect. Platforms that compute the hash upstream can rewrite requests to include the correct `_rsc` before forwarding to avoid an extra round trip.
> **Good to know:** Today, `next-url` is included in the `_rsc` hash even during static prefetches. This means you cannot safely ignore it under the current scheme without potentially getting cache misses. The pathname-based direction described below resolves this gap.
......
---
title: Client-side data fetching
description: Fetch data in Client Components with a data-fetching library, optionally provide initial data from a Server Component, and coordinate server and client caches.
related:
description: Related guides and references.
links:
- app/getting-started/fetching-data
- app/guides/single-page-applications
- app/guides/interactive-apps
- app/getting-started/caching
---
Many apps can provide responsive interactions without a client data-fetching library. If a Client Component only needs to read server data once, [pass it a Promise and unwrap it with React's `use()`](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api).
This avoids adding a library for data that never revalidates on the client. See [Building interactive apps](/docs/app/guides/interactive-apps) for patterns using Server Functions, transitions, optimistic UI, and pending feedback.
Use a client data-fetching library such as [SWR](https://swr.vercel.app), [TanStack Query](https://tanstack.com/query), or [Apollo Client](https://www.apollographql.com/docs/react) when Client Components need a shared browser cache. These libraries can add focus revalidation, interval polling, request deduplication, or optimistic updates across components.
## Choose a client fetching pattern
First decide whether the initial view needs data from the server or can wait for a browser request after hydration. Client data-fetching libraries support three common patterns:
| Pattern | SWR | TanStack Query | When data becomes available |
| ----------------------- | ------------------------------ | --------------------- | -------------------------------------- |
| Inline loading states | `useSWR` | `useQuery` | Browser request after hydration |
| Suspense loading states | `useSWR` with `suspense: true` | `useSuspenseQuery` | Browser request after hydration |
| Provided by the server | `<SWRConfig fallback>` | `<HydrationBoundary>` | Initial render or streamed from server |
Use inline loading states when each component should render its own loading UI. Use [Suspense](/docs/app/getting-started/fetching-data#streaming) to define loading UI at a boundary and coordinate which parts of the interface reveal together or progressively. For client-only fetching, choose the pattern that matches the loading experience you want. Suspense coordinates rendering, while the data library and component structure determine when requests start.
For browser-driven interactions such as autocomplete, you can use either client-only pattern. The initial result waits for hydration and a browser request, which is often the right tradeoff for data that is not needed until an interaction.
Provide initial data from a [Server Component](/docs/app/getting-started/server-and-client-components) when the server knows what the initial render needs. The value can be included in the initial render or streamed through Suspense. The library receives it in the React Server Component payload and can continue managing it in the browser.
## Cache server data with Cache Components (optional)
Providing initial data and caching it on the server are independent choices. Add Cache Components when the server read or rendered view should be reused. When both are enabled, three cache layers can hold related data:
| Layer | What it stores | Freshness control |
| ---------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Next.js server cache | Cached data and Server Component output | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `revalidate` and `expire` |
| Next.js client cache | React Server Component payloads for visited and prefetched routes | [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` |
| Client data-fetching library | Browser data stored under an SWR key or TanStack query key | The library's revalidation options and mutations |
Next.js [prefetching](/docs/app/guides/prefetching) can place a route's React Server Component payload in the client cache before navigation.
The cache layers keep independent freshness policies and do not need matching durations. Cache identities and mutation invalidation must stay coordinated across layers.
## Coordinate mutations
Server Components, data-fetching libraries, and mutations manage different parts of the data flow:
- **Server Components** provide the initial data, scoped to the segment that owns it.
- **The data-fetching library** stores the browser value under a shared cache identity.
- **Mutations** can update the browser cache immediately and invalidate cached server data so the next render can read a fresh value.
An optimistic update should restore the previous browser value if the write fails. If the server read is not cached, there is no server tag to invalidate.
After a mutation, invalidate any cached server read that provided the initial data:
| Method | Use when | Next server read |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------ |
| [`updateTag(tag)`](/docs/app/api-reference/functions/updateTag) | A Server Action must make its update visible immediately | Waits for fresh data |
| [`revalidateTag(tag, 'max')`](/docs/app/api-reference/functions/revalidateTag) | The update is passive or stale data is acceptable | Serves stale data while revalidating |
| [`revalidateTag(tag, { expire: 0 })`](/docs/app/api-reference/functions/revalidateTag) | A webhook or external system requires immediate expiration | Waits for fresh data |
## Apply these patterns with SWR or TanStack Query
- [Client-side data fetching with SWR](/docs/app/guides/client-side-data-fetching/swr)
- [Client-side data fetching with TanStack Query](/docs/app/guides/client-side-data-fetching/tanstack-query)
See both patterns in the live [`next-spa-patterns` demo](https://next-spa-patterns.labs.vercel.dev) and its [source code](https://github.com/vercel-labs/next-spa-patterns).
This diff is collapsed.
......@@ -59,6 +59,16 @@ app.prepare().then(() => {
})
```
> **Set your own response headers before calling `handle`**: Next.js begins sending the response inside `handle(req, res)`, so by the time its promise resolves `res.headersSent` is already `true` and any later `res.setHeader()` call is silently discarded. Set headers you own, such as `Set-Cookie`, before handing the request to Next.js:
>
> ```js
> res.setHeader('Set-Cookie', 'sessionId=abc123; Max-Age=2592000')
>
> await handle(req, res)
> ```
>
> The same ordering applies when wrapping Next.js in another framework, for example `reply.raw` in Fastify or `res` in Express.
> `server.js` does not run through the Next.js Compiler or bundling process. Make sure the syntax and source code this file requires are compatible with the current Node.js version you are using. [View an example](https://github.com/vercel/next.js/tree/canary/examples/custom-server).
To run the custom server, you'll need to update the `scripts` in `package.json` like so:
......
......@@ -55,7 +55,7 @@ This approach works well when:
### Data Access Layer
For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is a internal library that controls how and when data is fetched, and what gets passed to your render context.
For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is an internal library that controls how and when data is fetched, and what gets passed to your render context.
A Data Access Layer should:
......
......@@ -76,7 +76,7 @@ Now go to the Debug panel (`Ctrl+Shift+D` on Windows/Linux, `⇧+⌘+D` on macOS
## Using the Debugger in Jetbrains WebStorm
Click the drop down menu listing the runtime configuration, and click `Edit Configurations...`. Create a `JavaScript Debug` debug configuration with `http://localhost:3000` as the URL. Customize to your liking (e.g. Browser for debugging, store as project file), and click `OK`. Run this debug configuration, and the selected browser should automatically open. At this point, you should have 2 applications in debug mode: the NextJS node application, and the client/browser application.
Click the drop down menu listing the runtime configuration, and click `Edit Configurations...`. Create a `JavaScript Debug` debug configuration with `http://localhost:3000` as the URL. Customize to your liking (e.g. Browser for debugging, store as project file), and click `OK`. Run this debug configuration, and the selected browser should automatically open. At this point, you should have 2 applications in debug mode: the Next.js node application, and the client/browser application.
## Debugging with Browser DevTools
......
......@@ -163,7 +163,7 @@ NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
This will tell Next.js to replace all references to `process.env.NEXT_PUBLIC_ANALYTICS_ID` in the Node.js environment with the value from the environment in which you run `next build`, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser.
> **Note**: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all `NEXT_PUBLIC_` variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to setup your own API to provide them to the client (either on demand or during initialization).
> **Note**: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all `NEXT_PUBLIC_` variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to set up your own API to provide them to the client (either on demand or during initialization).
```js filename="pages/index.js"
import setupAnalyticsService from '../lib/my-analytics-service'
......
......@@ -131,7 +131,7 @@ export async function updateUser(userId, formData) {}
Forms can be validated on the client or server.
- For **client-side validation**, you can use the HTML attributes like `required` and `type="email"` for basic validation.
- For **server-side validation**, you can use a library like [zod](https://zod.dev/) to validate the form fields. For example:
- For **server-side validation**, you can use a schema validation library like [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/) to validate the form fields. For example:
```tsx filename="app/actions.ts" switcher
'use server'
......
......@@ -18,7 +18,7 @@ To set up instrumentation, create `instrumentation.ts|js` file in the **root dir
Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated, and must complete before the server is ready to handle requests.
For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/observability/otel-overview):
For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/tracing/instrumentation):
```ts filename="instrumentation.ts" switcher
import { registerOTel } from '@vercel/otel'
......
......@@ -434,6 +434,7 @@ Add `useOptimistic` with a reducer to remap the card's status on the current fra
'use client'
import { startTransition, use, useOptimistic } from 'react'
import { toast } from 'sonner'
import { updateStatus } from '@/features/task/task-actions'
export function Board({ tasksPromise }) {
......@@ -449,7 +450,8 @@ export function Board({ tasksPromise }) {
function handleDrop(targetStatus, taskId) {
startTransition(async () => {
moveTask({ taskId, status: targetStatus })
await updateStatus(taskId, targetStatus)
const result = await updateStatus(taskId, targetStatus)
if (!result.success) toast.error(result.error)
})
}
......@@ -467,9 +469,9 @@ export function Board({ tasksPromise }) {
}
```
The reducer maps over the task list and updates the status of the dragged card, leaving the rest unchanged. If a background refresh arrives mid-drag, for example from polling or another user's mutation, React re-runs the reducer with the updated base data so the optimistic move sits on top of fresh data.
The reducer maps over the task list and updates the status of the dragged card, leaving the rest unchanged. If a background refresh arrives mid-drag, for example from polling or another user's mutation, React re-runs the reducer with the updated base data so the optimistic move sits on top of fresh data. The Server Function returns an error result when the task no longer exists, which the client displays in a toast.
This step uses the standalone `startTransition` instead of `useTransition` because the hook's `isPending` would trigger the board fade from Step 3. The optimistic move already covers the visual feedback, so no pending indicator is needed. If the Server Function fails, the card reverts.
This step uses the standalone `startTransition` instead of `useTransition` because the hook's `isPending` would trigger the board fade from Step 3. The optimistic move already covers the visual feedback, so no pending indicator is needed. If the Server Function returns an expected error, the card reverts. Unexpected errors are forwarded to the nearest [error boundary](/docs/app/getting-started/error-handling).
A card dragged from "Todo" to "In Progress" now lands in the target column the moment you release.
......@@ -724,11 +726,17 @@ The per-id tag `task-${id}` gives a single task its own handle. The broader `tas
'use server'
import { updateTag } from 'next/cache'
import { updateTaskStatus } from '@/lib/db'
export async function updateStatus(taskId: string, newStatus: Status) {
// …mutate
const updated = await updateTaskStatus(taskId, newStatus)
if (!updated) {
return { success: false as const, error: 'Task no longer exists' }
}
updateTag('tasks')
updateTag(`task-${taskId}`)
return { success: true as const, status: newStatus }
}
```
......@@ -738,7 +746,7 @@ In this demo, the comment thread stays dynamic because readers expect the curren
#### Prefetch the destination with the real request
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [runtime prefetching](/docs/app/guides/runtime-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click:
Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click:
```tsx filename="features/task/components/task-card.tsx"
<Link href={`/task/${id}`} prefetch={true}>
......@@ -746,7 +754,7 @@ Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next
</Link>
```
Runtime prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks.
Per-link prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks.
## Next steps
......@@ -760,12 +768,14 @@ The patterns in this guide combine a handful of primitives:
| A form needs pending, reset, and result state | [`useActionState`](https://react.dev/reference/react/useActionState) |
| An ancestor should show pending state for work happening elsewhere | [`data-pending`](https://react.dev/reference/react-dom/components/form#props) attribute styled with CSS |
| Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) |
| Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [Runtime prefetching](/docs/app/guides/runtime-prefetching) via `prefetch={true}` for content that depends on URL data |
| Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [per-link prefetching](/docs/app/guides/optimizing-prefetching) via `prefetch={true}` for content that depends on URL data |
Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving.
Related guides:
- [Client-side data fetching](/docs/app/guides/client-side-data-fetching) for direct browser fetching, providing initial data from a Server Component, and client cache coordination
- [Streaming](/docs/app/guides/streaming) for loading boundaries and `<Suspense>` patterns
- [Instant Navigation](/docs/app/guides/instant-navigation) for validating that navigations stay instant
- [View Transitions](/docs/app/guides/view-transitions) for animating state changes
- [Single-page applications](/docs/app/guides/single-page-applications#mutating-data-with-server-actions) for a shared-reducer `useOptimistic` example that keeps client and server list updates in sync
......@@ -74,7 +74,7 @@ This allows `.mdx` files to act as pages, routes, or imports in your application
### Handling `.md` files
By default, `next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option:
By default, `@next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option:
```js filename="next.config.mjs"
const withMDX = createMDX({
......
......@@ -10,6 +10,7 @@ related:
- app/getting-started/caching
- app/guides/preserving-ui-state
- app/guides/incremental-static-regeneration-cache-components
- app/guides/authentication-with-cache-components
- app/api-reference/functions/generate-static-params
- app/api-reference/config/next-config-js/cacheComponents
---
......@@ -95,6 +96,8 @@ You don't have to migrate every route at once. `instant = false` lets you get th
npx @next/codemod@canary cache-components-instant-false ./app
```
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
The app keeps building and serving, now with validation deferred for the opted-out routes.
3. **Fix synchronous IO. It can't be deferred.** Calls like `new Date()`, `Date.now()`, `Math.random()`, and `crypto.randomUUID()` during prerender throw a build error that `instant = false` does not clear, so a route that uses them won't build until you address it, opt-out or not. Move the call out of the prerendered shell so it runs at request time: wrap the part that needs it in [`<Suspense>`](https://react.dev/reference/react/Suspense) and call [`connection()`](/docs/app/api-reference/functions/connection) before the call, or move it into a Client Component.
......@@ -552,11 +555,11 @@ export default async function Page() {
## `generateStaticParams` and `dynamicParams`
Two behaviors change for [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) when Cache Components is enabled.
Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) handle params.
### `generateStaticParams` must return at least one param
**Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [App Shell](/docs/app/glossary#app-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params).
**Returning an empty array now errors.** Without Cache Components, returning `[]` defers every path to the first runtime visit. With Cache Components, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) must return at least one param so Next.js can prerender the route and validate it produces a non-empty [static shell](/docs/app/glossary#static-shell). An empty array raises [`empty-generate-static-params`](/docs/messages/empty-generate-static-params).
```tsx filename="app/blog/[slug]/page.tsx" switcher
// Before - defer all paths to runtime
......@@ -588,13 +591,19 @@ export async function generateStaticParams() {
}
```
Paths you don't return are still served. Next.js serves the App Shell instantly, then upgrades it in the background once the params are known. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow.
Paths you don't return are still served. Next.js prerenders a static shell for the unknown params and streams the rest at request time. See [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components) for the full prerender-a-subset workflow.
### `dynamicParams` is not supported
**Delete the export.** With Cache Components enabled, exporting `dynamicParams` fails the build with this error message:
> Route segment config "dynamicParams" is not compatible with `nextConfig.cacheComponents`.
### `dynamicParams` no longer blocks the first visit
Params not returned by `generateStaticParams` are rendered on request. If you used `dynamicParams: false` to reject them, call [`notFound()`](/docs/app/api-reference/functions/not-found) in the page when the param doesn't resolve to real data.
**`dynamicParams: true` (the default) now serves an App Shell instead of blocking.** Previously, visiting a param not returned by `generateStaticParams` blocked the response while the page rendered. With Cache Components, Next.js serves the App Shell instantly, then upgrades it in the background with the now-known params. `dynamicParams: false` is unchanged: unspecified paths still 404.
### Await `params` inside `<Suspense>`
To produce the App Shell, pass the `params` promise into a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary instead of awaiting it at the top of the component, so unknown params can still prerender.
To produce the static shell, pass the `params` promise into a [`<Suspense>`](/docs/app/api-reference/file-conventions/loading) boundary instead of awaiting it at the top of the component, so unknown params can still prerender.
```tsx filename="app/blog/[slug]/page.tsx" switcher
// Before - awaiting params at the top blocks the shell
......@@ -652,7 +661,7 @@ async function Post({ params }) {
}
```
The same applies to client hooks that read the route. When the route's pathname is fully known, they resolve during prerendering and need no boundary. When it depends on dynamic params not yet known, they suspend, wherever the component sits. A nav or breadcrumb in a shared layout, for instance, suspends while Next.js generates the App Shell for any route below it that has dynamic params. Wrap the component that reads the hook in `<Suspense>` (push the read down to the smallest leaf so the rest stays prerendered), or the build fails:
The same applies to client hooks that read the route. When the route's pathname is fully known, they resolve during prerendering and need no boundary. When it depends on dynamic params not yet known, they suspend, wherever the component sits. A nav or breadcrumb in a shared layout, for instance, suspends while Next.js generates the static shell for any route below it that has dynamic params. Wrap the component that reads the hook in `<Suspense>` (push the read down to the smallest leaf so the rest stays prerendered), or the build fails:
- [`usePathname`](/docs/app/api-reference/functions/use-pathname)
- [`useParams`](/docs/app/api-reference/functions/use-params)
......
......@@ -108,7 +108,7 @@ To upgrade your links to Next.js 13, you can use the [`new-link` codemod](/docs/
The behavior of [`next/script`](/docs/app/api-reference/components/script) has been updated to support both `pages` and `app`, but some changes need to be made to ensure a smooth migration:
- Move any `beforeInteractive` scripts you previously included in `_document.js` to the root layout file (`app/layout.tsx`).
- Move any `beforeInteractive` scripts you previously included in `_document.js` to a [root layout](/docs/app/api-reference/file-conventions/layout#root-layout), such as `app/layout.tsx` or `app/[locale]/layout.tsx`.
- The experimental `worker` strategy does not yet work in `app` and scripts denoted with this strategy will either have to be removed or modified to use a different strategy (e.g. `lazyOnload`).
- `onLoad`, `onReady`, and `onError` handlers will not work in Server Components so make sure to move them to a [Client Component](/docs/app/getting-started/server-and-client-components) or remove them altogether.
......
......@@ -355,7 +355,7 @@ This tells Next.js to generate a single route for the empty slug (`/`), effectiv
### Step 7: Add a Client-Only Entrypoint
Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that clients components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript.
Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that Client Components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript.
Create a `client.tsx` (or `client.js`) in `app/[[...slug]]/`:
......
......@@ -307,7 +307,7 @@ For most apps, the pending loading state is enough. Add a banner in the root lay
The same pattern extends to parameterized routes. A route like `/chats/[id]` renders its shared [App Shell](/docs/app/glossary#app-shell) when you navigate to `/chats/42` offline, and the dynamic messages behind its `<Suspense>` boundary load when the connection returns.
If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [runtime prefetching](/docs/app/guides/runtime-prefetching) to learn more.
If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to learn more.
## Retry Server Actions after the network returns
......
......@@ -195,7 +195,7 @@ It will work both on Vercel and when self-hosted.
We made sure that OpenTelemetry works out of the box on Vercel.
Follow [Vercel documentation](https://vercel.com/docs/concepts/observability/otel-overview/quickstart) to connect your project to an observability provider.
Follow [Vercel documentation](https://vercel.com/docs/tracing/instrumentation) to connect your project to an observability provider.
#### Self-hosting
......
......@@ -85,10 +85,10 @@ Next.js stores prefetched React Server Component payloads in memory, keyed by ro
With [Partial Prefetching](/docs/app/glossary#partial-prefetching) enabled via the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) config (which requires [Cache Components](/docs/app/getting-started/caching)), prefetching switches from the all-or-nothing model above to a per-route [App Shell](/docs/app/glossary#app-shell):
- **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full.
- **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/runtime-prefetching).
- **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/optimizing-prefetching).
- **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches.
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path.
See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to resolve cached URL-specific content before navigation with `prefetch={true}`.
## Controlling prefetching
......
......@@ -376,11 +376,11 @@ Consider the following data structure:
}
```
In [Proxy](/docs/app/api-reference/file-conventions/proxy), you can read from a database such as Vercel's [Edge Config](https://vercel.com/docs/edge-config/get-started) or [Redis](https://vercel.com/docs/redis), and redirect the user based on the incoming request:
In [Proxy](/docs/app/api-reference/file-conventions/proxy), you can read from a database such as Vercel's [Global Config](https://vercel.com/docs/global-config/get-started) or [Redis](https://vercel.com/docs/redis), and redirect the user based on the incoming request:
```ts filename="proxy.ts" switcher
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'
import { get } from '@vercel/global-config'
type RedirectEntry = {
destination: string
......@@ -404,7 +404,7 @@ export async function proxy(request: NextRequest) {
```js filename="proxy.js" switcher
import { NextResponse } from 'next/server'
import { get } from '@vercel/edge-config'
import { get } from '@vercel/global-config'
export async function proxy(request) {
const pathname = request.nextUrl.pathname
......
......@@ -182,6 +182,8 @@ module.exports = {
}
```
> **Good to know:** When [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) is set, Next.js uses a constant build ID and `generateBuildId` has no effect. [Version skew](#version-skew) is detected from the deployment ID instead.
## Multi-Server Deployments
When running Next.js across multiple server instances (for example, containers behind a load balancer), there are additional considerations to ensure consistent behavior.
......
This diff is collapsed.
......@@ -232,15 +232,19 @@ export default function Page() {
### Route Handlers
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. For example:
Route Handlers will render a static response when running `next build`. Only the `GET` HTTP verb is supported. This can be used to generate static HTML, JSON, TXT, or other files from cached or uncached data. To ensure Route Handlers are prerendered, you must explicitly mark the handler as static by adding `export const dynamic = 'force-static'` when a static export is enabled. For example:
```ts filename="app/data.json/route.ts" switcher
export const dynamic = 'force-static'
export async function GET() {
return Response.json({ name: 'Lee' })
}
```
```js filename="app/data.json/route.js" switcher
export const dynamic = 'force-static'
export async function GET() {
return Response.json({ name: 'Lee' })
}
......
......@@ -36,7 +36,7 @@ When a browser requests a page, two streams work together during the initial pag
### The HTML stream
React's server renderer produces progressive HTML chunks. The static parts of your page (layouts, navigation, Suspense fallbacks) render first and are sent immediately. When an async [Server Component](/docs/app/glossary#server-component) resolves, React streams its completed HTML along with inline `<script>` tags: one that swaps the fallback DOM node with the new content, and another carrying the [component payload](#the-component-payload) so React can later hydrate it. The browser executes the swap instantly, without waiting for the page's JavaScript bundle to load or hydration to complete. This is what the user _sees_: the page painting progressively, section by section.
React's server renderer produces progressive HTML chunks. The static parts of your page (layouts, navigation, Suspense fallbacks) render first and are sent immediately. When a `<Suspense>` boundary's content is ready, for example when an async [Server Component](/docs/app/glossary#server-component) resolves, React streams its completed HTML along with inline `<script>` tags: one that swaps the fallback DOM node with the new content, and another carrying the [component payload](#the-component-payload) so React can later hydrate it. The browser executes the swap instantly, without waiting for the page's JavaScript bundle to load or hydration to complete. This is what the user _sees_: the page painting progressively, section by section.
### The component payload
......@@ -579,11 +579,17 @@ Without streaming, the server waits for all data before sending any HTML, so TTF
### LCP (Largest Contentful Paint)
If your LCP element (a hero image, a main heading, a product photo) is inside a Suspense boundary, it can't paint until that boundary resolves. To keep LCP fast:
If your LCP element (a hero image, a main heading, a product photo) is inside a Suspense boundary, it can't paint until that boundary's content is swapped in. The element then depends on the work the server does to render it, not on your initial server response time. Revealing it costs something on the client too, because React streams a small inline script alongside the boundary's HTML and the content only appears once that script runs.
Data fetching is not the only reason a boundary delays your LCP element. React also holds back a large boundary, because sending its HTML takes time. See [what activates a Suspense boundary](https://react.dev/reference/react/Suspense#what-activates-a-suspense-boundary).
> **Good to know:** As a rule of thumb, if there's a Suspense boundary, React might use it. Under a slow network or a busy CPU, concurrent rendering can fall back to it even when you didn't expect it. Adding a boundary means accepting that, so don't add one you don't need.
To keep LCP fast:
- Keep LCP elements **outside** or **above** Suspense boundaries so they render as part of the static shell.
- Use the [`preload`](/docs/app/api-reference/components/image#preload) prop on `next/image` for LCP images. This injects a `<link rel="preload">` into the `<head>`, so the browser starts fetching the image from the very first chunk, before the `<img>` tag even appears in the HTML.
- For non-image LCP elements (text, headings), make sure they are not wrapped in a Suspense boundary that depends on slow data.
- Use the [`preload`](/docs/app/api-reference/components/image#preload) prop on `next/image` for LCP images. This injects a `<link rel="preload">` into the `<head>`, so the browser starts fetching the image from the very first chunk, before the `<img>` tag even appears in the HTML. It controls when the image is fetched, not when it paints. An image inside a boundary still waits for the swap.
- For non-image LCP elements (text, headings), render them outside Suspense boundaries.
### CLS (Cumulative Layout Shift)
......
......@@ -70,7 +70,7 @@ yarn create jest@latest
bun create jest@latest
```
This will take you through a series of prompts to setup Jest for your project, including automatically creating a `jest.config.ts|js` file.
This will take you through a series of prompts to set up Jest for your project, including automatically creating a `jest.config.ts|js` file.
Update your config file to use `next/jest`. This transformer has all the necessary configuration options for Jest to work with Next.js:
......
......@@ -46,7 +46,7 @@ yarn create playwright
bun create playwright
```
This will take you through a series of prompts to setup and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide.
This will take you through a series of prompts to set up and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide.
## Creating your first Playwright E2E test
......
......@@ -4,7 +4,7 @@ nav_title: Vitest
description: Learn how to set up Vitest with Next.js for Unit Testing.
---
Vitest and React Testing Library are frequently used together for **Unit Testing**. This guide will show you how to setup Vitest with Next.js and write your first tests.
Vitest and React Testing Library are frequently used together for **Unit Testing**. This guide will show you how to set up Vitest with Next.js and write your first tests.
> **Good to know:** Since `async` Server Components are new to the React ecosystem, Vitest currently does not support them. While you can still run **unit tests** for synchronous Server and Client Components, we recommend using **E2E tests** for `async` components.
......
......@@ -76,7 +76,9 @@ npx @next/codemod upgrade canary --yes
npx @next/codemod@canary cache-components-instant-false ./app
```
This codemod adds `export const instant = false` to every `app/**/{page,layout,default}` file that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`.
This codemod adds `export const instant = false` to every `{page,layout,default}` file in your app directory that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`.
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
```diff filename="app/page.tsx"
+ // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.
......@@ -98,7 +100,9 @@ See the [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-comp
npx @next/codemod@canary remove-partial-prefetch ./app
```
This codemod removes `export const prefetch = 'partial'` from `app/**/{page,layout}` files, so you can enable [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) globally and then drop the now-redundant per-route opt-ins. It removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place.
This codemod removes `export const prefetch = 'partial'` from the `{page,layout}` files in your app directory, so you can enable [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) globally and then drop the now-redundant per-route opt-ins. It removes only the `'partial'` value and leaves other values such as `prefetch = 'force-disabled'` in place.
> **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count.
```diff filename="app/products/[slug]/page.tsx"
- export const prefetch = 'partial'
......
......@@ -602,7 +602,7 @@ To continue using Speed Insights, follow the [Vercel Speed Insights Quickstart](
The `geo` and `ip` properties on `NextRequest` have been removed as these values are provided by your hosting provider. A [codemod](/docs/app/guides/upgrading/codemods#150) is available to automate this migration.
If you are using Vercel, you can alternatively use the `geolocation` and `ipAddress` functions from [`@vercel/functions`](https://vercel.com/docs/functions/vercel-functions-package) instead:
If you are using Vercel, you can alternatively use the `geolocation` and `ipAddress` functions from [`@vercel/functions`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package) instead:
```ts filename="middleware.ts"
import { geolocation } from '@vercel/functions'
......
......@@ -276,7 +276,7 @@ export default nextConfig
### Turbopack File System Caching
Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`. See [`turbopackFileSystemCache`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable it.
Turbopack stores compiler artifacts on disk between runs, for significantly faster compile times across restarts. Filesystem caching is enabled by default for both `next dev` and `next build`, through `experimental.turbopackFileSystemCacheForDev` and `experimental.turbopackFileSystemCacheForBuild`. See [Turbopack FileSystem Caching](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) to configure or disable either one.
## Async Request APIs (Breaking change)
......@@ -1074,7 +1074,7 @@ const nextConfig = {
},
}
export default nextConfig
module.exports = nextConfig
```
Evaluate if AMP is still necessary for your use case. Most performance benefits can now be achieved through Next.js's built-in optimizations and modern web standards.
......
......@@ -163,13 +163,13 @@ Self-hosting videos may be preferable for several reasons:
### Using Vercel Blob for video hosting
[Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob:
[Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) offers an efficient way to host videos, providing a scalable cloud storage solution that works well with Next.js. Here's how you can host a video using Vercel Blob:
**1. Uploading a video to Vercel Blob**
In your Vercel dashboard, navigate to the "Storage" tab and select your [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table.
In your Vercel dashboard, navigate to the "Storage" tab and select your [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) store. In the Blob table's upper-right corner, find and click the "Upload" button. Then, choose the video file you wish to upload. After the upload completes, the video file will appear in the Blob table.
Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on [server-side uploads](https://vercel.com/docs/storage/vercel-blob/server-upload). Vercel also supports [client-side uploads](https://vercel.com/docs/storage/vercel-blob/client-upload). This method may be preferable for certain use cases.
Alternatively, you can upload your video using a server action. For detailed instructions, refer to the Vercel documentation on [server-side uploads](https://vercel.com/docs/vercel-blob/server-upload). Vercel also supports [client-side uploads](https://vercel.com/docs/vercel-blob/client-upload). This method may be preferable for certain use cases.
**2. Displaying the video in Next.js**
......@@ -207,7 +207,7 @@ In this approach, the page uses the video's `@vercel/blob` URL to display the vi
### Adding subtitles to your video
If you have subtitles for your video, you can easily add them using the `<track>` element inside your `<video>` tag. You can fetch the subtitle file from [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) in a similar way as the video file. Here's how you can update the `<VideoComponent>` to include subtitles.
If you have subtitles for your video, you can easily add them using the `<track>` element inside your `<video>` tag. You can fetch the subtitle file from [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) in a similar way as the video file. Here's how you can update the `<VideoComponent>` to include subtitles.
```jsx filename="app/page.jsx"
async function VideoComponent({ fileName }) {
......@@ -237,13 +237,13 @@ To continue learning more about video optimization and best practices, please re
- **Understanding video formats and codecs**: Choose the right format and codec, like MP4 for compatibility or WebM for web optimization, for your video needs. For more details, see [Mozilla's guide on video codecs](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs).
- **Video compression**: Use tools like FFmpeg to effectively compress videos, balancing quality with file size. Learn about compression techniques at [FFmpeg's official website](https://www.ffmpeg.org/).
- **Resolution and bitrate adjustment**: Adjust [resolution and bitrate](https://www.dacast.com/blog/bitrate-vs-resolution/#:~:text=The%20two%20measure%20different%20aspects,yield%20different%20qualities%20of%20video) based on the viewing platform, with lower settings for mobile devices.
- **Content Delivery Networks (CDNs)**: Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. [Learn more](https://vercel.com/docs/edge-network/overview?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) about CDNs and their benefits.
- **Content Delivery Networks (CDNs)**: Utilize a CDN to enhance video delivery speed and manage high traffic. When using some storage solutions, such as Vercel Blob, CDN functionality is automatically handled for you. [Learn more](https://vercel.com/docs/cdn?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) about CDNs and their benefits.
Explore these video streaming platforms for integrating video into your Next.js projects:
### Open source `next-video` component
- Provides a `<Video>` component for Next.js, compatible with various hosting services including [Vercel Blob](https://vercel.com/docs/storage/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), S3, Backblaze, and Mux.
- Provides a `<Video>` component for Next.js, compatible with various hosting services including [Vercel Blob](https://vercel.com/docs/vercel-blob?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), S3, Backblaze, and Mux.
- [Detailed documentation](https://next-video.dev/docs) for using `next-video.dev` with different hosting services.
### Cloudinary Integration
......
......@@ -12,22 +12,28 @@ React's `<ViewTransition>` component integrates with the browser's [View Transit
This guide walks through four patterns that cover the most common cases: morphing shared elements, animating loading states, adding directional navigation, and crossfading content within the same route.
## Use the vercel-react-view-transitions skill
## Add view transitions with an agent
The [`vercel-react-view-transitions`](https://github.com/vercel-labs/agent-skills/tree/main/skills/react-view-transitions) skill teaches a coding agent the patterns in this guide, plus the CSS recipes and troubleshooting for applying them to an existing app.
The [`vercel-react-view-transitions`](https://skills.sh/vercel-labs/agent-skills/vercel-react-view-transitions) skill teaches a coding agent the patterns in this guide, plus the CSS recipes and troubleshooting for applying them to an existing app.
Install the skill:
```bash filename="Terminal"
npx skills add https://github.com/vercel-labs/agent-skills --skill vercel-react-view-transitions
npx skills add vercel-labs/agent-skills --skill vercel-react-view-transitions
```
Then give the agent this prompt:
Then prompt the agent with something like:
```prompt
Add view transitions to this app using the vercel-react-view-transitions skill.
```
Or prompt for a specific transition, such as:
- Morphing a thumbnail into a hero image
- Sliding between routes forward and back
- Crossfading content within the same route
To apply the patterns yourself, follow the walkthrough below.
## Example
......
---
title: Directives
description: Directives are used to modify the behavior of your Next.js application.
description: Learn how React and Next.js directives define client entry points, Server Functions, and cached output.
---
The following directives are available:
Directives are string literals that tell the compiler and bundler how to treat the code around them. On their own, directives look like plain strings, but Next.js and React read them as instructions that transform the code they cover. A directive can create a client entry point or a Server Function, or cache a function's or component's output.
| Directive | Defined by | Effect |
| --------------------------------------------------------------- | ---------- | --------------------------------------------------- |
| [`'use client'`](/docs/app/api-reference/directives/use-client) | React | Creates a client entry point from Server Components |
| [`'use server'`](/docs/app/api-reference/directives/use-server) | React | Exposes server-side functions as Server Functions |
| [`'use cache'`](/docs/app/api-reference/directives/use-cache) | Next.js | Caches and reuses output based on the code's inputs |
The `'use cache'` directive also has [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) and [`'use cache: private'`](/docs/app/api-reference/directives/use-cache-private) variants. Configure custom [cache handlers](/docs/app/api-reference/config/next-config-js/cacheHandlers) to control where cached entries are stored.
> **Good to know:** Next.js applies directives during compilation in both development and production.
>
> The error overlay, indicators, and stack traces point to your source file and line rather than the generated output.
## Where to place a directive
The `'use client'` directive must appear at the top of a file, before any imports. It applies to the entire module and defines a file-wide boundary because the module is bundled and shipped to the browser. You cannot use `'use client'` inline.
Place `'use server'` or `'use cache'` at the top of a file to apply the directive to every export. Place either directive at the top of a function to apply it only to that function.
```ts filename="app/data.ts" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id: string) {
return { id }
}
```
```js filename="app/data.js" switcher
// File-level: applies to every export
'use cache'
export async function getUser(id) {
return { id }
}
```
```tsx filename="app/user.tsx" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
```jsx filename="app/user.js" switcher
// Function-level: applies to this function only
export async function User() {
'use cache'
return <p>User</p>
}
```
Declare `'use server'` and `'use cache'` in server modules, not in a `'use client'` module.
To import a `'use server'` or `'use cache'` function into a Client Component, place the directive at the top of the server module. The Client Component receives a reference that invokes the function on the server.
Place the directive inside a function when it should apply only to that function or component. When it should apply to several exported functions, place it at the top of the file instead of repeating it.
Every exported function covered by a file-level `'use server'` or `'use cache'` directive must be `async`.
## What each directive requires
A directive imposes rules on the code it covers:
- **`'use client'`** marks its exports as the boundary between server and client. Client Component props that cross the boundary must be [serializable](https://react.dev/reference/rsc/use-client#serializable-types). Ordinary functions, such as event handlers, cannot cross, but Server Functions can cross as references.
- **`'use server'`** marks the functions it covers as [Server Functions](/docs/app/glossary#server-function). Server Functions must be `async`. When invoked from a Client Component, their arguments and return values are serialized across the network. The Client Component receives a reference that invokes the function on the server, not the function's code.
- **`'use cache'`** caches the output of the functions or components it covers based on their inputs. Cached functions and components must be `async`. Their arguments and return values must be serializable, except for non-serializable values that the cached code passes through without inspecting. Cached code cannot read request-time APIs like `cookies()`, `headers()`, or `searchParams` directly.
With `'use cache'` at the top of a page or layout file, exported functions such as `generateMetadata` and `generateStaticParams` must be `async`.
## Placement decides what you cache
With `'use cache'`, placement determines the scope of a cache entry. A directive at the top of a page caches the page's output and the components it imports. The same directive inside a data function caches only that function's result. When one data request performs the expensive work, cache that function instead of the page.
With [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote), a remote cache handler stores entries. Larger entries can increase storage and network costs.
......@@ -44,13 +44,11 @@ const nextConfig = {
cacheComponents: true,
}
export default nextConfig
module.exports = nextConfig
```
Then add `'use cache: private'` to your function along with a `cacheLife` configuration.
> **Good to know**: This directive is not available in Route Handlers.
### Basic example
In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope:
......@@ -151,7 +149,7 @@ async function getRecommendations(productId) {
}
```
> **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
> **Good to know**: The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
## Request APIs allowed in private caches
......
......@@ -44,7 +44,7 @@ const nextConfig = {
cacheComponents: true,
}
export default nextConfig
module.exports = nextConfig
```
Then add `'use cache: remote'` to the functions or components where you've determined remote caching is justified. The handler implementation is configured via [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers), though hosting providers should typically provide this automatically. If you're self-hosting, see the `cacheHandlers` configuration reference to set up your cache storage.
......
......@@ -7,7 +7,7 @@ The `'use client'` directive declares an entry point for the components to be re
> **Good to know:**
>
> You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the client-server [boundary](https://nextjs.org/docs/app/building-your-application/rendering#network-boundary), and the components exported from such a file serve as entry points to the client.
> You do not need to add the `'use client'` directive to every file that contains Client Components. You only need to add it to the files whose components you want to render directly within Server Components. The `'use client'` directive defines the [server and client boundary](/docs/app/guides/server-and-client-boundary), and the components exported from such a file serve as entry points to the client.
## Usage
......
......@@ -109,36 +109,38 @@ export default function MyButton() {
In the following example, `use server` is used inline at the top of a function to mark it as a [Server Function](https://19.react.dev/reference/rsc/server-functions):
```tsx filename="app/posts/[id]/page.tsx" switcher highlight={8}
```tsx filename="app/posts/[id]/page.tsx" switcher highlight={9}
import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache'
export default async function PostPage({ params }: { params: { id: string } }) {
const post = await getPost(params.id)
export default async function PostPage({ params }: PageProps<'/posts/[id]'>) {
const { id } = await params
const post = await getPost(id)
async function updatePost(formData: FormData) {
'use server'
// Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData)
revalidatePath(`/posts/${params.id}`)
await savePost(id, formData)
revalidatePath(`/posts/${id}`)
}
return <EditPost updatePostAction={updatePost} post={post} />
}
```
```jsx filename="app/posts/[id]/page.js" switcher highlight={8}
```jsx filename="app/posts/[id]/page.js" switcher highlight={9}
import { EditPost } from './edit-post'
import { revalidatePath } from 'next/cache'
export default async function PostPage({ params }) {
const post = await getPost(params.id)
const { id } = await params
const post = await getPost(id)
async function updatePost(formData) {
'use server'
// Verify auth before saving (e.g. inside savePost)
await savePost(params.id, formData)
revalidatePath(`/posts/${params.id}`)
await savePost(id, formData)
revalidatePath(`/posts/${id}`)
}
return <EditPost updatePostAction={updatePost} post={post} />
......
......@@ -285,7 +285,7 @@ export default function Page() {
}
```
```jsx filename="/app/ui/search-button.js" switcher
```jsx filename="/app/page.js" switcher
import Form from 'next/form'
import { SearchButton } from '@/ui/search-button'
......
......@@ -239,7 +239,7 @@ An integer between `1` and `100` that sets the quality of the optimized image. H
<Image quality={75} />
```
If you’ve configured [qualities](#qualities) in `next.config.js`, the value must match one of the allowed entries.
If you’ve configured [qualities](#qualities) in `next.config.js`, a value outside that list is coerced to the closest allowed entry. For example, with `qualities: [50, 75, 100]`, a `quality` of `80` is served as `75`. Development logs a warning so you can add the value to the allowlist.
> **Good to know**: If the original image is already low quality, setting a high quality value will increase the file size without improving appearance.
......@@ -1069,7 +1069,7 @@ export default function MyImage() {
}
```
When using `fill`, the parent element must have `position: relative` or `display: block`. This is necessary for the proper rendering of the image element in that layout mode.
When using `fill`, the parent element must be positioned, with `position: relative`, `fixed`, or `absolute`. The image itself uses `position: absolute`, so it sizes against the nearest positioned ancestor.
```jsx
<div style={{ position: 'relative' }}>
......
......@@ -70,14 +70,14 @@ The following props can be passed to the `<Link>` component:
<AppOnly>
| Prop | Example | Type | Required |
| ------------------------------------- | -------------------------------- | ---------------- | -------- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes |
| [`replace`](#replace) | `replace={false}` | Boolean | - |
| [`scroll`](#scroll) | `scroll={false}` | Boolean | - |
| [`prefetch`](#prefetch) | `prefetch={false}` | Boolean or null | - |
| [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - |
| [`transitionTypes`](#transitiontypes) | `transitionTypes={['slide-in']}` | `string[]` | - |
| Prop | Example | Type | Required |
| ------------------------------------- | -------------------------------- | -------------------------- | -------- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes |
| [`replace`](#replace) | `replace={false}` | Boolean | - |
| [`scroll`](#scroll) | `scroll={false}` | Boolean | - |
| [`prefetch`](#prefetch) | `prefetch={false}` | Boolean, `"auto"`, or null | - |
| [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - |
| [`transitionTypes`](#transitiontypes) | `transitionTypes={['slide-in']}` | `string[]` | - |
</AppOnly>
......@@ -300,7 +300,7 @@ Prefetching happens when a `<Link />` component enters the user's viewport (init
The following values can be passed to the `prefetch` prop:
- **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched.
- **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch is the [App Shell](/docs/app/glossary#app-shell) plus the per-link runtime data and the cached content behind it. See [Runtime prefetching](/docs/app/guides/runtime-prefetching).
- **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch includes the [App Shell](/docs/app/glossary#app-shell) and cached content that depends on the link's URL data. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
- `false`: Prefetching will never happen both on entering the viewport and on hover.
> **With Partial Prefetching enabled** ([`partialPrefetching: true`](/docs/app/api-reference/config/next-config-js/partialPrefetching)): the default changes. `auto` prefetches the per-route [App Shell](/docs/app/glossary#app-shell) (the route's static and cached content) instead of the full page. See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full behavior change.
......@@ -333,7 +333,7 @@ export default function Page() {
<PagesOnly>
Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation's. **Prefetching is only enabled in production**.
Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation. **Prefetching is only enabled in production**.
The following values can be passed to the `prefetch` prop:
......
......@@ -72,7 +72,7 @@ Scripts denoted with this strategy are preloaded and fetched before any first-pa
<AppOnly>
`beforeInteractive` scripts must be placed inside the root layout (`app/layout.tsx`) and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
Scripts with the `beforeInteractive` strategy must be placed inside a [root layout](/docs/app/api-reference/file-conventions/layout#root-layout), such as `app/layout.tsx` or `app/[locale]/layout.tsx`, and are designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).
</AppOnly>
......@@ -155,6 +155,12 @@ export default function Document() {
> **Good to know**: Scripts with `beforeInteractive` will always be injected inside the `head` of the HTML document regardless of where it's placed in the component.
<AppOnly>
> **Good to know**: These scripts run once per document load. A client-side navigation does not run them again, including one that only changes a root param, such as `/en` to `/fi`, since the root layout stays the same.
</AppOnly>
Some examples of scripts that should be fetched as soon as possible with `beforeInteractive` include:
- Bot detectors
......
......@@ -389,7 +389,7 @@ export default async function sitemap(props) {
}
```
Your generated sitemaps will be available at `/.../sitemap/[id]`. For example, `/product/sitemap/1.xml`.
Your generated sitemaps will be available at `/.../sitemap/[id].xml`. For example, `/product/sitemap/1.xml`.
See the [`generateSitemaps` API reference](/docs/app/api-reference/functions/generate-sitemaps) for more information.
......@@ -413,6 +413,8 @@ type Sitemap = Array<{
alternates?: {
languages?: Languages<string>
}
images?: string[]
videos?: Videos[]
}>
```
......
......@@ -39,11 +39,11 @@ export default function Page() {
Opts the segment into [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) without enabling the global [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag. A `<Link>` pointing at a segment with `prefetch = 'partial'` loads the per-route [App Shell](/docs/app/glossary#app-shell) instead of the legacy full prefetch. Set this on the destination, not the link.
For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js may also prefetch the segment at runtime. The server renders a fresh response that resolves per-link runtime data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime.
For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js uses per-link prefetching. The server renders a fresh response that resolves URL data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime.
Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports.
> **Good to know**: When Next.js runtime-prefetches a segment, all downstream segments are included in the same runtime prefetch request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the runtime response.
> **Good to know**: When Next.js performs a per-link prefetch for a segment, all downstream segments are included in the same request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the response.
```tsx filename="page.tsx"
export const prefetch = 'partial'
......@@ -61,7 +61,7 @@ A prefetch starts with a `<Link>` that expresses intent (should this destination
A destination can't know which links target it, so the segment config caps what any `<Link prefetch={true}>` pulls:
- [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves per-link runtime data (`params`, `searchParams`, the full URL).
- [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves URL data (`params`, `searchParams`, and the full URL) and the cached content behind it.
- [`'force-disabled'`](#force-disabled): skip segment data entirely.
`<Link prefetch={false}>` skips prefetching at the link level regardless of how the destination is configured.
......
......@@ -108,7 +108,7 @@ By default, Next.js keeps track of the active _state_ (or subpage) for each slot
### With `useSelectedLayoutSegment(s)`
Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRoutesKey` parameter, which allows you to read the active route segment within a slot.
Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) and [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) accept a `parallelRouteKey` parameter, which allows you to read the active route segment within a slot.
```tsx filename="app/layout.tsx" switcher
'use client'
......
......@@ -138,9 +138,11 @@ Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp
## Params
Next.js calls the Proxy function with two arguments, [`request`](#request) and [`event`](#event), in that order. Declare only the ones you use.
### `request`
When defining Proxy, the default export function accepts a single parameter, `request`. This parameter is an instance of `NextRequest`, which represents the incoming HTTP request.
The first parameter is an instance of `NextRequest`, which represents the incoming HTTP request.
```tsx filename="proxy.ts" switcher
import type { NextRequest } from 'next/server'
......@@ -156,6 +158,36 @@ export function proxy(request) {
}
```
### `event`
The second parameter is an instance of `NextFetchEvent`. It exposes a single method, `waitUntil(promise)`, which keeps the Proxy invocation alive until the promise settles, so background work like logging or analytics can finish after the response is sent. See [`waitUntil` and `NextFetchEvent`](#waituntil-and-nextfetchevent) for a full example.
```tsx filename="proxy.ts" switcher
import type { NextFetchEvent, NextRequest } from 'next/server'
export function proxy(request: NextRequest, event: NextFetchEvent) {
event.waitUntil(
fetch('https://example.com/log', {
method: 'POST',
body: JSON.stringify({ pathname: request.nextUrl.pathname }),
})
)
}
```
```js filename="proxy.js" switcher
export function proxy(request, event) {
event.waitUntil(
fetch('https://example.com/log', {
method: 'POST',
body: JSON.stringify({ pathname: request.nextUrl.pathname }),
})
)
}
```
### `NextProxy` type
If you prefer a shorthand, you can use the `NextProxy` type. It infers the parameter types for both `request` (`NextRequest`) and `event` (`NextFetchEvent`) automatically:
```tsx filename="proxy.ts"
......
......@@ -34,7 +34,7 @@ const nextConfig = {
cacheComponents: true,
}
export default nextConfig
module.exports = nextConfig
```
`cacheLife` can only be used within a cache directive scope.
......@@ -265,7 +265,7 @@ A short cache lifetime changes where the cached content can be delivered from:
- **`revalidate` of `0`, or `expire` under 5 minutes**: excluded from prerenders, becoming a "dynamic hole" resolved at request time.
- **`stale` under 30 seconds**: excluded from prerenders, because a prefetch would expire before the user could click.
- **`stale` from 30 seconds up to 5 minutes**: included in prerenders, but excluded from the route's [App Shell](/docs/app/glossary#app-shell).
- **`stale` of at least 30 seconds but under 5 minutes**: included in prerenders, but excluded from the route's [App Shell](/docs/app/glossary#app-shell).
Of the presets, only `seconds` falls under any of these thresholds: its `expire` of 1 minute excludes it from prerenders.
......
......@@ -33,7 +33,7 @@ const nextConfig = {
cacheComponents: true,
}
export default nextConfig
module.exports = nextConfig
```
The `cacheTag` function takes one or more string values.
......@@ -44,7 +44,8 @@ import { cacheTag } from 'next/cache'
export async function getData() {
'use cache'
cacheTag('my-data')
const data = await fetch('/api/data')
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
```
......@@ -55,7 +56,8 @@ import { cacheTag } from 'next/cache'
export async function getData() {
'use cache'
cacheTag('my-data')
const data = await fetch('/api/data')
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
```
......@@ -118,7 +120,10 @@ export async function Bookings({ type = 'haircut' }: BookingsProps) {
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data
}
......@@ -134,7 +139,10 @@ export async function Bookings({ type = 'haircut' }) {
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
return data
}
......@@ -156,7 +164,10 @@ interface BookingsProps {
export async function Bookings({ type = 'haircut' }: BookingsProps) {
async function getBookingsData() {
'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
cacheTag('bookings-data', data.id)
return data
}
......@@ -170,7 +181,10 @@ import { cacheTag } from 'next/cache'
export async function Bookings({ type = 'haircut' }) {
async function getBookingsData() {
'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
const response = await fetch(
`https://api.example.com/bookings?type=${encodeURIComponent(type)}`
)
const data = await response.json()
cacheTag('bookings-data', data.id)
return data
}
......
......@@ -8,6 +8,8 @@ related:
- app/api-reference/file-conventions/error
---
<AppOnly>
The `catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to the [`error.js`](/docs/app/api-reference/file-conventions/error) file convention, enabling component-level error recovery anywhere in your component tree.
Compared to a custom React error boundary, `catchError` is designed to work with Next.js out of the box:
......@@ -54,6 +56,51 @@ function ErrorFallback(props, { error, retry }) {
export default catchError(ErrorFallback)
```
</AppOnly>
<PagesOnly>
The `catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to writing a [custom React error boundary class](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary), enabling component-level error recovery anywhere in your component tree.
Compared to a custom React error boundary, `catchError` is designed to work with Next.js out of the box:
- **Built-in error recovery** — `reset()` re-renders the error boundary's children, letting users recover from errors without a full page reload.
- **Client navigation handling** — The error state automatically clears when you do a client navigation to a different route.
```tsx filename="components/custom-error-boundary.tsx" switcher
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, reset }: ErrorInfo) {
return (
<div>
<h2>{props.title}</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
```jsx filename="components/custom-error-boundary.js" switcher
import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) {
return (
<div>
<h2>{props.title}</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
</PagesOnly>
## Reference
### Parameters
......@@ -71,6 +118,8 @@ A function that renders the error UI when an error is caught. It receives two ar
- `props` — The props passed to the wrapper component (excluding `children`).
- `errorInfo` — An object containing information about the error:
<AppOnly>
| Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. |
......@@ -79,6 +128,17 @@ A function that renders the error UI when an error is caught. It receives two ar
The `fallback` function must be a Client Component (or defined in a `'use client'` module).
</AppOnly>
<PagesOnly>
| Property | Type | Description |
| -------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. |
| `reset` | `() => void` | Resets the error state and re-renders the error boundary's children. |
</PagesOnly>
### Returns
`catchError` returns a React component that:
......@@ -89,10 +149,12 @@ The `fallback` function must be a Client Component (or defined in a `'use client
## Examples
### Client Component
### Basic usage
Define a fallback and use the returned component to wrap parts of your UI:
<AppOnly>
```tsx filename="app/some-component.tsx" switcher
import ErrorWrapper from '../custom-error-boundary'
......@@ -109,8 +171,32 @@ export default function Component({ children }) {
}
```
</AppOnly>
<PagesOnly>
```tsx filename="components/some-component.tsx" switcher
import ErrorWrapper from './custom-error-boundary'
export default function Component({ children }: { children: React.ReactNode }) {
return <ErrorWrapper title="Dashboard Error">{children}</ErrorWrapper>
}
```
```jsx filename="components/some-component.js" switcher
import ErrorWrapper from './custom-error-boundary'
export default function Component({ children }) {
return <ErrorWrapper title="Dashboard Error">{children}</ErrorWrapper>
}
```
</PagesOnly>
### Recovering from errors
<AppOnly>
Use `retry()` to prompt the user to recover from the error. When called, the function re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result.
In most cases, use `retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors.
......@@ -151,6 +237,46 @@ function ErrorFallback(props, { error, retry, reset }) {
export default catchError(ErrorFallback)
```
</AppOnly>
<PagesOnly>
Use `reset()` to prompt the user to recover from the error. When called, the function clears the error state and re-renders the error boundary's children.
```tsx filename="components/custom-error-boundary.tsx" switcher
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: {}, { error, reset }: ErrorInfo) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
```jsx filename="components/custom-error-boundary.js" switcher
import { catchError } from 'next/error'
function ErrorFallback(props, { error, reset }) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)
```
</PagesOnly>
<AppOnly>
### Server-rendered error fallback
You can pass server-rendered content as a prop to display data-driven fallback UI. This works by rendering a Server Component as a `React.ReactNode` prop that the fallback displays when an error is caught.
......@@ -216,6 +342,14 @@ export default function Component({ children }) {
> - Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations.
> - You don't need to wrap `error.js` default exports with `catchError`. The [`error.js`](/docs/app/api-reference/file-conventions/error) file convention already renders inside a built-in error boundary provided by Next.js.
</AppOnly>
<PagesOnly>
> **Good to know**: Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations.
</PagesOnly>
## Version History
| Version | Changes |
......
......@@ -98,7 +98,7 @@ fetch(url, { signal })
## Troubleshooting
### Fetch default `auto no store` and `cache: 'no-store'` not showing fresh data in development
### Fetch default `auto no cache` and `cache: 'no-store'` not showing fresh data in development
Next.js caches `fetch` responses in Server Components across Hot Module Replacement (HMR) in local development for faster responses and to reduce costs for billed API calls.
......
......@@ -383,7 +383,6 @@ export const metadata = {
<meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" />
<meta name="format-detection" content="telephone=no, address=no, email=no" />
......@@ -422,6 +421,7 @@ export const metadata = {
> **Good to know**:
>
> - `metadataBase` is typically set in root `app/layout.js` to apply to URL-based `metadata` fields across all routes.
> - When `generateMetadata` uses `'use cache'`, its return value must be serializable. `URL` instances are not supported by Cache Functions, so values such as `metadataBase` should be returned as strings (for example, `url.toString()`). See [`use cache` serialization requirements](/docs/app/api-reference/directives/use-cache#serialization).
> - All URL-based `metadata` fields that require absolute URLs can be configured with a `metadataBase` option.
> - `metadataBase` can contain a subdomain e.g. `https://app.acme.com` or base path e.g. `https://acme.com/start/from/here`
> - If a `metadata` field provides an absolute URL, `metadataBase` will be ignored.
......@@ -924,6 +924,24 @@ export const metadata = {
<link rel="bookmarks" href="https://nextjs.org/13" />
```
### `pagination`
Describes the previous and next pages in a paginated sequence.
```jsx filename="layout.js | page.js"
export const metadata = {
pagination: {
previous: 'https://nextjs.org/blog?page=1',
next: 'https://nextjs.org/blog?page=3',
},
}
```
```html filename="<head> output" hideLineNumbers
<link rel="prev" href="https://nextjs.org/blog?page=1" />
<link rel="next" href="https://nextjs.org/blog?page=3" />
```
### `category`
```jsx filename="layout.js | page.js"
......@@ -1124,7 +1142,7 @@ The following metadata types do not currently have built-in support. However, th
| `<style>` | Learn more about [styling in Next.js](/docs/app/getting-started/css). |
| `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). |
| `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. |
| `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) |
| `<link rel="preload" />` | Use [ReactDOM preload method](#link-relpreload) |
| `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) |
| `<link rel="dns-prefetch" />` | Use [ReactDOM prefetchDNS method](#link-reldns-prefetch) |
......@@ -1422,5 +1440,5 @@ export const metadata = {
| Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `v15.2.0` | Introduced streaming support to `generateMetadata`. |
| `v13.2.0` | `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). |
| `v14.0.0` | `viewport`, `themeColor`, and `colorScheme` deprecated in favor of the [`viewport` configuration](/docs/app/api-reference/functions/generate-viewport). |
| `v13.2.0` | `metadata` and `generateMetadata` introduced. |
......@@ -54,7 +54,7 @@ export default async function Page({ params }) {
> **Good to know**:
>
> - You can use the [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config/dynamicParams) segment config option to control what happens when a dynamic segment is visited that was not generated with `generateStaticParams`.
> - You must return [an empty array from `generateStaticParams`](#all-paths-at-build-time) or utilize [`export const dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic) in order to revalidate (ISR) [paths at runtime](#all-paths-at-runtime).
> - You must return [an empty array from `generateStaticParams`](#all-paths-at-runtime) or utilize [`export const dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic) in order to revalidate (ISR) [paths at runtime](#all-paths-at-runtime).
> - During `next dev`, `generateStaticParams` will be called when you navigate to a route.
> - During `next build`, `generateStaticParams` runs before the corresponding Layouts or Pages are generated.
> - During revalidation (ISR), `generateStaticParams` will not be called again.
......
......@@ -46,7 +46,7 @@ Please refer to [Satori’s documentation](https://github.com/vercel/satori#css)
## Behavior
- `ImageResponse` uses [@vercel/og](https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG.
- `ImageResponse` uses [@vercel/og](https://vercel.com/docs/og-image-generation), [Satori](https://github.com/vercel/satori), and Resvg to convert HTML and CSS into PNG.
- Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. `display: grid`) will not work.
- Maximum bundle size of `500KB`. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime.
- Only `ttf`, `otf`, and `woff` font formats are supported. To maximize the font parsing speed, `ttf` or `otf` are preferred over `woff`.
......
......@@ -12,8 +12,6 @@ When used in a streaming context, this will insert a meta tag to emit the redire
If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead.
> **Good to know**: If you prefer to return a 307 (Temporary) HTTP redirect instead of 308 (Permanent), you can use the [`redirect` function](/docs/app/api-reference/functions/redirect) instead.
## Parameters
The `permanentRedirect` function accepts two arguments:
......@@ -45,6 +43,11 @@ The `type` parameter has no effect when used in Server Components.
`permanentRedirect` does not return a value.
## Behavior
- In Server Actions and Route Handlers, `permanentRedirect` should be called **outside** the `try` block when using `try/catch` statements because it throws an error.
- If you prefer to return a 307 (Temporary) HTTP redirect instead of 308 (Permanent), you can use the [`redirect` function](/docs/app/api-reference/functions/redirect) instead.
## Example
Invoking the `permanentRedirect()` function throws a `NEXT_REDIRECT` error and terminates rendering of the route segment in which it was thrown.
......
......@@ -8,7 +8,7 @@ related:
`revalidateTag` allows you to invalidate cached data on-demand for a specific cache tag.
This function is ideal for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. Users receive stale content while fresh data loads in the background.
This function is ideal for content where a slight delay in updates is acceptable, such as blog posts, product catalogs, or documentation. With the recommended `max` profile, users receive stale content while fresh data loads in the background.
## Usage
......@@ -18,13 +18,16 @@ This function is ideal for content where a slight delay in updates is acceptable
### Revalidation Behavior
The revalidation behavior depends on whether you provide the second argument:
Calling `revalidateTag` marks the tagged data as stale. The next request for that data kicks off a revalidation and is served stale content while it runs, using stale-while-revalidate semantics. The second argument sets how long stale content may be served. Past that, a request blocks until the revalidation completes.
- **With `profile="max"` (recommended)**: The tag entry is marked as stale, and the next time a resource with that tag is visited, it will use stale-while-revalidate semantics. This means the stale content is served while fresh content is fetched in the background.
- **With a custom cache life profile**: For advanced usage, you can specify any cache life profile that your application has defined, allowing for custom revalidation behaviors tailored to your specific caching requirements.
- **Without the second argument (deprecated)**: The tag entry is expired immediately, and the next request to that resource will be a blocking revalidate/cache miss. This behavior is now deprecated, and you should either use `profile="max"` or migrate to [`updateTag`](/docs/app/api-reference/functions/updateTag).
- **`profile="max"` (recommended)**: A one year window, long enough that requests are always served stale content while the revalidation runs.
- **Another profile, or an object**: Any other default or custom profile defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife), or an object with an `expire` property, when you want a different window.
- **`{ expire: 0 }`**: Stale content is never served, so the next request is a blocking revalidate/cache miss. Use it when the caller needs the data gone immediately and you cannot use [`updateTag`](/docs/app/api-reference/functions/updateTag).
- **No second argument (deprecated)**: Behaves like `{ expire: 0 }`. Migrate to [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions, or `profile="max"`.
> **Good to know**: When using `profile="max"`, `revalidateTag` marks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means calling `revalidateTag` will not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag is next visited.
The profile sets the point past which data correctness is more important than being fast.
> **Good to know**: A revalidation is triggered by a request, not by the `revalidateTag` call, so pages using the tag revalidate as they are visited rather than all at once.
## Parameters
......@@ -32,8 +35,8 @@ The revalidation behavior depends on whether you provide the second argument:
revalidateTag(tag: string, profile: string | { expire?: number }): void;
```
- `tag`: A string representing the cache tag associated with the data you want to revalidate. Must not exceed 256 characters. This value is case-sensitive.
- `profile`: A string that specifies the revalidation behavior. The recommended value is `"max"` which provides stale-while-revalidate semantics, or any of the other default or custom profiles defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife). Alternatively, you can pass an object with an `expire` property for custom expiration behavior.
- `tag`: A string representing the cache tag associated with the data you want to revalidate. Tags are case-sensitive and must not exceed 256 characters. A tag that exceeds the limit is never assigned to cached data, so revalidating it does nothing.
- `profile`: How long stale content may be served, see [Revalidation Behavior](#revalidation-behavior). The recommended value is `"max"`. Any other default or custom profile defined in [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife) is also accepted, and only its `expire` is read. You can also pass an object with an `expire` property, in seconds.
Tags must first be assigned to cached data. You can do this in two ways:
......@@ -136,4 +139,8 @@ export async function GET(request) {
}
```
> **Good to know**: For webhooks or third-party services that need immediate expiration, you can pass `{ expire: 0 }` as the second argument: `revalidateTag(tag, { expire: 0 })`. This pattern is necessary when external systems call your Route Handlers and require data to expire immediately. For all other cases, it's recommended to use [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions for immediate updates instead.
When the invalidation comes from outside a Server Action, for example a webhook or another service calling a Route Handler, [`updateTag`](/docs/app/api-reference/functions/updateTag) is not available. Pass `{ expire: 0 }` to expire the data immediately:
```ts
revalidateTag(tag, { expire: 0 })
```
......@@ -121,7 +121,7 @@ export async function createPost(formData) {
### Error when used outside Server Actions
```ts filename="app/api/posts/route.ts" switcher
import { updateTag } from 'next/cache'
import { revalidateTag, updateTag } from 'next/cache'
export async function POST() {
// This will throw an error
......
......@@ -40,10 +40,10 @@ export default function ExampleClientComponent() {
## Parameters
```tsx
const segment = useSelectedLayoutSegment(parallelRoutesKey?: string)
const segment = useSelectedLayoutSegment(parallelRouteKey?: string)
```
`useSelectedLayoutSegment` _optionally_ accepts a [`parallelRoutesKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
`useSelectedLayoutSegment` _optionally_ accepts a [`parallelRouteKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
## Returns
......
......@@ -52,10 +52,10 @@ export default function ExampleClientComponent() {
## Parameters
```tsx
const segments = useSelectedLayoutSegments(parallelRoutesKey?: string)
const segments = useSelectedLayoutSegments(parallelRouteKey?: string)
```
`useSelectedLayoutSegments` _optionally_ accepts a [`parallelRoutesKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
`useSelectedLayoutSegments` _optionally_ accepts a [`parallelRouteKey`](/docs/app/api-reference/file-conventions/parallel-routes#with-useselectedlayoutsegments), which allows you to read the active route segment within that slot.
## Returns
......
......@@ -8,14 +8,14 @@ description: Learn how to use the assetPrefix config option to configure your CD
<AppOnly>
> **Attention**: [Deploying to Vercel](/docs/app/getting-started/deploying) automatically configures a global CDN for your Next.js project.
> You do not need to manually setup an Asset Prefix.
> You do not need to manually set up an Asset Prefix.
</AppOnly>
<PagesOnly>
> **Attention**: [Deploying to Vercel](/docs/pages/getting-started/deploying) automatically configures a global CDN for your Next.js project.
> You do not need to manually setup an Asset Prefix.
> You do not need to manually set up an Asset Prefix.
</PagesOnly>
......
......@@ -471,7 +471,7 @@ For a full explanation of the tag architecture (including soft tags and multi-in
## Soft Tags
Soft tags are implicit tags that Next.js automatically generates based on the route path. For example, the route `/blog/hello` generates soft tags for `/`, `/blog`, `/blog/hello`, and their corresponding layout entries. These tags are prefixed internally with `_N_T_`.
Soft tags are implicit tags that Next.js automatically generates based on the route path. Every segment in the path gets a layout tag, plus the leaf route itself. For example, the route `/blog/hello` generates soft tags for `/layout`, `/blog/layout`, `/blog/hello/layout`, and `/blog/hello`. These tags are prefixed internally with `_N_T_`.
Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based cache system. When `revalidatePath('/blog/hello')` is called, it invalidates all cache entries associated with that path's soft tags.
......
......@@ -54,7 +54,8 @@ import { cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
```
......@@ -65,7 +66,8 @@ import { cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return data
}
```
......
---
title: cacheMaxMemorySize
description: Configure the size of the in-memory cache that Next.js keeps in each server instance.
---
{/* 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. */}
`cacheMaxMemorySize` sets the size, in bytes, of the in-memory cache each Next.js server instance keeps. It defaults to 50 MB.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheMaxMemorySize: 50 * 1024 * 1024, // 50 MB, the default
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheMaxMemorySize: 50 * 1024 * 1024, // 50 MB, the default
}
module.exports = nextConfig
```
The option sizes two separate caches:
- The server cache that stores prerendered pages, route handler responses, and optimized images. Set this to `0` when adopting a [custom `cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath), so reads go to your store rather than a per-instance copy.
- The built-in handler behind [`'use cache'`](/docs/app/api-reference/directives/use-cache). If you register your own handler through [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers), that handler manages its own memory and this option no longer applies to it.
Setting `cacheMaxMemorySize: 0` disables both in-memory caches. It is also a way to mimic how `use cache` behaves in a serverless environment, where entries rarely survive between requests.
> **Good to know**: `next dev` keeps its own in-memory cache regardless of this option, so reloads stay fast. Production honors the configured value exactly.
......@@ -68,12 +68,15 @@ module.exports = {
}
```
A per-deployment value only avoids skew if requests are also routed by deployment. Next.js does not route on `?dpl=`, so that routing comes from your host or CDN. Without it, clients that reach an instance from another deployment during a rollout will reload rather than navigate.
## Version History
| Version | Changes |
| ---------- | ----------------------------------------------------- |
| `v14.1.4` | `deploymentId` stabilized as top-level config option. |
| `v13.4.10` | `experimental.deploymentId` introduced. |
| Version | Changes |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `v16.2.0` | Pages Router detects version skew from the response header rather than the build ID, and the build ID is constant when `deploymentId` is set. |
| `v14.1.4` | `deploymentId` stabilized as top-level config option. |
| `v13.4.10` | `experimental.deploymentId` introduced. |
## Related
......
......@@ -17,3 +17,5 @@ module.exports = {
},
}
```
> **Good to know:** When [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) is set, Next.js uses a constant build ID and `generateBuildId` has no effect. [Version skew](/docs/app/guides/self-hosting#version-skew) is detected from the deployment ID instead.
......@@ -156,8 +156,8 @@ export default function gumletLoader({ src, width, quality }) {
// Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives
export default function imageengineLoader({ src, width, quality }) {
const compression = 100 - (quality || 50)
const params = [`w_${width}`, `cmpr_${compression}`)]
return `https://example.com${src}?imgeng=/${params.join('/')`
const params = [`w_${width}`, `cmpr_${compression}`]
return `https://example.com${src}?imgeng=/${params.join('/')}`
}
```
......
......@@ -6,7 +6,7 @@ description: Configure the Next.js cache used for storing and revalidating data
You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application.
> **Good to know**: The `cacheHandler` (singular) configuration is specifically used by Next.js for server cache operations such as storing and revalidating ISR, route handler responses, and optimized images. It is **not** used by `'use cache'` directives. For `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers) (plural) instead.
> **Good to know**: The `cacheHandler` (singular) configuration is specifically used by Next.js for server cache operations such as storing and revalidating ISR, route handler responses, and optimized images. It is **not** used by `'use cache'` directives. For `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers) (plural) instead. [`cacheMaxMemorySize`](/docs/app/api-reference/config/next-config-js/cacheMaxMemorySize) is separate from both, and sizes the in-memory cache for each.
```js filename="next.config.js"
module.exports = {
......
......@@ -8,10 +8,10 @@ related:
- app/api-reference/config/next-config-js/cacheComponents
- app/api-reference/file-conventions/route-segment-config/prefetch
- app/api-reference/components/link
- app/guides/runtime-prefetching
- app/guides/optimizing-prefetching
---
`partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; opt individual routes into [runtime prefetching](/docs/app/guides/runtime-prefetching) to fetch more.
`partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; set `prefetch={true}` on individual links to use [per-link prefetching](/docs/app/guides/optimizing-prefetching) and fetch more.
## Usage
......@@ -46,13 +46,13 @@ module.exports = {
Before Partial Prefetching, Next.js prefetched per visible link: a page with N links to N routes produced ~N route prefetches as those links entered the viewport.
With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The shell carries the route's rendered output minus per-link data; specifics like params and search-bound data fill in after navigation. Shells are cached on the client, so a route is fetched once even if many links on the page point at it.
With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The App Shell contains rendered output that does not depend on a link's URL. URL-specific content, including content that depends on `params` or `searchParams`, resolves after navigation by default. App Shells are cached on the client, so links to the same route reuse one prefetch.
The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it.
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client.
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching).
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves URL data like `params`, `searchParams`, and the full URL, and the cached content behind it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
> **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail.
......
......@@ -29,7 +29,7 @@ const nextConfig = {
},
}
export default nextConfig
module.exports = nextConfig
```
## Config Options
......
......@@ -63,7 +63,7 @@ In this case, the `getUserDetails` function returns data about a given user. We
```ts switcher
import { experimental_taintObjectReference } from 'react'
function getUserDetails(id: string): UserDetails {
async function getUserDetails(id: string): Promise<UserDetails> {
const user = await db.queryUserById(id)
experimental_taintObjectReference(
......@@ -78,7 +78,7 @@ function getUserDetails(id: string): UserDetails {
```js switcher
import { experimental_taintObjectReference } from 'react'
function getUserDetails(id) {
async function getUserDetails(id) {
const user = await db.queryUserById(id)
experimental_taintObjectReference(
......@@ -151,15 +151,15 @@ export async function ContactPage({ params }) {
### Tainting a unique value
In this case, we can access the server configuration by awaiting calls to `config.getConfigDetails`. However, the system configuration contains the `SERVICE_API_KEY` that we don't want to expose to clients.
In this case, we can access the server configuration by awaiting calls to `configService.getConfigDetails`. However, the system configuration contains the `SERVICE_API_KEY` that we don't want to expose to clients.
We can taint the `config.SERVICE_API_KEY` value.
```ts switcher
import { experimental_taintUniqueValue } from 'react'
function getSystemConfig(): SystemConfig {
const config = await config.getConfigDetails()
async function getSystemConfig(): Promise<SystemConfig> {
const config = await configService.getConfigDetails()
experimental_taintUniqueValue(
'Do not pass configuration tokens to the client',
......@@ -174,8 +174,8 @@ function getSystemConfig(): SystemConfig {
```js switcher
import { experimental_taintUniqueValue } from 'react'
function getSystemConfig() {
const config = await config.getConfigDetails()
async function getSystemConfig() {
const config = await configService.getConfigDetails()
experimental_taintUniqueValue(
'Do not pass configuration tokens to the client',
......
......@@ -7,7 +7,7 @@ description: Configure Next.js with Turbopack-specific options
The `turbopack` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved.
> **Good to know**: The `turbopack` option was previously named `experimental.turbo` in Next.js versions 13.0.0 to 15.2.x. The `experimental.turbo` option will be removed in Next.js 16.
> **Good to know**: The `turbopack` option was previously named `experimental.turbo` in Next.js versions 13.0.0 to 15.2.x, an option which still works as an alias, but new configuration should use the top-level `turbopack` option.
>
> If you are using an older version of Next.js, run `npx @next/codemod@latest next-experimental-turbo-to-turbopack .` to automatically migrate your configuration.
......
......@@ -4,13 +4,29 @@ description: Configure how Turbopack splits your client-side JavaScript into chu
version: experimental
---
{/* 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. */}
<AppOnly>
`experimental.turbopackChunking` lets you configure Turbopack's production JavaScript
chunker. These options allow you to change the assumptions the chunker makes about user
behaviour, tweak the raw size thresholds it uses, and enable the experimental component
behavior, tweak the raw size thresholds it uses, and enable the experimental component
chunks feature.
</AppOnly>
<PagesOnly>
`experimental.turbopackChunking` lets you configure Turbopack's production JavaScript
chunker. These options allow you to change the assumptions the chunker makes about user
behavior and tweak the raw size thresholds it uses.
</PagesOnly>
By default, Turbopack's chunking is configured as follows:
<AppOnly>
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
......@@ -46,6 +62,43 @@ const nextConfig = {
module.exports = nextConfig
```
</AppOnly>
<PagesOnly>
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig = {
experimental: {
turbopackChunking: {
minChunkSize: 50000,
maxChunkCountPerGroup: 40,
maxMergeChunkSize: 200000,
},
},
} satisfies NextConfig
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbopackChunking: {
minChunkSize: 50000,
maxChunkCountPerGroup: 40,
maxMergeChunkSize: 200000,
},
},
}
module.exports = nextConfig
```
</PagesOnly>
## Size Thresholds
The following options control how aggressively Turbopack merges chunks and how large a chunk is
......@@ -69,6 +122,8 @@ When merging chunks, the trade-off being made is an improvement to performance o
loads at the cost of navigation performance. This is because each additional network request
being made is costly, however, smaller chunks are more likely to be re-usable across pages.
<AppOnly>
## Component Chunks
Producing component chunks is an experimental feature that aims to give you the initial
......@@ -86,6 +141,8 @@ This avoids re-downloading JavaScript the browser already has when navigating.
this size are folded into a single component instead of being emitted on their own,
to avoid producing many tiny chunks.
</AppOnly>
## Heuristics
These change the assumptions the chunker makes when weighing whether merging two
......
......@@ -282,6 +282,7 @@ export function proxy(request: NextRequest) {
```tsx filename="app/some/page.tsx"
import type { Route } from 'next'
import Link from 'next/link'
export default function Page() {
return <Link href={'/proxy-redirect' as Route}>Link Text</Link>
......
......@@ -139,7 +139,7 @@ const eslintConfig = defineConfig([
{
files: ['**/*.{js,jsx,ts,tsx}'],
plugins: {
next: eslintNextPlugin,
'@next/next': eslintNextPlugin,
},
settings: {
next: {
......
......@@ -142,7 +142,7 @@ You can view a list of all available examples along with setup instructions in t
### With any public GitHub example
To create a new app using any public GitHub example, use the `--example` option with the GitHub repo's URL. For example:
To create a new app using any public GitHub example, use the `--example` option with the GitHub repository's URL. For example:
```bash package="pnpm"
pnpm create next-app --example "https://github.com/.../" [your-project-name]
......
......@@ -48,6 +48,7 @@ export interface NextAdapter {
onBuildComplete?: (ctx: {
routing: {
beforeMiddleware: Array<Route>
middlewareMatchers: Array<Route>
beforeFiles: Array<Route>
afterFiles: Array<Route>
dynamicRoutes: Array<Route>
......
......@@ -24,6 +24,7 @@ Called after the build process completes with detailed information about routes
- `context.routing`: Object containing Next.js routing phases and metadata
- `routing.beforeMiddleware`: Routes executed before middleware (includes header and redirect handling)
- `routing.middlewareMatchers`: Middleware matcher definitions for this build, used to decide whether middleware should be invoked for a given request
- `routing.beforeFiles`: Rewrite routes checked before filesystem route matching
- `routing.afterFiles`: Rewrite routes checked after filesystem route matching
- `routing.dynamicRoutes`: Dynamic route matching table
......
......@@ -30,6 +30,7 @@ React pages from the `pages/` directory:
sourcePage: string // Original source file path in pages/ directory
runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
......@@ -57,6 +58,7 @@ API routes from `pages/api/`:
sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
......@@ -84,6 +86,7 @@ React pages from the `app/` directory:
sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
......@@ -111,6 +114,7 @@ API and metadata routes from the `app/` directory:
sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
......@@ -218,6 +222,7 @@ See [Supporting immutable static assets](/docs/app/api-reference/adapters/immuta
sourcePage: string // Always 'middleware'
runtime: 'nodejs' | 'edge' // Runtime the route is built for
assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
assetsHashes: Record<string, string> // Content hashes of each `assets` entry (key: same as `assets`, value: content hash)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
edgeRuntime?: {
modulePath: string // Absolute path to the module registered in the edge runtime
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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