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

Unify caching story across the docs (#90149)

This PRs unifies the caching story across the docs, making Cache
Components the happy path, while still providing guidance to users in
the old model. However, instead of explaining the old model and its
caching layers, we've created a new guide focusing on what APIs to use
and when.

This follow-up PR aligns terminology across the docs:
https://github.com/vercel/next.js/pull/90589

## IA updates

Getting Started section: 

- Improves Getting Started progression:
- **Before:** CC → Fetching Data → Updating Data → Caching and
Revalidating (old and new model mixed)
- **After:** Fetching Data (Dynamic) → Mutating Data (Dynamic) → Caching
with CC (Prerendering) → Revalidating with CC.
- New: `caching.mdx` (CC-first)
   - Structure: 
      - Enabling Cache Components
      - Data vs UI-level caching
      - Working with request time APIs
      - Passing request values to cached functions
      - Working with non-deterministic operations
      - Working with synchronous operations
      - How rendering works (PPR and static shell story)
- New: `revalidating.mdx` (CC-first)
   - Explains how to use `cacheLife` and `cacheTag`

Guides Section: 

- New: `caching-and-revalidating.mdx` (Previous Model)
- For users who are not using CC, includes `fetch` options and route
segment config
- Moves route segment config options that don't apply to CC from API
reference to this guide (for easy archiving in the future).
- New: `migrating-to-cache-components.mdx` (WIP)
- Del: `caching.mdx` 😌 

## Terminology

We should remove caching layers from the docs. Users only needed to be
exposed to them when they were configured independently, but the new CC
APIs work across layers.

To make it easier to review this PR, I'm consolidating terminology and
fixing broken links in a new PR:
https://github.com/vercel/next.js/pull/90589

---------
Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarJoseph <joseph.chamochumbi@vercel.com>
parent ce14ca88
...@@ -269,11 +269,11 @@ export default async function Page({ searchParams }) { ...@@ -269,11 +269,11 @@ export default async function Page({ searchParams }) {
} }
``` ```
Using `searchParams` opts your page into [**dynamic rendering**](/docs/app/guides/caching#dynamic-rendering) because it requires an incoming request to read the search parameters from. Using `searchParams` opts your page into [**dynamic rendering**](/docs/app/glossary#dynamic-rendering) because it requires an incoming request to read the search parameters from.
Client Components can read search params using the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook. Client Components can read search params using the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook.
Learn more about `useSearchParams` in [statically rendered](/docs/app/api-reference/functions/use-search-params#static-rendering) and [dynamically rendered](/docs/app/api-reference/functions/use-search-params#dynamic-rendering) routes. Learn more about `useSearchParams` in [prerendered](/docs/app/api-reference/functions/use-search-params#prerendering) and [dynamically rendered](/docs/app/api-reference/functions/use-search-params#dynamic-rendering) routes.
### What to use and when ### What to use and when
......
...@@ -27,7 +27,7 @@ In Next.js, [Layouts and Pages](/docs/app/getting-started/layouts-and-pages) are ...@@ -27,7 +27,7 @@ In Next.js, [Layouts and Pages](/docs/app/getting-started/layouts-and-pages) are
There are two types of server rendering, based on _when_ it happens: There are two types of server rendering, based on _when_ it happens:
- **Static Rendering (or Prerendering)** happens at build time or during [revalidation](/docs/app/getting-started/caching-and-revalidating) and the result is cached. - **Prerendering** happens at build time or during [revalidation](/docs/app/getting-started/revalidating) and the result is cached.
- **Dynamic Rendering** happens at request time in response to a client request. - **Dynamic Rendering** happens at request time in response to a client request.
The trade-off of server rendering is that the client must wait for the server to respond before the new route can be shown. Next.js addresses this delay by [prefetching](#prefetching) routes the user is likely to visit and performing [client-side transitions](#client-side-transitions). The trade-off of server rendering is that the client must wait for the server to respond before the new route can be shown. Next.js addresses this delay by [prefetching](#prefetching) routes the user is likely to visit and performing [client-side transitions](#client-side-transitions).
......
...@@ -102,7 +102,7 @@ export default function LikeButton({ likes }) { ...@@ -102,7 +102,7 @@ export default function LikeButton({ likes }) {
On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks, by individual route segments ([layouts and pages](/docs/app/getting-started/layouts-and-pages)): On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks, by individual route segments ([layouts and pages](/docs/app/getting-started/layouts-and-pages)):
- **Server Components** are rendered into a special data format called the React Server Component Payload (RSC Payload). - **Server Components** are rendered into a special data format called the React Server Component Payload (RSC Payload).
- **Client Components** and the RSC Payload are used to [pre-render](/docs/app/guides/caching#rendering-strategies) HTML. - **Client Components** and the RSC Payload are used to [prerender](/docs/app/glossary#prerendering) HTML.
> **What is the React Server Component Payload (RSC)?** > **What is the React Server Component Payload (RSC)?**
> >
...@@ -412,191 +412,6 @@ Your Server Component will now be able to directly render your provider, and all ...@@ -412,191 +412,6 @@ Your Server Component will now be able to directly render your provider, and all
> **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components. > **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components.
### Sharing data with context and React.cache
You can share fetched data across both Server and Client Components by combining [`React.cache`](https://react.dev/reference/react/cache) with context providers.
Create a cached function that fetches data:
```ts filename="app/lib/user.ts" switcher
import { cache } from 'react'
export const getUser = cache(async () => {
const res = await fetch('https://api.example.com/user')
return res.json()
})
```
```js filename="app/lib/user.js" switcher
import { cache } from 'react'
export const getUser = cache(async () => {
const res = await fetch('https://api.example.com/user')
return res.json()
})
```
Create a context provider that stores the promise:
```tsx filename="app/user-provider.tsx" switcher
'use client'
import { createContext } from 'react'
type User = {
id: string
name: string
}
export const UserContext = createContext<Promise<User> | null>(null)
export default function UserProvider({
children,
userPromise,
}: {
children: React.ReactNode
userPromise: Promise<User>
}) {
return <UserContext value={userPromise}>{children}</UserContext>
}
```
```jsx filename="app/user-provider.js" switcher
'use client'
import { createContext } from 'react'
export const UserContext = createContext(null)
export default function UserProvider({ children, userPromise }) {
return <UserContext value={userPromise}>{children}</UserContext>
}
```
In a layout, pass the promise to the provider without awaiting:
```tsx filename="app/layout.tsx" switcher
import UserProvider from './user-provider'
import { getUser } from './lib/user'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const userPromise = getUser() // Don't await
return (
<html>
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}
```
```jsx filename="app/layout.js" switcher
import UserProvider from './user-provider'
import { getUser } from './lib/user'
export default function RootLayout({ children }) {
const userPromise = getUser() // Don't await
return (
<html>
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}
```
Client Components use [`use()`](https://react.dev/reference/react/use) to resolve the promise from context, wrapped in `<Suspense>` for fallback UI:
```tsx filename="app/ui/profile.tsx" switcher
'use client'
import { use, useContext } from 'react'
import { UserContext } from '../user-provider'
export function Profile() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useContext must be used within a UserProvider')
}
const user = use(userPromise)
return <p>Welcome, {user.name}</p>
}
```
```jsx filename="app/ui/profile.js" switcher
'use client'
import { use, useContext } from 'react'
import { UserContext } from '../user-provider'
export function Profile() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useContext must be used within a UserProvider')
}
const user = use(userPromise)
return <p>Welcome, {user.name}</p>
}
```
```tsx filename="app/page.tsx" switcher
import { Suspense } from 'react'
import { Profile } from './ui/profile'
export default function Page() {
return (
<Suspense fallback={<div>Loading profile...</div>}>
<Profile />
</Suspense>
)
}
```
```jsx filename="app/page.js" switcher
import { Suspense } from 'react'
import { Profile } from './ui/profile'
export default function Page() {
return (
<Suspense fallback={<div>Loading profile...</div>}>
<Profile />
</Suspense>
)
}
```
Server Components can also call `getUser()` directly:
```tsx filename="app/dashboard/page.tsx" switcher
import { getUser } from '../lib/user'
export default async function DashboardPage() {
const user = await getUser() // Cached - same request, no duplicate fetch
return <h1>Dashboard for {user.name}</h1>
}
```
```jsx filename="app/dashboard/page.js" switcher
import { getUser } from '../lib/user'
export default async function DashboardPage() {
const user = await getUser() // Cached - same request, no duplicate fetch
return <h1>Dashboard for {user.name}</h1>
}
```
Since `getUser` is wrapped with `React.cache`, multiple calls within the same request return the same memoized result, whether called directly in Server Components or resolved via context in Client Components.
> **Good to know**: `React.cache` is scoped to the current request only. Each request gets its own memoization scope with no sharing between requests.
### Third-party components ### Third-party components
When using a third-party component that relies on client-only features, you can wrap it in a Client Component to ensure it works as expected. When using a third-party component that relies on client-only features, you can wrap it in a Client Component to ensure it works as expected.
......
This diff is collapsed.
--- ---
title: Updating Data title: Mutating Data
description: Learn how to mutate data using Server Functions and Server Actions in Next.js. description: Learn how to mutate data using Server Functions and Server Actions in Next.js.
related: related:
title: API Reference title: API Reference
...@@ -10,25 +10,25 @@ related: ...@@ -10,25 +10,25 @@ related:
- app/api-reference/functions/redirect - app/api-reference/functions/redirect
--- ---
You can update data in Next.js using React's [Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions. You can mutate data in Next.js using [React Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions.
## What are Server Functions? ## What are Server Functions?
A **Server Function** is an asynchronous function that runs on the server. They can be called from the client through a network request, which is why they must be asynchronous. A **Server Function** is an asynchronous function that runs on the server. You can call them from the client through a network request, which is why they must be asynchronous.
In an `action` or mutation context, they are also called **Server Actions**. In an `action` or mutation context, they are also called **Server Actions**.
> **Good to know:** A Server Action is a Server Function used in a specific way (for handling form submissions and mutations). Server Function is the broader term.
By convention, a Server Action is an async function used with [`startTransition`](https://react.dev/reference/react/startTransition). This happens automatically when the function is: By convention, a Server Action is an async function used with [`startTransition`](https://react.dev/reference/react/startTransition). This happens automatically when the function is:
- Passed to a `<form>` using the `action` prop. - Passed to a `<form>` using the `action` prop.
- Passed to a `<button>` using the `formAction` prop. - Passed to a `<button>` using the `formAction` prop.
In Next.js, Server Actions integrate with the framework's [caching](/docs/app/guides/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip.
Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them. Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them.
> **Good to know:** A Server Action is a Server Function used in a specific way (for handling form submissions and mutations). Server Function is the broader term.
## Creating Server Functions ## Creating Server Functions
A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file. A Server Function can be defined by using the [`use server`](https://react.dev/reference/rsc/use-server) directive. You can place the directive at the top of an **asynchronous** function to mark the function as a Server Function, or at the top of a separate file to mark all exports of that file.
...@@ -39,7 +39,7 @@ export async function createPost(formData: FormData) { ...@@ -39,7 +39,7 @@ export async function createPost(formData: FormData) {
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
...@@ -47,7 +47,7 @@ export async function deletePost(formData: FormData) { ...@@ -47,7 +47,7 @@ export async function deletePost(formData: FormData) {
'use server' 'use server'
const id = formData.get('id') const id = formData.get('id')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
``` ```
...@@ -58,7 +58,7 @@ export async function createPost(formData) { ...@@ -58,7 +58,7 @@ export async function createPost(formData) {
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
...@@ -66,7 +66,7 @@ export async function deletePost(formData) { ...@@ -66,7 +66,7 @@ export async function deletePost(formData) {
'use server' 'use server'
const id = formData.get('id') const id = formData.get('id')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
``` ```
...@@ -90,7 +90,7 @@ export default function Page() { ...@@ -90,7 +90,7 @@ export default function Page() {
```jsx filename="app/page.js" switcher ```jsx filename="app/page.js" switcher
export default function Page() { export default function Page() {
// Server Action // Server Action
async function createPost(formData: FormData) { async function createPost(formData) {
'use server' 'use server'
// ... // ...
} }
...@@ -217,7 +217,7 @@ export async function createPost(formData: FormData) { ...@@ -217,7 +217,7 @@ export async function createPost(formData: FormData) {
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
``` ```
...@@ -229,7 +229,7 @@ export async function createPost(formData) { ...@@ -229,7 +229,7 @@ export async function createPost(formData) {
const title = formData.get('title') const title = formData.get('title')
const content = formData.get('content') const content = formData.get('content')
// Update data // Mutate data
// Revalidate cache // Revalidate cache
} }
``` ```
...@@ -330,7 +330,7 @@ export function Button() { ...@@ -330,7 +330,7 @@ export function Button() {
} }
``` ```
### Refreshing ### Refresh data
After a mutation, you may want to refresh the current page to show the latest data. You can do this by calling [`refresh`](/docs/app/api-reference/functions/refresh) from `next/cache` in a Server Action: After a mutation, you may want to refresh the current page to show the latest data. You can do this by calling [`refresh`](/docs/app/api-reference/functions/refresh) from `next/cache` in a Server Action:
...@@ -340,7 +340,7 @@ After a mutation, you may want to refresh the current page to show the latest da ...@@ -340,7 +340,7 @@ After a mutation, you may want to refresh the current page to show the latest da
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
export async function updatePost(formData: FormData) { export async function updatePost(formData: FormData) {
// Update data // Mutate data
// ... // ...
refresh() refresh()
...@@ -353,7 +353,7 @@ export async function updatePost(formData: FormData) { ...@@ -353,7 +353,7 @@ export async function updatePost(formData: FormData) {
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
export async function updatePost(formData) { export async function updatePost(formData) {
// Update data // Mutate data
// ... // ...
refresh() refresh()
...@@ -362,16 +362,16 @@ export async function updatePost(formData) { ...@@ -362,16 +362,16 @@ export async function updatePost(formData) {
This refreshes the client router, ensuring the UI reflects the latest state. The `refresh()` function does not revalidate tagged data. To revalidate tagged data, use [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead. This refreshes the client router, ensuring the UI reflects the latest state. The `refresh()` function does not revalidate tagged data. To revalidate tagged data, use [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead.
### Revalidating ### Revalidate data
After performing an update, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function: After performing a mutation, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function:
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
'use server' 'use server'
// Update data // Mutate data
// ... // ...
revalidatePath('/posts') revalidatePath('/posts')
...@@ -383,15 +383,15 @@ import { revalidatePath } from 'next/cache' ...@@ -383,15 +383,15 @@ import { revalidatePath } from 'next/cache'
export async function createPost(formData) { export async function createPost(formData) {
'use server' 'use server'
// Update data // Mutate data
// ... // ...
revalidatePath('/posts') revalidatePath('/posts')
} }
``` ```
### Redirecting ### Redirect after a mutation
You may want to redirect the user to a different page after performing an update. You can do this by calling [`redirect`](/docs/app/api-reference/functions/redirect) within the Server Function. You may want to redirect the user to a different page after a mutation. You can do this by calling [`redirect`](/docs/app/api-reference/functions/redirect) within the Server Function.
```ts filename="app/lib/actions.ts" switcher ```ts filename="app/lib/actions.ts" switcher
'use server' 'use server'
...@@ -400,7 +400,7 @@ import { revalidatePath } from 'next/cache' ...@@ -400,7 +400,7 @@ import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
// Update data // Mutate data
// ... // ...
revalidatePath('/posts') revalidatePath('/posts')
...@@ -415,7 +415,7 @@ import { revalidatePath } from 'next/cache' ...@@ -415,7 +415,7 @@ import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
// Update data // Mutate data
// ... // ...
revalidatePath('/posts') revalidatePath('/posts')
......
This diff is collapsed.
---
title: Revalidating
description: Learn how to revalidate cached data using time-based and on-demand strategies.
related:
title: API Reference
description: Learn more about the APIs mentioned on this page.
links:
- app/api-reference/functions/cacheLife
- app/api-reference/functions/cacheTag
- app/api-reference/functions/revalidateTag
- app/api-reference/functions/updateTag
- app/api-reference/functions/revalidatePath
---
> This page covers revalidation with [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), enabled by setting [`cacheComponents: true`](/docs/app/api-reference/config/next-config-js/cacheComponents) in your `next.config.ts` file. If you're not using Cache Components, see the [Caching and Revalidating (Previous Model)](/docs/app/guides/caching-without-cache-components) guide.
Revalidation is the process of updating cached data. It lets you keep serving fast, cached responses while ensuring content stays fresh. There are two strategies:
- **Time-based revalidation**: Automatically refresh cached data after a set duration using [`cacheLife`](#cachelife).
- **On-demand revalidation**: Manually invalidate cached data after a mutation using [`revalidateTag`](#revalidatetag), [`updateTag`](#updatetag), or [`revalidatePath`](#revalidatepath).
## `cacheLife`
[`cacheLife`](/docs/app/api-reference/functions/cacheLife) controls how long cached data remains valid. Use it inside a [`use cache`](/docs/app/api-reference/directives/use-cache) scope to set the cache lifetime.
```tsx filename="app/lib/data.ts" highlight={1,4,5}
import { cacheLife } from 'next/cache'
export async function getProducts() {
'use cache'
cacheLife('hours')
return db.query('SELECT * FROM products')
}
```
`cacheLife` accepts a profile name or a custom configuration object:
| Profile | `stale` | `revalidate` | `expire` |
| --------- | ------- | ------------ | ----------- |
| `seconds` | 0 | 1s | 60s |
| `minutes` | 5m | 1m | 1h |
| `hours` | 5m | 1h | 1d |
| `days` | 5m | 1d | 1w |
| `weeks` | 5m | 1w | 30d |
| `max` | 5m | 30d | ~indefinite |
For fine-grained control, pass an object:
```tsx highlight={2-6}
'use cache'
cacheLife({
stale: 3600, // 1 hour until considered stale
revalidate: 7200, // 2 hours until revalidated
expire: 86400, // 1 day until expired
})
```
> **Good to know:** A cache is considered "short-lived" when it uses the `seconds` profile, `revalidate: 0`, or `expire` under 5 minutes. Short-lived caches are automatically excluded from prerenders and become dynamic holes instead. See [Prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details.
See the [`cacheLife` API reference](/docs/app/api-reference/functions/cacheLife) for all profiles and custom configuration options.
## `cacheTag`
[`cacheTag`](/docs/app/api-reference/functions/cacheTag) lets you tag cached data so it can be invalidated on-demand. Use it inside a [`use cache`](/docs/app/api-reference/directives/use-cache) scope:
```tsx filename="app/lib/data.ts" switcher
import { cacheTag } from 'next/cache'
export async function getProducts() {
'use cache'
cacheTag('products')
return db.query('SELECT * FROM products')
}
```
```jsx filename="app/lib/data.js" switcher
import { cacheTag } from 'next/cache'
export async function getProducts() {
'use cache'
cacheTag('products')
return db.query('SELECT * FROM products')
}
```
Once tagged, invalidate the cache using [`revalidateTag`](#revalidatetag) or [`updateTag`](#updatetag).
See the [`cacheTag` API reference](/docs/app/api-reference/functions/cacheTag) to learn more.
## `revalidateTag`
`revalidateTag` invalidates cache entries by tag using stale-while-revalidate semantics — stale content is served immediately while fresh content loads in the background. This is ideal for content where a slight delay in updates is acceptable, like blog posts or product catalogs.
```tsx filename="app/lib/actions.ts" highlight={1,5} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id: string) {
// Mutate data
revalidateTag('user', 'max') // Recommended: stale-while-revalidate
}
```
```jsx filename="app/lib/actions.js" highlight={1,5} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id) {
// Mutate data
revalidateTag('user', 'max') // Recommended: stale-while-revalidate
}
```
You can reuse the same tag in multiple functions to revalidate them all at once. Call `revalidateTag` in a [Server Action](/docs/app/getting-started/mutating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
> **Good to know:** The second argument sets how long stale content can be served while fresh content generates in the background. Once it expires, subsequent requests block until fresh content is ready. Using `'max'` gives the longest stale window.
See the [`revalidateTag` API reference](/docs/app/api-reference/functions/revalidateTag) to learn more.
## `updateTag`
`updateTag` immediately expires cached data for read-your-own-writes scenarios — the user sees their change right away instead of stale content. Unlike `revalidateTag`, it can only be used in [Server Actions](/docs/app/getting-started/mutating-data).
```tsx filename="app/lib/actions.ts" highlight={1,6} switcher
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const post = await db.post.create({
data: {
title: formData.get('title'),
content: formData.get('content'),
},
})
updateTag('posts')
redirect(`/posts/${post.id}`)
}
```
```jsx filename="app/lib/actions.js" highlight={1,6} switcher
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
const post = await db.post.create({
data: {
title: formData.get('title'),
content: formData.get('content'),
},
})
updateTag('posts')
redirect(`/posts/${post.id}`)
}
```
| | `updateTag` | `revalidateTag` |
| ------------ | --------------------------------------------- | ------------------------------------ |
| **Where** | Server Actions only | Server Actions and Route Handlers |
| **Behavior** | Immediately expires cache | Stale-while-revalidate |
| **Use case** | Read-your-own-writes (user sees their change) | Background refresh (slight delay OK) |
See the [`updateTag` API reference](/docs/app/api-reference/functions/updateTag) to learn more.
## `revalidatePath`
`revalidatePath` invalidates all cached data for a specific route path. Use it when you want to revalidate a route without knowing which tags are associated with it.
```tsx filename="app/lib/actions.ts" highlight={1,5} switcher
import { revalidatePath } from 'next/cache'
export async function updateUser(id: string) {
// Mutate data
revalidatePath('/profile')
}
```
```jsx filename="app/lib/actions.js" highlight={1,5} switcher
import { revalidatePath } from 'next/cache'
export async function updateUser(id) {
// Mutate data
revalidatePath('/profile')
}
```
> **Good to know**: Prefer tag-based revalidation (`revalidateTag`/`updateTag`) over path-based when possible — it's more precise and avoids over-invalidating.
See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) to learn more.
## What should I cache?
Cache data that doesn't depend on [runtime data](/docs/app/getting-started/caching#working-with-runtime-apis) and that you're OK serving from cache for a period of time. Use `use cache` with `cacheLife` to describe that behavior.
For content management systems with update mechanisms, use tags with longer cache durations and rely on `revalidateTag` to refresh content when it actually changes, rather than expiring the cache preemptively.
...@@ -126,7 +126,7 @@ Streaming metadata is **disabled for bots and crawlers** that expect metadata to ...@@ -126,7 +126,7 @@ Streaming metadata is **disabled for bots and crawlers** that expect metadata to
You can customize or **disable** streaming metadata completely, with the [`htmlLimitedBots`](/docs/app/api-reference/config/next-config-js/htmlLimitedBots#disabling) option in your Next.js config file. You can customize or **disable** streaming metadata completely, with the [`htmlLimitedBots`](/docs/app/api-reference/config/next-config-js/htmlLimitedBots#disabling) option in your Next.js config file.
Statically rendered pages don’t use streaming since metadata is resolved at build time. Prerendered pages don’t use streaming since metadata is resolved at build time.
Learn more about [streaming metadata](/docs/app/api-reference/functions/generate-metadata#streaming-metadata). Learn more about [streaming metadata](/docs/app/api-reference/functions/generate-metadata#streaming-metadata).
......
...@@ -48,7 +48,7 @@ In addition to supporting the native [Request](https://developer.mozilla.org/doc ...@@ -48,7 +48,7 @@ In addition to supporting the native [Request](https://developer.mozilla.org/doc
### Caching ### Caching
Route Handlers are not cached by default. You can, however, opt into caching for `GET` methods. Other supported HTTP methods are **not** cached. To cache a `GET` method, use a [route config option](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) such as `export const dynamic = 'force-static'` in your Route Handler file. Route Handlers are not cached by default. You can, however, opt into caching for `GET` methods. Other supported HTTP methods are **not** cached. To cache a `GET` method, use a [route config option](/docs/app/guides/caching-without-cache-components#dynamic) such as `export const dynamic = 'force-static'` in your Route Handler file.
```ts filename="app/items/route.ts" switcher ```ts filename="app/items/route.ts" switcher
export const dynamic = 'force-static' export const dynamic = 'force-static'
...@@ -86,9 +86,9 @@ export async function GET() { ...@@ -86,9 +86,9 @@ export async function GET() {
#### With Cache Components #### With Cache Components
When [Cache Components](/docs/app/getting-started/cache-components) is enabled, `GET` Route Handlers follow the same model as normal UI routes in your application. They run at request time by default, can be prerendered when they don't access dynamic or runtime data, and you can use `use cache` to include dynamic data in the static response. When [Cache Components](/docs/app/getting-started/caching) is enabled, `GET` Route Handlers follow the same model as normal UI routes in your application. They run at request time by default, can be prerendered when they don't access uncached or runtime data, and you can use `use cache` to include uncached data in the static response.
**Static example** - doesn't access dynamic or runtime data, so it will be prerendered at build time: **Static example** - doesn't access uncached or runtime data, so it will be prerendered at build time:
```tsx filename="app/api/project-info/route.ts" ```tsx filename="app/api/project-info/route.ts"
export async function GET() { export async function GET() {
...@@ -123,7 +123,7 @@ export async function GET() { ...@@ -123,7 +123,7 @@ export async function GET() {
> **Good to know**: Prerendering stops if the `GET` handler accesses network requests, database queries, async file system operations, request object properties (like `req.url`, `request.headers`, `request.cookies`, `request.body`), runtime APIs like [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`connection()`](/docs/app/api-reference/functions/connection), or non-deterministic operations. > **Good to know**: Prerendering stops if the `GET` handler accesses network requests, database queries, async file system operations, request object properties (like `req.url`, `request.headers`, `request.cookies`, `request.body`), runtime APIs like [`cookies()`](/docs/app/api-reference/functions/cookies), [`headers()`](/docs/app/api-reference/functions/headers), [`connection()`](/docs/app/api-reference/functions/connection), or non-deterministic operations.
**Cached example** - accesses dynamic data (database query) but caches it with `use cache`, allowing it to be included in the prerendered response: **Cached example** - accesses uncached data (database query) but caches it with `use cache`, allowing it to be included in the prerendered response:
```tsx filename="app/api/products/route.ts" ```tsx filename="app/api/products/route.ts"
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -145,7 +145,7 @@ async function getProducts() { ...@@ -145,7 +145,7 @@ async function getProducts() {
### Special Route Handlers ### Special Route Handlers
Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) remain static by default unless they use Dynamic APIs or dynamic config options. Special Route Handlers like [`sitemap.ts`](/docs/app/api-reference/file-conventions/metadata/sitemap), [`opengraph-image.tsx`](/docs/app/api-reference/file-conventions/metadata/opengraph-image), and [`icon.tsx`](/docs/app/api-reference/file-conventions/metadata/app-icons), and other [metadata files](/docs/app/api-reference/file-conventions/metadata) remain static by default unless they use Request-time APIs or dynamic config options.
### Route Resolution ### Route Resolution
......
...@@ -30,7 +30,7 @@ The examples on this page walk through basic username and password auth for educ ...@@ -30,7 +30,7 @@ The examples on this page walk through basic username and password auth for educ
### Sign-up and login functionality ### Sign-up and login functionality
You can use the [`<form>`](https://react.dev/reference/react-dom/components/form) element with React's [Server Actions](/docs/app/getting-started/updating-data) and `useActionState` to capture user credentials, validate form fields, and call your Authentication Provider's API or database. You can use the [`<form>`](https://react.dev/reference/react-dom/components/form) element with React's [Server Actions](/docs/app/getting-started/mutating-data) and `useActionState` to capture user credentials, validate form fields, and call your Authentication Provider's API or database.
Since Server Actions always execute on the server, they provide a secure environment for handling authentication logic. Since Server Actions always execute on the server, they provide a secure environment for handling authentication logic.
...@@ -1448,7 +1448,7 @@ This pattern allows you to show or hide UI elements based on user permissions wh ...@@ -1448,7 +1448,7 @@ This pattern allows you to show or hide UI elements based on user permissions wh
### Server Actions ### Server Actions
Treat [Server Actions](/docs/app/getting-started/updating-data) with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation. Treat [Server Actions](/docs/app/getting-started/mutating-data) with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation.
In the example below, we check the user's role before allowing the action to proceed: In the example below, we check the user's role before allowing the action to proceed:
...@@ -1542,7 +1542,7 @@ The example above demonstrates a Route Handler with a two-tier security check. I ...@@ -1542,7 +1542,7 @@ The example above demonstrates a Route Handler with a two-tier security check. I
## Context Providers ## Context Providers
Using context providers for auth works due to [interleaving](/docs/app/getting-started/server-and-client-components#examples#interleaving-server-and-client-components). However, React `context` is not supported in Server Components, making them only applicable to Client Components. 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: 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:
......
...@@ -866,7 +866,7 @@ These examples include, working with [Cookies](/docs/app/api-reference/file-conv ...@@ -866,7 +866,7 @@ These examples include, working with [Cookies](/docs/app/api-reference/file-conv
Fetch data in Server Components directly from its source, not via Route Handlers. Fetch data in Server Components directly from its source, not via Route Handlers.
For Server Components pre-rendered at build time, using Route Handlers will fail the build step. This is because, while building there is no server listening for these requests. For Server Components prerendered at build time, using Route Handlers will fail the build step. This is because, while building there is no server listening for these requests.
For Server Components rendered on demand, fetching from Route Handlers is slower due to the extra HTTP round trip between the handler and the render process. For Server Components rendered on demand, fetching from Route Handlers is slower due to the extra HTTP round trip between the handler and the render process.
...@@ -893,7 +893,7 @@ Server Actions are queued. Using them for data fetching introduces sequential ex ...@@ -893,7 +893,7 @@ Server Actions are queued. Using them for data fetching introduces sequential ex
`export` mode outputs a static site without a runtime server. Features that require the Next.js runtime are [not supported](/docs/app/guides/static-exports#unsupported-features), because this mode produces a static site, and no runtime server. `export` mode outputs a static site without a runtime server. Features that require the Next.js runtime are [not supported](/docs/app/guides/static-exports#unsupported-features), because this mode produces a static site, and no runtime server.
In `export mode`, only `GET` Route Handlers are supported, in combination with the [`dynamic`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) route segment config, set to `'force-static'`. In `export mode`, only `GET` Route Handlers are supported, in combination with the [`dynamic`](/docs/app/guides/caching-without-cache-components#dynamic) route segment config, set to `'force-static'`.
This can be used to generate static HTML, JSON, TXT, or other files. This can be used to generate static HTML, JSON, TXT, or other files.
......
This diff is collapsed.
This diff is collapsed.
...@@ -35,7 +35,7 @@ If an attacker wanted to load a script into your page, they'd need to guess the ...@@ -35,7 +35,7 @@ If an attacker wanted to load a script into your page, they'd need to guess the
[Proxy](/docs/app/api-reference/file-conventions/proxy) enables you to add headers and generate nonces before the page renders. [Proxy](/docs/app/api-reference/file-conventions/proxy) enables you to add headers and generate nonces before the page renders.
Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/guides/caching#dynamic-rendering) to add nonces**. Every time a page is viewed, a fresh nonce should be generated. This means that you **must use [dynamic rendering](/docs/app/glossary#dynamic-rendering) to add nonces**.
For example: For example:
......
...@@ -206,7 +206,7 @@ On the initial load, both Server and Client Components run on the server to gene ...@@ -206,7 +206,7 @@ On the initial load, both Server and Client Components run on the server to gene
**Client Components:** **Client Components:**
- Run on the server during pre-rendering, but must follow the same security assumptions as code running in the browser. - Run on the server during prerendering, but must follow the same security assumptions as code running in the browser.
- Must not access privileged data or server-only modules. - Must not access privileged data or server-only modules.
This ensures the app is secure by default, but it's possible to accidentally expose private data through how data is fetched or passed to components. This ensures the app is secure by default, but it's possible to accidentally expose private data through how data is fetched or passed to components.
......
...@@ -9,7 +9,7 @@ related: ...@@ -9,7 +9,7 @@ related:
- app/api-reference/functions/draft-mode - app/api-reference/functions/draft-mode
--- ---
**Draft Mode** allows you to preview draft content from your headless CMS in your Next.js application. This is useful for static pages that are generated at build time as it allows you to switch to [dynamic rendering](/docs/app/guides/caching#dynamic-rendering) and see the draft changes without having to rebuild your entire site. **Draft Mode** allows you to preview draft content from your headless CMS in your Next.js application. This is useful for static pages that are generated at build time as it allows you to switch to [dynamic rendering](/docs/app/glossary#dynamic-rendering) and see the draft changes without having to rebuild your entire site.
This page walks through how to enable and use Draft Mode. This page walks through how to enable and use Draft Mode.
......
...@@ -212,7 +212,7 @@ import { connection } from 'next/server' ...@@ -212,7 +212,7 @@ import { connection } from 'next/server'
export default async function Component() { export default async function Component() {
await connection() await connection()
// cookies, headers, and other Dynamic APIs // cookies, headers, and other Request-time APIs
// will also opt into dynamic rendering, meaning // will also opt into dynamic rendering, meaning
// this env variable is evaluated at runtime // this env variable is evaluated at runtime
const value = process.env.MY_VALUE const value = process.env.MY_VALUE
...@@ -225,7 +225,7 @@ import { connection } from 'next/server' ...@@ -225,7 +225,7 @@ import { connection } from 'next/server'
export default async function Component() { export default async function Component() {
await connection() await connection()
// cookies, headers, and other Dynamic APIs // cookies, headers, and other Request-time APIs
// will also opt into dynamic rendering, meaning // will also opt into dynamic rendering, meaning
// this env variable is evaluated at runtime // this env variable is evaluated at runtime
const value = process.env.MY_VALUE const value = process.env.MY_VALUE
......
...@@ -206,7 +206,7 @@ Here's how this example works: ...@@ -206,7 +206,7 @@ Here's how this example works:
### Route segment config ### Route segment config
- [`revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) - [`revalidate`](/docs/app/guides/caching-without-cache-components#route-segment-config-revalidate)
- [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) - [`dynamicParams`](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams)
### Functions ### Functions
...@@ -277,7 +277,7 @@ export default async function Page() { ...@@ -277,7 +277,7 @@ export default async function Page() {
} }
``` ```
We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to [dynamic rendering](/docs/app/guides/caching#dynamic-rendering). We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to [dynamic rendering](/docs/app/glossary#dynamic-rendering).
### On-demand revalidation with `revalidatePath` ### On-demand revalidation with `revalidatePath`
...@@ -373,7 +373,7 @@ export default async function Page() { ...@@ -373,7 +373,7 @@ export default async function Page() {
} }
``` ```
You can then use `revalidateTag` in a [Server Actions](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route): You can then use `revalidateTag` in a [Server Actions](/docs/app/getting-started/mutating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route):
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
'use server' 'use server'
...@@ -572,8 +572,8 @@ This will make the Next.js server console log ISR cache hits and misses. You can ...@@ -572,8 +572,8 @@ This will make the Next.js server console log ISR cache hits and misses. You can
- ISR is only supported when using the Node.js runtime (default). - ISR is only supported when using the Node.js runtime (default).
- ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports).
- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/guides/caching#data-cache). - If you have multiple `fetch` requests in a prerendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [cache](/docs/app/getting-started/caching).
- If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/guides/caching#dynamic-rendering). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be dynamically rendered.
- Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. - Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`.
</AppOnly> </AppOnly>
......
...@@ -65,7 +65,7 @@ When using `React.lazy()` and Suspense, Client Components will be [prerendered]( ...@@ -65,7 +65,7 @@ When using `React.lazy()` and Suspense, Client Components will be [prerendered](
> **Note:** `ssr: false` option will only work for Client Components, move it into Client Components ensure the client code-splitting working properly. > **Note:** `ssr: false` option will only work for Client Components, move it into Client Components ensure the client code-splitting working properly.
If you want to disable pre-rendering for a Client Component, you can use the `ssr` option set to `false`: If you want to disable prerendering for a Client Component, you can use the `ssr` option set to `false`:
```jsx ```jsx
const ComponentC = dynamic(() => import('../components/C'), { ssr: false }) const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
......
...@@ -45,7 +45,7 @@ For more configuration options, see the [next-devtools-mcp repository](https://g ...@@ -45,7 +45,7 @@ For more configuration options, see the [next-devtools-mcp repository](https://g
- **Next.js Knowledge Base**: Query comprehensive Next.js documentation and best practices - **Next.js Knowledge Base**: Query comprehensive Next.js documentation and best practices
- **Migration and Upgrade Tools**: Automated helpers for upgrading to Next.js 16 with codemods - **Migration and Upgrade Tools**: Automated helpers for upgrading to Next.js 16 with codemods
- **Cache Components Guide**: Setup and configuration assistance for Cache Components - **Caching Guide**: Setup and configuration assistance for Cache Components
- **Browser Testing**: [Playwright MCP](https://github.com/microsoft/playwright-mcp) integration for verifying pages in the browser - **Browser Testing**: [Playwright MCP](https://github.com/microsoft/playwright-mcp) integration for verifying pages in the browser
> **Note:** The Next.js team is actively expanding these capabilities. New tools and features are added regularly to improve the agent development experience. > **Note:** The Next.js team is actively expanding these capabilities. New tools and features are added regularly to improve the agent development experience.
......
---
title: Migrating to Cache Components
nav_title: Migrating to Cache Components
description: Learn how to migrate from route segment configs to Cache Components in Next.js.
---
When [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled, route segment configs like `dynamic`, `revalidate`, and `fetchCache` are replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) and [`cacheLife`](/docs/app/api-reference/functions/cacheLife).
## `dynamic = "force-dynamic"`
**Not needed.** All pages are dynamic by default.
```tsx filename="app/page.tsx" switcher
// Before - No longer needed
export const dynamic = 'force-dynamic'
export default function Page() {
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// Before - No longer needed
export const dynamic = 'force-dynamic'
export default function Page() {
return <div>...</div>
}
```
```tsx filename="app/page.tsx" switcher
// After - Just remove it
export default function Page() {
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// After - Just remove it
export default function Page() {
return <div>...</div>
}
```
## `dynamic = "force-static"`
Start by removing it. When unhandled uncached or runtime data access is detected during development and build time, Next.js raises an error. Otherwise, the prerendering step automatically extracts the static HTML shell.
For uncached data access, add [`use cache`](/docs/app/api-reference/directives/use-cache) as close to the data access as possible with a long [`cacheLife`](/docs/app/api-reference/functions/cacheLife) like `'max'` to maintain cached behavior. If needed, add it at the top of the page or layout.
For runtime data access (`cookies()`, `headers()`, etc.), errors will direct you to wrap it with `<Suspense>`. Since you started by using `force-static`, you must remove the runtime data access to prevent any request time work.
```tsx filename="app/page.tsx" switcher
// Before
export const dynamic = 'force-static'
export default async function Page() {
const data = await fetch('https://api.example.com/data')
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// Before
export const dynamic = 'force-static'
export default async function Page() {
const data = await fetch('https://api.example.com/data')
return <div>...</div>
}
```
```tsx filename="app/page.tsx" switcher
import { cacheLife } from 'next/cache'
// After - Use 'use cache' instead
export default async function Page() {
'use cache'
cacheLife('max')
const data = await fetch('https://api.example.com/data')
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
import { cacheLife } from 'next/cache'
// After - Use 'use cache' instead
export default async function Page() {
'use cache'
cacheLife('max')
const data = await fetch('https://api.example.com/data')
return <div>...</div>
}
```
## `revalidate`
**Replace with `cacheLife`.** Use the `cacheLife` function to define cache duration instead of the route segment config.
```tsx filename="app/page.tsx" switcher
// Before
export const revalidate = 3600 // 1 hour
export default async function Page() {
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// Before
export const revalidate = 3600 // 1 hour
export default async function Page() {
return <div>...</div>
}
```
```tsx filename="app/page.tsx" switcher
// After - Use cacheLife
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife('hours')
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// After - Use cacheLife
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife('hours')
return <div>...</div>
}
```
## `fetchCache`
**Not needed.** With `use cache`, all data fetching within a cached scope is automatically cached, making `fetchCache` unnecessary.
```tsx filename="app/page.tsx" switcher
// Before
export const fetchCache = 'force-cache'
```
```jsx filename="app/page.js" switcher
// Before
export const fetchCache = 'force-cache'
```
```tsx filename="app/page.tsx" switcher
// After - Use 'use cache' to control caching behavior
export default async function Page() {
'use cache'
// All fetches here are cached
return <div>...</div>
}
```
```jsx filename="app/page.js" switcher
// After - Use 'use cache' to control caching behavior
export default async function Page() {
'use cache'
// All fetches here are cached
return <div>...</div>
}
```
## `runtime = 'edge'`
**Not supported.** Cache Components requires the Node.js runtime. Switch to the Node.js runtime (the default) by removing the `runtime = 'edge'` export. If you need edge behavior for specific routes, use [Proxy](/docs/app/api-reference/file-conventions/proxy) instead.
...@@ -509,7 +509,7 @@ In addition, the new `useRouter` hook has the following changes: ...@@ -509,7 +509,7 @@ In addition, the new `useRouter` hook has the following changes:
- The `locale`, `locales`, `defaultLocales`, `domainLocales` values have been removed because built-in i18n Next.js features are no longer necessary in the `app` directory. [Learn more about i18n](/docs/app/guides/internationalization). - The `locale`, `locales`, `defaultLocales`, `domainLocales` values have been removed because built-in i18n Next.js features are no longer necessary in the `app` directory. [Learn more about i18n](/docs/app/guides/internationalization).
- `basePath` has been removed. The alternative will not be part of `useRouter`. It has not yet been implemented. - `basePath` has been removed. The alternative will not be part of `useRouter`. It has not yet been implemented.
- `asPath` has been removed because the concept of `as` has been removed from the new router. - `asPath` has been removed because the concept of `as` has been removed from the new router.
- `isReady` has been removed because it is no longer necessary. During [static rendering](/docs/app/guides/caching#static-rendering), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) hook will skip the prerendering step and instead be rendered on the client at runtime. - `isReady` has been removed because it is no longer necessary. During [prerendering](/docs/app/glossary#prerendering), any component that uses the [`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) hook will skip the prerendering step and instead be rendered on the client at runtime.
- `route` has been removed. `usePathname` or `useSelectedLayoutSegments()` provide an alternative. - `route` has been removed. `usePathname` or `useSelectedLayoutSegments()` provide an alternative.
[View the `useRouter()` API reference](/docs/app/api-reference/functions/use-router). [View the `useRouter()` API reference](/docs/app/api-reference/functions/use-router).
...@@ -708,7 +708,7 @@ export default async function Page() { ...@@ -708,7 +708,7 @@ export default async function Page() {
#### Static Site Generation (`getStaticProps`) #### Static Site Generation (`getStaticProps`)
In the `pages` directory, the `getStaticProps` function is used to pre-render a page at build time. This function can be used to fetch data from an external API or directly from a database, and pass this data down to the entire page as it's being generated during the build. In the `pages` directory, the `getStaticProps` function is used to prerender a page at build time. This function can be used to fetch data from an external API or directly from a database, and pass this data down to the entire page as it's being generated during the build.
```jsx filename="pages/index.js" ```jsx filename="pages/index.js"
// `pages` directory // `pages` directory
...@@ -747,7 +747,7 @@ export default async function Index() { ...@@ -747,7 +747,7 @@ export default async function Index() {
#### Dynamic paths (`getStaticPaths`) #### Dynamic paths (`getStaticPaths`)
In the `pages` directory, the `getStaticPaths` function is used to define the dynamic paths that should be pre-rendered at build time. In the `pages` directory, the `getStaticPaths` function is used to define the dynamic paths that should be prerendered at build time.
```jsx filename="pages/posts/[id].js" ```jsx filename="pages/posts/[id].js"
// `pages` directory // `pages` directory
...@@ -803,7 +803,7 @@ Using the name `generateStaticParams` is more appropriate than `getStaticPaths` ...@@ -803,7 +803,7 @@ Using the name `generateStaticParams` is more appropriate than `getStaticPaths`
#### Replacing `fallback` #### Replacing `fallback`
In the `pages` directory, the `fallback` property returned from `getStaticPaths` is used to define the behavior of a page that isn't pre-rendered at build time. This property can be set to `true` to show a fallback page while the page is being generated, `false` to show a 404 page, or `blocking` to generate the page at request time. In the `pages` directory, the `fallback` property returned from `getStaticPaths` is used to define the behavior of a page that isn't prerendered at build time. This property can be set to `true` to show a fallback page while the page is being generated, `false` to show a 404 page, or `blocking` to generate the page at request time.
```jsx filename="pages/posts/[id].js" ```jsx filename="pages/posts/[id].js"
// `pages` directory // `pages` directory
......
...@@ -125,7 +125,7 @@ Since the pages in different zones may be released at different times, feature f ...@@ -125,7 +125,7 @@ Since the pages in different zones may be released at different times, feature f
## Server Actions ## Server Actions
When using [Server Actions](/docs/app/getting-started/updating-data) with Multi-Zones, you must explicitly allow the user-facing origin since your user facing domain may serve multiple applications. In your `next.config.js` file, add the following lines: When using [Server Actions](/docs/app/getting-started/mutating-data) with Multi-Zones, you must explicitly allow the user-facing origin since your user facing domain may serve multiple applications. In your `next.config.js` file, add the following lines:
```js filename="next.config.js" ```js filename="next.config.js"
const nextConfig = { const nextConfig = {
......
...@@ -23,11 +23,11 @@ When navigating to the new page, there's no full page reload or browser loading ...@@ -23,11 +23,11 @@ When navigating to the new page, there's no full page reload or browser loading
## Prefetching static vs. dynamic routes ## Prefetching static vs. dynamic routes
| | **Static page** | **Dynamic page** | | | **Static page** | **Dynamic page** |
| ----------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------- | | ------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------- |
| **Prefetched** | Yes, full route | No, unless [`loading.js`](/docs/app/api-reference/file-conventions/loading) | | **Prefetched** | Yes, full route | No, unless [`loading.js`](/docs/app/api-reference/file-conventions/loading) |
| [**Client Cache TTL**](/docs/app/guides/caching#full-route-cache) | 5 min (default) | Off, unless [enabled](/docs/app/api-reference/config/next-config-js/staleTimes) | | [**Client Cache TTL**](/docs/app/glossary#client-cache) | 5 min (default) | Off, unless [enabled](/docs/app/api-reference/config/next-config-js/staleTimes) |
| **Server roundtrip on click** | No | Yes, streamed after [shell](/docs/app/getting-started/cache-components) | | **Server roundtrip on click** | No | Yes, streamed after [shell](/docs/app/getting-started/caching) |
> **Good to know:** During the initial navigation, the browser fetches the HTML, JavaScript, and React Server Components (RSC) Payload. For subsequent navigations, the browser will fetch the RSC Payload for Server Components and JS bundle for Client Components. > **Good to know:** During the initial navigation, the browser fetches the HTML, JavaScript, and React Server Components (RSC) Payload. For subsequent navigations, the browser will fetch the RSC Payload for Server Components and JS bundle for Client Components.
...@@ -208,7 +208,7 @@ The scheduler prioritizes likely navigations while minimizing unused downloads. ...@@ -208,7 +208,7 @@ The scheduler prioritizes likely navigations while minimizing unused downloads.
When PPR is enabled, a page is divided into a static shell and a streamed dynamic section: When PPR is enabled, a page is divided into a static shell and a streamed dynamic section:
- The shell, which can be prefetched, streams immediately - The shell, which can be prefetched, streams immediately
- Dynamic data streams when ready - Uncached data streams when ready
- Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches - Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches
## Troubleshooting ## Troubleshooting
......
...@@ -6,10 +6,10 @@ related: ...@@ -6,10 +6,10 @@ related:
title: Related title: Related
description: Learn more about Cache Components and preserving UI state. description: Learn more about Cache Components and preserving UI state.
links: links:
- app/getting-started/cache-components - app/getting-started/caching
--- ---
> **Good to know:** This guide assumes [Cache Components](/docs/app/getting-started/cache-components) is enabled. Enable it by setting [`cacheComponents: true`](/docs/app/api-reference/config/next-config-js/cacheComponents) in your Next config file. > **Good to know:** This guide assumes [Cache Components](/docs/app/getting-started/caching) is enabled. Enable it by setting [`cacheComponents: true`](/docs/app/api-reference/config/next-config-js/cacheComponents) in your Next config file.
Before Cache Components, preserving page-level state across navigations required workarounds like hoisting state to a [shared layout](/docs/app/getting-started/layouts-and-pages#nesting-layouts) or using an external store. With Cache Components, Next.js preserves state and DOM out of the box. Before Cache Components, preserving page-level state across navigations required workarounds like hoisting state to a [shared layout](/docs/app/getting-started/layouts-and-pages#nesting-layouts) or using an external store. With Cache Components, Next.js preserves state and DOM out of the box.
......
...@@ -17,8 +17,8 @@ These Next.js optimizations are enabled by default and require no configuration: ...@@ -17,8 +17,8 @@ These Next.js optimizations are enabled by default and require no configuration:
- **[Server Components](/docs/app/getting-started/server-and-client-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/getting-started/server-and-client-components) as needed for interactivity. - **[Server Components](/docs/app/getting-started/server-and-client-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/getting-started/server-and-client-components) as needed for interactivity.
- **[Code-splitting](/docs/app/getting-started/linking-and-navigating#how-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Code-splitting](/docs/app/getting-started/linking-and-navigating#how-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate.
- **[Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate.
- **[Static Rendering](/docs/app/guides/caching#static-rendering):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/guides/caching#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} - **[Prerendering](/docs/app/glossary#prerendering):** Next.js prerenders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/glossary#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */}
- **[Caching](/docs/app/guides/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. - **[Caching](/docs/app/getting-started/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate.
</AppOnly> </AppOnly>
...@@ -26,7 +26,7 @@ These Next.js optimizations are enabled by default and require no configuration: ...@@ -26,7 +26,7 @@ These Next.js optimizations are enabled by default and require no configuration:
- **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/guides/lazy-loading) third-party libraries, where appropriate. - **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/guides/lazy-loading) third-party libraries, where appropriate.
- **[Prefetching](/docs/pages/api-reference/components/link#prefetch):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Prefetching](/docs/pages/api-reference/components/link#prefetch):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate.
- **[Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization):** Next.js automatically determines that a page is static (can be pre-rendered) if it has no blocking data requirements. Optimized pages can be cached, and served to the end-user from multiple CDN locations. You may opt into [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props), where appropriate. - **[Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization):** Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements. Optimized pages can be cached, and served to the end-user from multiple CDN locations. You may opt into [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props), where appropriate.
</PagesOnly> </PagesOnly>
...@@ -43,8 +43,8 @@ While building your application, we recommend using the following features to en ...@@ -43,8 +43,8 @@ While building your application, we recommend using the following features to en
- **[Layouts](/docs/app/api-reference/file-conventions/layout):** Use layouts to share UI across pages and enable [partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions) on navigation. - **[Layouts](/docs/app/api-reference/file-conventions/layout):** Use layouts to share UI across pages and enable [partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions) on navigation.
- **[`<Link>` component](/docs/app/api-reference/components/link):** Use the `<Link>` component for [client-side navigation and prefetching](/docs/app/getting-started/linking-and-navigating#how-navigation-works). - **[`<Link>` component](/docs/app/api-reference/components/link):** Use the `<Link>` component for [client-side navigation and prefetching](/docs/app/getting-started/linking-and-navigating#how-navigation-works).
- **[Error Handling](/docs/app/getting-started/error-handling):** Gracefully handle [catch-all errors](/docs/app/getting-started/error-handling) and [404 errors](/docs/app/api-reference/file-conventions/not-found) in production by creating custom error pages. - **[Error Handling](/docs/app/getting-started/error-handling):** Gracefully handle [catch-all errors](/docs/app/getting-started/error-handling) and [404 errors](/docs/app/api-reference/file-conventions/not-found) in production by creating custom error pages.
- **[Client and Server Components](/docs/app/getting-started/server-and-client-components#examples):** Follow the recommended composition patterns for Server and Client Components, and check the placement of your [`"use client"` boundaries](/docs/app/getting-started/server-and-client-components#examples#moving-client-components-down-the-tree) to avoid unnecessarily increasing your client-side JavaScript bundle. - **[Client and Server Components](/docs/app/getting-started/server-and-client-components#examples):** Follow the recommended composition patterns for Server and Client Components, and check the placement of your [`"use client"` boundaries](/docs/app/getting-started/server-and-client-components#reducing-js-bundle-size) to avoid unnecessarily increasing your client-side JavaScript bundle.
- **[Dynamic APIs](/docs/app/guides/caching#dynamic-rendering):** Be aware that Dynamic APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop will opt the entire route into [Dynamic Rendering](/docs/app/guides/caching#dynamic-rendering) (or your whole application if used in the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout)). Ensure Dynamic API usage is intentional and wrap them in `<Suspense>` boundaries where appropriate. - **Request-time APIs:** Be aware that Request-time APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop will opt the entire route into [Dynamic Rendering](/docs/app/glossary#dynamic-rendering) (or your whole application if used in the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout)). Ensure Request-time API usage is intentional and wrap them in `<Suspense>` boundaries where appropriate.
> **Good to know**: [Partial Prerendering (experimental)](/blog/next-14#partial-prerendering-preview) will allow parts of a route to be dynamic without opting the whole route into dynamic rendering. > **Good to know**: [Partial Prerendering (experimental)](/blog/next-14#partial-prerendering-preview) will allow parts of a route to be dynamic without opting the whole route into dynamic rendering.
...@@ -64,8 +64,8 @@ While building your application, we recommend using the following features to en ...@@ -64,8 +64,8 @@ While building your application, we recommend using the following features to en
- **[Server Components](/docs/app/getting-started/fetching-data):** Leverage the benefits of fetching data on the server using Server Components. - **[Server Components](/docs/app/getting-started/fetching-data):** Leverage the benefits of fetching data on the server using Server Components.
- **[Route Handlers](/docs/app/api-reference/file-conventions/route):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request. - **[Route Handlers](/docs/app/api-reference/file-conventions/route):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request.
- **[Streaming](/docs/app/api-reference/file-conventions/loading):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Streaming](/docs/app/api-reference/file-conventions/loading):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched.
- **[Parallel Data Fetching](/docs/app/getting-started/fetching-data#parallel-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/getting-started/fetching-data#preloading-data) where appropriate. - **[Parallel Data Fetching](/docs/app/getting-started/fetching-data#parallel-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate.
- **[Data Caching](/docs/app/guides/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). - **[Data Caching](/docs/app/getting-started/caching):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache).
- **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. - **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images.
</AppOnly> </AppOnly>
...@@ -99,7 +99,7 @@ While building your application, we recommend using the following features to en ...@@ -99,7 +99,7 @@ While building your application, we recommend using the following features to en
<AppOnly> <AppOnly>
- **[Tainting](/docs/app/api-reference/config/next-config-js/taint):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values. - **[Tainting](/docs/app/api-reference/config/next-config-js/taint):** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values.
- **[Server Actions](/docs/app/getting-started/updating-data):** Ensure users are authorized to call Server Actions. Review the recommended [security practices](/blog/security-nextjs-server-components-actions). - **[Server Actions](/docs/app/getting-started/mutating-data):** Ensure users are authorized to call Server Actions. Review the recommended [security practices](/blog/security-nextjs-server-components-actions).
</AppOnly> </AppOnly>
......
...@@ -14,7 +14,7 @@ This guide will show you how to build public pages that share data across users. ...@@ -14,7 +14,7 @@ This guide will show you how to build public pages that share data across users.
As an example, we'll build a product list page. As an example, we'll build a product list page.
We'll start with a static header, add a product list with async external data, and learn how to render it without blocking the response. Finally, we'll add a user-specific promotion banner without switching the entire page to [request-time rendering](/docs/app/glossary#request-time-rendering). We'll start with a static header, add a product list with async external data, and learn how to render it without blocking the response. Finally, we'll add a user-specific promotion banner without switching the entire page to [dynamic rendering](/docs/app/glossary#dynamic-rendering).
You can find the resources used in this example here: You can find the resources used in this example here:
...@@ -234,7 +234,7 @@ Route (app) Revalidate Expire ...@@ -234,7 +234,7 @@ Route (app) Revalidate Expire
At [**build time**](/docs/app/glossary#build-time), most of the page, including the header, product list and promotion fallback, is rendered, cached and pushed to a content delivery network. At [**build time**](/docs/app/glossary#build-time), most of the page, including the header, product list and promotion fallback, is rendered, cached and pushed to a content delivery network.
At [**request time**](/docs/app/glossary#request-time), the prerendered part is served instantly from a CDN node close to the user. At [**request time**](/docs/app/glossary#dynamic-rendering), the prerendered part is served instantly from a CDN node close to the user.
In parallel, the user specific promotion is rendered on the server, streamed to the client, and swapped into the fallback slot. In parallel, the user specific promotion is rendered on the server, streamed to the client, and swapped into the fallback slot.
......
...@@ -38,7 +38,7 @@ There are a few ways you can handle redirects in Next.js. This page will go thro ...@@ -38,7 +38,7 @@ There are a few ways you can handle redirects in Next.js. This page will go thro
## `redirect` function ## `redirect` function
The `redirect` function allows you to redirect the user to another URL. You can call `redirect` in [Server Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/updating-data). The `redirect` function allows you to redirect the user to another URL. You can call `redirect` in [Server Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data).
`redirect` is often used after a mutation or event. For example, creating a post: `redirect` is often used after a mutation or event. For example, creating a post:
...@@ -90,7 +90,7 @@ See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) f ...@@ -90,7 +90,7 @@ See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) f
## `permanentRedirect` function ## `permanentRedirect` function
The `permanentRedirect` function allows you to **permanently** redirect the user to another URL. You can call `permanentRedirect` in [Server Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/updating-data). The `permanentRedirect` function allows you to **permanently** redirect the user to another URL. You can call `permanentRedirect` in [Server Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data).
`permanentRedirect` is often used after a mutation or event that changes an entity's canonical URL, such as updating a user's profile URL after they change their username: `permanentRedirect` is often used after a mutation or event that changes an entity's canonical URL, such as updating a user's profile URL after they change their username:
......
...@@ -55,7 +55,7 @@ import { connection } from 'next/server' ...@@ -55,7 +55,7 @@ import { connection } from 'next/server'
export default async function Component() { export default async function Component() {
await connection() await connection()
// cookies, headers, and other Dynamic APIs // cookies, headers, and other Request-time APIs
// will also opt into dynamic rendering, meaning // will also opt into dynamic rendering, meaning
// this env variable is evaluated at runtime // this env variable is evaluated at runtime
const value = process.env.MY_VALUE const value = process.env.MY_VALUE
...@@ -68,7 +68,7 @@ import { connection } from 'next/server' ...@@ -68,7 +68,7 @@ import { connection } from 'next/server'
export default async function Component() { export default async function Component() {
await connection() await connection()
// cookies, headers, and other Dynamic APIs // cookies, headers, and other Request-time APIs
// will also opt into dynamic rendering, meaning // will also opt into dynamic rendering, meaning
// this env variable is evaluated at runtime // this env variable is evaluated at runtime
const value = process.env.MY_VALUE const value = process.env.MY_VALUE
...@@ -108,7 +108,7 @@ If you want to host static assets on a different domain or CDN, you can use the ...@@ -108,7 +108,7 @@ If you want to host static assets on a different domain or CDN, you can use the
By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching. By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching.
To configure the ISR/Data Cache location when self-hosting, you can configure a custom handler in your `next.config.js` file: To configure the cache location when self-hosting, you can configure a custom handler in your `next.config.js` file:
```jsx filename="next.config.js" ```jsx filename="next.config.js"
module.exports = { module.exports = {
...@@ -186,7 +186,7 @@ When running Next.js across multiple server instances (for example, containers b ...@@ -186,7 +186,7 @@ When running Next.js across multiple server instances (for example, containers b
### Server Functions encryption key ### Server Functions encryption key
Next.js encrypts [Server Function](/docs/app/getting-started/updating-data) closure variables before sending them to the client. By default, a unique encryption key is generated for each build. Next.js encrypts [Server Function](/docs/app/getting-started/mutating-data) closure variables before sending them to the client. By default, a unique encryption key is generated for each build.
When running multiple server instances, all instances must use the same encryption key. Otherwise, a Server Function encrypted by one instance cannot be decrypted by another, causing "Failed to find Server Action" errors. When running multiple server instances, all instances must use the same encryption key. Otherwise, a Server Function encrypted by one instance cannot be decrypted by another, causing "Failed to find Server Action" errors.
...@@ -258,7 +258,7 @@ module.exports = { ...@@ -258,7 +258,7 @@ module.exports = {
## Cache Components ## Cache Components
[Cache Components](/docs/app/getting-started/cache-components) works by default with Next.js and is not a CDN-only feature. This includes deployment as a Node.js server (through `next start`) and when used with a Docker container. [Cache Components](/docs/app/getting-started/caching) works by default with Next.js and is not a CDN-only feature. This includes deployment as a Node.js server (through `next start`) and when used with a Docker container.
## Usage with CDNs ## Usage with CDNs
......
...@@ -25,7 +25,7 @@ Next.js can automatically code split your JavaScript bundles, and generate multi ...@@ -25,7 +25,7 @@ Next.js can automatically code split your JavaScript bundles, and generate multi
The [`next/link`](/docs/app/api-reference/components/link) component automatically [prefetches](/docs/app/api-reference/components/link#prefetch) routes, giving you the fast page transitions of a strict SPA, but with the advantage of persisting application routing state to the URL for linking and sharing. The [`next/link`](/docs/app/api-reference/components/link) component automatically [prefetches](/docs/app/api-reference/components/link#prefetch) routes, giving you the fast page transitions of a strict SPA, but with the advantage of persisting application routing state to the URL for linking and sharing.
Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, Next.js allows you to progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/getting-started/updating-data), and more) as needed. Next.js can start as a static site or even a strict SPA where everything is rendered client-side. If your project grows, Next.js allows you to progressively add more server features (e.g. [React Server Components](/docs/app/getting-started/server-and-client-components), [Server Actions](/docs/app/getting-started/mutating-data), and more) as needed.
## Examples ## Examples
...@@ -389,7 +389,7 @@ export function Button() { ...@@ -389,7 +389,7 @@ export function Button() {
} }
``` ```
Learn more about [mutating data with Server Actions](/docs/app/getting-started/updating-data). Learn more about [mutating data with Server Actions](/docs/app/getting-started/mutating-data).
## Static export (optional) ## Static export (optional)
......
...@@ -252,7 +252,7 @@ If you need to read dynamic values from the incoming request, you cannot use a s ...@@ -252,7 +252,7 @@ If you need to read dynamic values from the incoming request, you cannot use a s
### Browser APIs ### Browser APIs
Client Components are pre-rendered to HTML during `next build`. Because [Web APIs](https://developer.mozilla.org/docs/Web/API) like `window`, `localStorage`, and `navigator` are not available on the server, you need to safely access these APIs only when running in the browser. For example: Client Components are prerendered to HTML during `next build`. Because [Web APIs](https://developer.mozilla.org/docs/Web/API) like `window`, `localStorage`, and `navigator` are not available on the server, you need to safely access these APIs only when running in the browser. For example:
```jsx ```jsx
'use client'; 'use client';
...@@ -288,10 +288,10 @@ Features that require a Node.js server, or dynamic logic that cannot be computed ...@@ -288,10 +288,10 @@ Features that require a Node.js server, or dynamic logic that cannot be computed
- [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration) - [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration)
- [Image Optimization](/docs/app/api-reference/components/image) with the default `loader` - [Image Optimization](/docs/app/api-reference/components/image) with the default `loader`
- [Draft Mode](/docs/app/guides/draft-mode) - [Draft Mode](/docs/app/guides/draft-mode)
- [Server Actions](/docs/app/getting-started/updating-data) - [Server Actions](/docs/app/getting-started/mutating-data)
- [Intercepting Routes](/docs/app/api-reference/file-conventions/intercepting-routes) - [Intercepting Routes](/docs/app/api-reference/file-conventions/intercepting-routes)
Attempting to use any of these features with `next dev` will result in an error, similar to setting the [`dynamic`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) option to `error` in the root layout. Attempting to use any of these features with `next dev` will result in an error, similar to setting the [`dynamic`](/docs/app/guides/caching-without-cache-components#dynamic) option to `error` in the root layout.
```jsx ```jsx
export const dynamic = 'error' export const dynamic = 'error'
......
...@@ -59,7 +59,7 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest ...@@ -59,7 +59,7 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest
## Async Request APIs (Breaking change) ## Async Request APIs (Breaking change)
Previously synchronous Dynamic APIs that rely on runtime information are now **asynchronous**: Previously synchronous Request-time APIs that rely on request information are now **asynchronous**:
- [`cookies`](/docs/app/api-reference/functions/cookies) - [`cookies`](/docs/app/api-reference/functions/cookies)
- [`headers`](/docs/app/api-reference/functions/headers) - [`headers`](/docs/app/api-reference/functions/headers)
...@@ -520,9 +520,9 @@ export const dynamic = 'force-static' ...@@ -520,9 +520,9 @@ export const dynamic = 'force-static'
export async function GET() {} export async function GET() {}
``` ```
## Client-side Router Cache ## Client Cache
When navigating between pages via `<Link>` or `useRouter`, [page](/docs/app/api-reference/file-conventions/page) segments are no longer reused from the client-side router cache. However, they are still reused during browser backward and forward navigation and for shared layouts. When navigating between pages via `<Link>` or `useRouter`, [page](/docs/app/api-reference/file-conventions/page) segments are no longer reused from the [Client Cache](/docs/app/glossary#client-cache). However, they are still reused during browser backward and forward navigation and for shared layouts.
To opt page segments into caching, you can use the [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes) config option: To opt page segments into caching, you can use the [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes) config option:
......
...@@ -303,9 +303,9 @@ Starting with **Next.js 16**, synchronous access is fully removed. These APIs ca ...@@ -303,9 +303,9 @@ Starting with **Next.js 16**, synchronous access is fully removed. These APIs ca
- `params` in [`layout.js`](/docs/app/api-reference/file-conventions/layout), [`page.js`](/docs/app/api-reference/file-conventions/page), [`route.js`](/docs/app/api-reference/file-conventions/route), [`default.js`](/docs/app/api-reference/file-conventions/default), [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#opengraph-image), [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#twitter-image), [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon), and [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon). - `params` in [`layout.js`](/docs/app/api-reference/file-conventions/layout), [`page.js`](/docs/app/api-reference/file-conventions/page), [`route.js`](/docs/app/api-reference/file-conventions/route), [`default.js`](/docs/app/api-reference/file-conventions/default), [`opengraph-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#opengraph-image), [`twitter-image`](/docs/app/api-reference/file-conventions/metadata/opengraph-image#twitter-image), [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon), and [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon).
- `searchParams` in [`page.js`](/docs/app/api-reference/file-conventions/page) - `searchParams` in [`page.js`](/docs/app/api-reference/file-conventions/page)
Use the [codemod](/docs/app/guides/upgrading/codemods#migrate-to-async-dynamic-apis) to migrate to async Dynamic APIs. Use the [codemod](/docs/app/guides/upgrading/codemods#migrate-to-async-dynamic-apis) to migrate to async Request-time APIs.
### Migrating types for async Dynamic APIs ### Migrating types for async Request-time APIs
To help migrate to async `params` and `searchParams`, you can run [`npx next typegen`](/docs/app/api-reference/cli/next#next-typegen-options) to automatically generate these globally available types helpers: To help migrate to async `params` and `searchParams`, you can run [`npx next typegen`](/docs/app/api-reference/cli/next#next-typegen-options) to automatically generate these globally available types helpers:
...@@ -482,7 +482,7 @@ Use `revalidateTag` for content where a slight delay in updates is acceptable, s ...@@ -482,7 +482,7 @@ Use `revalidateTag` for content where a slight delay in updates is acceptable, s
### updateTag ### updateTag
[`updateTag`](/docs/app/api-reference/functions/updateTag) is a new [Server Actions](/docs/app/getting-started/updating-data#what-are-server-functions)-only API that provides **read-your-writes** semantics, where a user makes a change and the UI immediately shows the change, rather than stale data. [`updateTag`](/docs/app/api-reference/functions/updateTag) is a new [Server Actions](/docs/app/getting-started/mutating-data#what-are-server-functions)-only API that provides **read-your-writes** semantics, where a user makes a change and the UI immediately shows the change, rather than stale data.
It does this by expiring and immediately refreshing data within the same request. It does this by expiring and immediately refreshing data within the same request.
...@@ -582,9 +582,9 @@ However, you may see more individual prefetch requests with much lower total tra ...@@ -582,9 +582,9 @@ However, you may see more individual prefetch requests with much lower total tra
If the increased request count causes issues, please let us know by creating an [issue](https://github.com/vercel/next.js/issues) or [discussion](https://github.com/vercel/next.js/discussions) item. If the increased request count causes issues, please let us know by creating an [issue](https://github.com/vercel/next.js/issues) or [discussion](https://github.com/vercel/next.js/discussions) item.
## Partial Pre-Rendering (PPR) ## Partial Prerendering (PPR)
**Next.js 16** removes the experimental **Partial Pre-Rendering (PPR)** flag and configuration options, including the route level segment `experimental_ppr`. **Next.js 16** removes the experimental **Partial Prerendering (PPR)** flag and configuration options, including the route level segment `experimental_ppr`.
Starting with **Next.js 16**, you can opt into PPR using the [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) configuration. Starting with **Next.js 16**, you can opt into PPR using the [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) configuration.
...@@ -597,7 +597,7 @@ const nextConfig = { ...@@ -597,7 +597,7 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
PPR in **Next.js 16** works differently than in **Next.js 15** canaries. If you are using PPR today, stay in the current Next.js 15 canary you are using. We will follow up with a guide to migrate to Cache Components. PPR in **Next.js 16** works differently than in **Next.js 15** canaries. If you are using PPR today, stay in the current Next.js 15 canary you are using. See [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components) for migration patterns.
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
......
...@@ -16,16 +16,16 @@ The `'use cache: private'` directive allows functions to access runtime request ...@@ -16,16 +16,16 @@ The `'use cache: private'` directive allows functions to access runtime request
Reach for `'use cache: private'` when: Reach for `'use cache: private'` when:
- You want to cache a function that already accesses runtime data, and refactoring to [move the runtime access outside and pass values as arguments](/docs/app/getting-started/cache-components#with-runtime-data) is not practical. - You want to cache a function that already accesses runtime data, and refactoring to [move the runtime access outside and pass values as arguments](/docs/app/getting-started/caching#working-with-runtime-apis) is not practical.
- Compliance requirements prevent storing certain data on the server, even temporarily - Compliance requirements prevent storing certain data on the server, even temporarily
Because this directive accesses runtime data, the function executes on every server render and is excluded from running during [static shell](/docs/app/getting-started/cache-components#how-rendering-works-with-cache-components) generation. Because this directive accesses runtime data, the function executes on every server render and is excluded from running during [static shell](/docs/app/getting-started/caching#how-rendering-works) generation.
It is **not** possible to configure custom cache handlers for `'use cache: private'`. It is **not** possible to configure custom cache handlers for `'use cache: private'`.
For a comparison of the different cache directives, see [How `use cache: remote` differs from `use cache` and `use cache: private`](/docs/app/api-reference/directives/use-cache-remote#how-use-cache-remote-differs-from-use-cache-and-use-cache-private). For a comparison of the different cache directives, see [How `use cache: remote` differs from `use cache` and `use cache: private`](/docs/app/api-reference/directives/use-cache-remote#how-use-cache-remote-differs-from-use-cache-and-use-cache-private).
> **Good to know**: This directive is marked as `experimental` because it depends on runtime prefetching, which is not yet stable. Runtime prefetching is an upcoming feature that will let the router prefetch past the [static shell](/docs/app/getting-started/cache-components#how-rendering-works-with-cache-components) into **any** cached scope, not just private caches. > **Good to know**: This directive is marked as `experimental` because it depends on runtime prefetching, which is not yet stable. Runtime prefetching is an upcoming feature that will let the router prefetch past the [static shell](/docs/app/getting-started/caching#how-rendering-works) into **any** cached scope, not just private caches.
## Usage ## Usage
...@@ -154,7 +154,7 @@ async function getRecommendations(productId) { ...@@ -154,7 +154,7 @@ async function getRecommendations(productId) {
} }
``` ```
> **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work. See [`cacheLife` client router cache behavior](/docs/app/api-reference/functions/cacheLife#client-router-cache-behavior) for details. > **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior) for details.
## Request APIs allowed in private caches ## Request APIs allowed in private caches
......
...@@ -90,7 +90,7 @@ Next.js provides three caching directives, each designed for different use cases ...@@ -90,7 +90,7 @@ Next.js provides three caching directives, each designed for different use cases
### Caching with runtime data ### Caching with runtime data
Both `use cache` and `'use cache: remote'` can't access runtime values like cookies or search params directly. You can extract these values and pass them as arguments to cached functions. See [with runtime data](/docs/app/getting-started/cache-components#with-runtime-data) for this pattern. Both `use cache` and `'use cache: remote'` can't access runtime values like cookies or search params directly. You can extract these values and pass them as arguments to cached functions. See [with runtime data](/docs/app/getting-started/caching#working-with-runtime-apis) for this pattern.
> **Good to know**: `use cache` stores entries in-memory. In serverless environments, memory is not shared between instances and is typically destroyed after serving a request, leading to frequent cache misses for runtime caching. > **Good to know**: `use cache` stores entries in-memory. In serverless environments, memory is not shared between instances and is typically destroyed after serving a request, leading to frequent cache misses for runtime caching.
......
...@@ -191,13 +191,13 @@ async function CachedForm({ action }: { action: () => Promise<void> }) { ...@@ -191,13 +191,13 @@ async function CachedForm({ action }: { action: () => Promise<void> }) {
Cached functions execute in an isolated environment. The following constraints ensure cache behavior remains predictable and secure. Cached functions execute in an isolated environment. The following constraints ensure cache behavior remains predictable and secure.
### Runtime APIs ### Request-time APIs
Cached functions and components **cannot** directly access runtime APIs like `cookies()`, `headers()`, or `searchParams`. Instead, read these values outside the cached scope and pass them as arguments. Cached functions and components **cannot** directly access runtime APIs like `cookies()`, `headers()`, or `searchParams`. Instead, read these values outside the cached scope and pass them as arguments.
### Runtime caching considerations ### Runtime caching considerations
While `use cache` is designed primarily to include dynamic data in the static shell, it can also cache data at runtime using in-memory LRU (Least Recently Used) storage. While `use cache` is designed primarily to include uncached data in the static shell, it can also cache data at runtime using in-memory LRU (Least Recently Used) storage.
Runtime cache behavior depends on your hosting environment: Runtime cache behavior depends on your hosting environment:
...@@ -307,7 +307,7 @@ Both `cacheLife` and `cacheTag` integrate across client and server caching layer ...@@ -307,7 +307,7 @@ Both `cacheLife` and `cacheTag` integrate across client and server caching layer
### Caching an entire route with `use cache` ### Caching an entire route with `use cache`
To pre-render an entire route, add `use cache` to the top of **both** the `layout` and `page` files. Each of these segments are treated as separate entry points in your application, and will be cached independently. To prerender an entire route, add `use cache` to the top of **both** the `layout` and `page` files. Each of these segments are treated as separate entry points in your application, and will be cached independently.
```tsx filename="app/layout.tsx" switcher ```tsx filename="app/layout.tsx" switcher
'use cache' 'use cache'
...@@ -570,11 +570,11 @@ In development, console logs from cached functions appear with a `Cache` prefix. ...@@ -570,11 +570,11 @@ In development, console logs from cached functions appear with a `Cache` prefix.
### Build Hangs (Cache Timeout) ### Build Hangs (Cache Timeout)
If your build hangs, you're accessing Promises that resolve to dynamic or runtime data, created outside a `use cache` boundary. The cached function waits for data that can't resolve during the build, causing a timeout after 50 seconds. If your build hangs, you're accessing Promises that resolve to uncached or runtime data, created outside a `use cache` boundary. The cached function waits for data that can't resolve during the build, causing a timeout after 50 seconds.
When the build timeouts you'll see this error message: When the build timeouts you'll see this error message:
> Error: Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or dynamic data were used inside "use cache". > Error: Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or uncached data were used inside "use cache".
Common ways this happens: passing such Promises as props, accessing them via closure, or retrieving them from shared storage (Maps). Common ways this happens: passing such Promises as props, accessing them via closure, or retrieving them from shared storage (Maps).
......
...@@ -401,6 +401,6 @@ export default async function PostPage({ params }) { ...@@ -401,6 +401,6 @@ export default async function PostPage({ params }) {
} }
``` ```
See the [Server Actions](/docs/app/getting-started/updating-data) docs for more examples. See the [Server Actions](/docs/app/getting-started/mutating-data) docs for more examples.
</AppOnly> </AppOnly>
...@@ -166,10 +166,10 @@ export default function Icon() { ...@@ -166,10 +166,10 @@ export default function Icon() {
> **Good to know**: > **Good to know**:
> >
> - By default, generated icons are [**statically optimized**](/docs/app/guides/caching#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) or uncached data. > - By default, generated icons are [**statically optimized**](/docs/app/glossary#prerendering) (generated at build time and cached) unless they use [Request-time APIs](/docs/app/glossary#request-time-apis) or uncached data.
> - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
> - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead. > - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead.
> - App icons are special Route Handlers that are cached by default unless they use a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > - App icons are special Route Handlers that are cached by default unless they use a [Request-time API](/docs/app/glossary#request-time-apis) or [dynamic config](/docs/app/guides/caching-without-cache-components#dynamic) option.
### Props ### Props
......
...@@ -21,7 +21,7 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif ...@@ -21,7 +21,7 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif
Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object). Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object).
> Good to know: `manifest.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > Good to know: `manifest.js` is a special Route Handlers that is cached by default unless it uses a [Request-time API](/docs/app/glossary#request-time-apis) or [dynamic config](/docs/app/guides/caching-without-cache-components#dynamic) option.
```ts filename="app/manifest.ts" switcher ```ts filename="app/manifest.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -88,9 +88,9 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi ...@@ -88,9 +88,9 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi
> **Good to know**: > **Good to know**:
> >
> - By default, generated images are [**statically optimized**](/docs/app/guides/caching#static-rendering) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) or uncached data. > - By default, generated images are [**statically optimized**](/docs/app/glossary#prerendering) (generated at build time and cached) unless they use [Request-time APIs](/docs/app/glossary#request-time-apis) or uncached data.
> - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata).
> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Request-time API](/docs/app/glossary#request-time-apis) or [dynamic config](/docs/app/guides/caching-without-cache-components#dynamic) option.
The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`. The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`.
...@@ -330,7 +330,7 @@ export default function Image() {} ...@@ -330,7 +330,7 @@ export default function Image() {}
This example uses the `params` object and external data to generate the image. This example uses the `params` object and external data to generate the image.
> **Good to know**: > **Good to know**:
> By default, this generated image will be [statically optimized](/docs/app/guides/caching#static-rendering). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior. > By default, this generated image will be statically optimized. You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/guides/caching-without-cache-components#route-segment-config-revalidate) to change this behavior.
```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher ```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
......
...@@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml ...@@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml
Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object). Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object).
> **Good to know**: `robots.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > **Good to know**: `robots.js` is a special Route Handler that is cached by default unless it uses a [Request-time API](/docs/app/glossary#request-time-apis) or [dynamic config](/docs/app/guides/caching-without-cache-components#dynamic) option.
```ts filename="app/robots.ts" switcher ```ts filename="app/robots.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -41,7 +41,7 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th ...@@ -41,7 +41,7 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th
You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available. You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available.
> **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Request-time API](/docs/app/glossary#request-time-apis) or [dynamic config](/docs/app/guides/caching-without-cache-components#dynamic) option.
```ts filename="app/sitemap.ts" switcher ```ts filename="app/sitemap.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -146,7 +146,7 @@ export default async function Page(props: PageProps<'/[locale]'>) { ...@@ -146,7 +146,7 @@ export default async function Page(props: PageProps<'/[locale]'>) {
### With Cache Components ### With Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components) with dynamic route segments, how you handle params depends on whether you use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). When using [Cache Components](/docs/app/getting-started/caching) with dynamic route segments, how you handle params depends on whether you use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params).
Without `generateStaticParams`, param values are unknown during prerendering, making params runtime data. You must wrap param access in `<Suspense>` boundaries to provide fallback UI. Without `generateStaticParams`, param values are unknown during prerendering, making params runtime data. You must wrap param access in `<Suspense>` boundaries to provide fallback UI.
...@@ -293,7 +293,7 @@ async function PrivatePost({ slug }: { slug: string }) { ...@@ -293,7 +293,7 @@ async function PrivatePost({ slug }: { slug: string }) {
### With `generateStaticParams` ### With `generateStaticParams`
The [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) function can be used to [statically generate](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time. The [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) function can be used to [statically generate](/docs/app/glossary#prerendering) routes at build time instead of on-demand at request time.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
export async function generateStaticParams() { export async function generateStaticParams() {
...@@ -315,7 +315,7 @@ export async function generateStaticParams() { ...@@ -315,7 +315,7 @@ export async function generateStaticParams() {
} }
``` ```
When using `fetch` inside the `generateStaticParams` function, the requests are [automatically deduplicated](/docs/app/guides/caching#request-memoization). This avoids multiple network calls for the same data Layouts, Pages, and other `generateStaticParams` functions, speeding up build time. When using `fetch` inside the `generateStaticParams` function, the requests are [automatically deduplicated](/docs/app/glossary#memoization). This avoids multiple network calls for the same data Layouts, Pages, and other `generateStaticParams` functions, speeding up build time.
### Dynamic GET Route Handlers with `generateStaticParams` ### Dynamic GET Route Handlers with `generateStaticParams`
......
...@@ -47,7 +47,7 @@ Loading UI components do not accept any parameters. ...@@ -47,7 +47,7 @@ Loading UI components do not accept any parameters.
### Instant Loading States ### Instant Loading States
An instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience. An instant loading state is fallback UI that is shown immediately upon navigation. You can prerender loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience.
Create a loading state by adding a `loading.js` file inside a folder. Create a loading state by adding a `loading.js` file inside a folder.
......
...@@ -115,7 +115,7 @@ export default function Page({ searchParams }) { ...@@ -115,7 +115,7 @@ export default function Page({ searchParams }) {
- Since the `searchParams` prop is a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access the values. - Since the `searchParams` prop is a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access the values.
- In version 14 and earlier, `searchParams` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `searchParams` was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- `searchParams` is a **[Dynamic API](/docs/app/guides/caching#dynamic-rendering)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/guides/caching#dynamic-rendering)** at request time. - `searchParams` is a **[Request-time API](/docs/app/glossary#request-time-apis)** whose values cannot be known ahead of time. Using it will opt the page into **[dynamic rendering](/docs/app/glossary#dynamic-rendering)** at request time.
- `searchParams` is a plain JavaScript object, not a `URLSearchParams` instance. - `searchParams` is a plain JavaScript object, not a `URLSearchParams` instance.
### Page Props Helper ### Page Props Helper
......
...@@ -66,7 +66,7 @@ export default function Layout({ children, team, analytics }) { ...@@ -66,7 +66,7 @@ export default function Layout({ children, team, analytics }) {
} }
``` ```
However, slots are **not** route segments and do not affect the URL structure. For example, for `/@analytics/views`, the URL will be `/views` since `@analytics` is a slot. Slots are combined with the regular [Page](/docs/app/api-reference/file-conventions/page) component to form the final page associated with the route segment. Because of this, you cannot have separate [static](/docs/app/guides/caching#static-rendering) and [dynamic](/docs/app/guides/caching#dynamic-rendering) slots at the same route segment level. If one slot is dynamic, all slots at that level must be dynamic. However, slots are **not** route segments and do not affect the URL structure. For example, for `/@analytics/views`, the URL will be `/views` since `@analytics` is a slot. Slots are combined with the regular [Page](/docs/app/api-reference/file-conventions/page) component to form the final page associated with the route segment. Because of this, you cannot have separate [prerendered](/docs/app/glossary#prerendering) and [dynamically rendered](/docs/app/glossary#dynamic-rendering) slots at the same route segment level. If one slot is dynamic, all slots at that level must be dynamic.
> **Good to know**: > **Good to know**:
> >
...@@ -307,7 +307,7 @@ export default function Page() { ...@@ -307,7 +307,7 @@ export default function Page() {
> **Good to know:** > **Good to know:**
> >
> - The convention `(.)` is used for intercepting routes. See [Intercepting Routes](/docs/app/api-reference/file-conventions/intercepting-routes#convention) docs for more information. > - The convention `(.)` is used for intercepting routes. See [Intercepting Routes](/docs/app/api-reference/file-conventions/intercepting-routes#convention) docs for more information.
> - By separating the `<Modal>` functionality from the modal content (`<Login>`), you can ensure any content inside the modal, e.g. [forms](/docs/app/guides/forms), are Server Components. See [Interleaving Client and Server Components](/docs/app/getting-started/server-and-client-components#examples#supported-pattern-passing-server-components-to-client-components-as-props) for more information. > - By separating the `<Modal>` functionality from the modal content (`<Login>`), you can ensure any content inside the modal, e.g. [forms](/docs/app/guides/forms), are Server Components. See [Interleaving Client and Server Components](/docs/app/getting-started/server-and-client-components#interleaving-server-and-client-components) for more information.
#### Opening the modal #### Opening the modal
......
...@@ -338,7 +338,7 @@ export async function GET(request, { params }) { ...@@ -338,7 +338,7 @@ export async function GET(request, { params }) {
You can use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) with dynamic Route Handlers to statically generate responses at build time for specified params, while handling other params dynamically at request time. You can use [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) with dynamic Route Handlers to statically generate responses at build time for specified params, while handling other params dynamically at request time.
When using [Cache Components](/docs/app/getting-started/cache-components), you can combine `generateStaticParams` with `use cache` to enable data caching for both prerendered and runtime params. When using [Cache Components](/docs/app/getting-started/caching), you can combine `generateStaticParams` with `use cache` to enable data caching for both prerendered and runtime params.
See the [generateStaticParams with Route Handlers](/docs/app/api-reference/functions/generate-static-params#with-route-handlers) documentation for examples and details. See the [generateStaticParams with Route Handlers](/docs/app/api-reference/functions/generate-static-params#with-route-handlers) documentation for examples and details.
......
...@@ -5,7 +5,7 @@ description: API Reference for the after function. ...@@ -5,7 +5,7 @@ description: API Reference for the after function.
`after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics. `after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics.
It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)), [Server Functions](/docs/app/getting-started/updating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Proxy](/docs/app/api-reference/file-conventions/proxy). It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)), [Server Functions](/docs/app/getting-started/mutating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Proxy](/docs/app/api-reference/file-conventions/proxy).
The function accepts a callback that will be executed after the response (or prerender) is finished: The function accepts a callback that will be executed after the response (or prerender) is finished:
...@@ -37,7 +37,7 @@ export default function Layout({ children }) { ...@@ -37,7 +37,7 @@ export default function Layout({ children }) {
} }
``` ```
> **Good to know:** `after` is not a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) and calling it does not cause a route to become dynamic. If it's used within a static page, the callback will execute at build time, or whenever a page is revalidated. > **Good to know:** `after` is not a [Request-time API](/docs/app/glossary#request-time-apis) and calling it does not cause a route to become dynamic. If it's used within a static page, the callback will execute at build time, or whenever a page is revalidated.
## Reference ## Reference
...@@ -63,7 +63,7 @@ Whether you can use request APIs like [`cookies`](/docs/app/api-reference/functi ...@@ -63,7 +63,7 @@ Whether you can use request APIs like [`cookies`](/docs/app/api-reference/functi
#### In Route Handlers and Server Functions #### In Route Handlers and Server Functions
You can call `cookies` and `headers` directly inside the `after` callback when used in [Route Handlers](/docs/app/api-reference/file-conventions/route) and [Server Functions](/docs/app/getting-started/updating-data). This is useful for logging activity after a mutation or API request. For example: You can call `cookies` and `headers` directly inside the `after` callback when used in [Route Handlers](/docs/app/api-reference/file-conventions/route) and [Server Functions](/docs/app/getting-started/mutating-data). This is useful for logging activity after a mutation or API request. For example:
```ts filename="app/api/route.ts" highlight={2,10-16} switcher ```ts filename="app/api/route.ts" highlight={2,10-16} switcher
import { after } from 'next/server' import { after } from 'next/server'
...@@ -117,7 +117,7 @@ export async function POST(request) { ...@@ -117,7 +117,7 @@ export async function POST(request) {
#### In Server Components (pages and layouts) #### In Server Components (pages and layouts)
[Server Components](/docs/app/getting-started/server-and-client-components) (including pages, layouts, and `generateMetadata`) **cannot** use `cookies`, `headers`, or other [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) inside `after`. This is because Next.js needs to know which part of the component tree accesses request data to support [Partial Prerendering](/docs/app/glossary#partial-prerendering-ppr) and [Cache Components](/docs/app/getting-started/cache-components), but `after` runs after React's rendering lifecycle. [Server Components](/docs/app/getting-started/server-and-client-components) (including pages, layouts, and `generateMetadata`) **cannot** use `cookies`, `headers`, or other Request-time APIs inside `after`. This is because Next.js needs to know which part of the component tree accesses request data to support [Partial Prerendering](/docs/app/glossary#partial-prerendering-ppr) and [Cache Components](/docs/app/getting-started/caching), but `after` runs after React's rendering lifecycle.
If you need request data inside an `after` callback in a Server Component, read it beforehand and pass the values in: If you need request data inside an `after` callback in a Server Component, read it beforehand and pass the values in:
...@@ -167,7 +167,7 @@ Calling `cookies()` or `headers()` inside the `after` callback in a Server Compo ...@@ -167,7 +167,7 @@ Calling `cookies()` or `headers()` inside the `after` callback in a Server Compo
#### With Cache Components #### With Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components), components that access request data like `cookies` or `headers` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the rest of the page can be prerendered into a static shell. When using [Cache Components](/docs/app/getting-started/caching), components that access request data like `cookies` or `headers` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the rest of the page can be prerendered into a static shell.
You can combine this pattern with `after` by reading request data in a dynamic component and passing it into `after`: You can combine this pattern with `after` by reading request data in a dynamic component and passing it into `after`:
......
...@@ -237,9 +237,9 @@ Inline profiles apply only to the specific function or component. For reusable c ...@@ -237,9 +237,9 @@ Inline profiles apply only to the specific function or component. For reusable c
Using `cacheLife({})` with an empty object applies the `default` profile values. Using `cacheLife({})` with an empty object applies the `default` profile values.
### Client router cache behavior ### Client cache behavior
The `stale` property controls the client-side router cache, not the `Cache-Control` header: The `stale` property controls the [Client Cache](/docs/app/glossary#client-cache), not the `Cache-Control` header:
- The server sends the stale time via the `x-nextjs-stale-time` response header - The server sends the stale time via the `x-nextjs-stale-time` response header
- The client router uses this value to determine when to revalidate - The client router uses this value to determine when to revalidate
......
...@@ -59,7 +59,7 @@ export async function getData() { ...@@ -59,7 +59,7 @@ export async function getData() {
} }
``` ```
You can then purge the cache on-demand using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) API in another function, for example, a [route handler](/docs/app/api-reference/file-conventions/route) or [Server Action](/docs/app/getting-started/updating-data): You can then purge the cache on-demand using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) API in another function, for example, a [route handler](/docs/app/api-reference/file-conventions/route) or [Server Action](/docs/app/getting-started/mutating-data):
```tsx filename="app/action.ts" switcher ```tsx filename="app/action.ts" switcher
'use server' 'use server'
......
...@@ -5,7 +5,7 @@ description: API Reference for the connection function. ...@@ -5,7 +5,7 @@ description: API Reference for the connection function.
The `connection()` function allows you to indicate rendering should wait for an incoming user request before continuing. The `connection()` function allows you to indicate rendering should wait for an incoming user request before continuing.
It's useful when a component doesn't use [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering), but you want it to be dynamically rendered at runtime and not statically rendered at build time. This usually occurs when you access external information that you intentionally want to change the result of a render, such as `Math.random()` or `new Date()`. It's useful when a component doesn't use [Request-time APIs](/docs/app/glossary#request-time-apis), but you want it to be rendered at runtime and not prerendered at build time. This usually occurs when you access external information that you intentionally want to change the result of a render, such as `Math.random()` or `new Date()`.
```ts filename="app/page.tsx" switcher ```ts filename="app/page.tsx" switcher
import { connection } from 'next/server' import { connection } from 'next/server'
...@@ -48,7 +48,7 @@ function connection(): Promise<void> ...@@ -48,7 +48,7 @@ function connection(): Promise<void>
## Good to know ## Good to know
- `connection` replaces [`unstable_noStore`](/docs/app/api-reference/functions/unstable_noStore) to better align with the future of Next.js. - `connection` replaces [`unstable_noStore`](/docs/app/api-reference/functions/unstable_noStore) to better align with the future of Next.js.
- The function is only necessary when dynamic rendering is required and common Dynamic APIs are not used. - The function is only necessary when dynamic rendering is required and common Request-time APIs are not used.
### Version History ### Version History
......
...@@ -3,7 +3,7 @@ title: cookies ...@@ -3,7 +3,7 @@ title: cookies
description: API Reference for the cookies function. description: API Reference for the cookies function.
--- ---
`cookies` is an **async** function that allows you to read the HTTP incoming request cookies in [Server Components](/docs/app/getting-started/server-and-client-components), and read/write outgoing request cookies in [Server Functions](/docs/app/getting-started/updating-data) or [Route Handlers](/docs/app/api-reference/file-conventions/route). `cookies` is an **async** function that allows you to read the HTTP incoming request cookies in [Server Components](/docs/app/getting-started/server-and-client-components), and read/write outgoing request cookies in [Server Functions](/docs/app/getting-started/mutating-data) or [Route Handlers](/docs/app/api-reference/file-conventions/route).
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
...@@ -66,11 +66,11 @@ To learn more about these options, see the [MDN docs](https://developer.mozilla. ...@@ -66,11 +66,11 @@ To learn more about these options, see the [MDN docs](https://developer.mozilla.
- `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access cookies. - `cookies` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function to access cookies.
- In version 14 and earlier, `cookies` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `cookies` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- `cookies` is a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into [dynamic rendering](/docs/app/guides/caching#dynamic-rendering). - `cookies` is a [Request-time API](/docs/app/glossary#request-time-apis) whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into [dynamic rendering](/docs/app/glossary#dynamic-rendering).
- The `.delete` method can only be called: - The `.delete` method can only be called:
- In a [Server Function](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route). - In a [Server Function](/docs/app/getting-started/mutating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
- If it belongs to the same domain from which `.set` is called. For wildcard domains, the specific subdomain must be an exact match. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete. - If it belongs to the same domain from which `.set` is called. For wildcard domains, the specific subdomain must be an exact match. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.
- HTTP does not allow setting cookies after streaming starts, so you must use `.set` in a [Server Function](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route). - HTTP does not allow setting cookies after streaming starts, so you must use `.set` in a [Server Function](/docs/app/getting-started/mutating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route).
## Understanding Cookie Behavior in Server Components ## Understanding Cookie Behavior in Server Components
...@@ -83,7 +83,7 @@ The server can only send instructions (via `Set-Cookie` headers) to tell the bro ...@@ -83,7 +83,7 @@ The server can only send instructions (via `Set-Cookie` headers) to tell the bro
## Understanding Cookie Behavior in Server Functions ## Understanding Cookie Behavior in Server Functions
After you set or delete a cookie in a Server Function, Next.js can return both the updated UI and new data in a single server roundtrip when the function is used as a [Server Action](/docs/app/getting-started/updating-data#what-are-server-functions) (e.g., passed to a form's `action` prop). See the [Caching guide](/docs/app/guides/caching#cookies). After you set or delete a cookie in a Server Function, Next.js can return both the updated UI and new data in a single server roundtrip when the function is used as a [Server Action](/docs/app/getting-started/mutating-data#what-are-server-functions) (e.g., passed to a form's `action` prop). See [Caching and Revalidating](/docs/app/getting-started/caching).
The UI is not unmounted, but effects that depend on data coming from the server will re-run. The UI is not unmounted, but effects that depend on data coming from the server will re-run.
...@@ -149,7 +149,7 @@ export default async function Page() { ...@@ -149,7 +149,7 @@ export default async function Page() {
### Setting a cookie ### Setting a cookie
You can use the `(await cookies()).set(name, value, options)` method in a [Server Function](/docs/app/getting-started/updating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route) to set a cookie. The [`options` object](#options) is optional. You can use the `(await cookies()).set(name, value, options)` method in a [Server Function](/docs/app/getting-started/mutating-data) or [Route Handler](/docs/app/api-reference/file-conventions/route) to set a cookie. The [`options` object](#options) is optional.
```tsx filename="app/actions.ts" switcher ```tsx filename="app/actions.ts" switcher
'use server' 'use server'
......
...@@ -5,7 +5,7 @@ description: API reference for the extended fetch function. ...@@ -5,7 +5,7 @@ description: API reference for the extended fetch function.
Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching and revalidation semantics. Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching and revalidation semantics.
In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent [Data Cache](/docs/app/guides/caching#data-cache). In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent cache.
You can call `fetch` with `async` and `await` directly within Server Components. You can call `fetch` with `async` and `await` directly within Server Components.
...@@ -43,15 +43,15 @@ Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs ...@@ -43,15 +43,15 @@ Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs
### `options.cache` ### `options.cache`
Configure how the request should interact with Next.js [Data Cache](/docs/app/guides/caching#data-cache). Configure how the request should interact with Next.js [caching](/docs/app/getting-started/caching).
```ts ```ts
fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
``` ```
- **`auto no cache`** (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during `next build` because the route will be statically prerendered. If [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) are detected on the route, Next.js will fetch the resource on every request. - **`auto no cache`** (default): Next.js fetches the resource from the remote server on every request in development, but will fetch once during `next build` because the route will be statically prerendered. If [Request-time APIs](/docs/app/glossary#request-time-apis) are detected on the route, Next.js will fetch the resource on every request.
- **`no-store`**: Next.js fetches the resource from the remote server on every request, even if Dynamic APIs are not detected on the route. - **`no-store`**: Next.js fetches the resource from the remote server on every request, even if Request-time APIs are not detected on the route.
- **`force-cache`**: Next.js looks for a matching request in its Data Cache. - **`force-cache`**: Next.js looks for a matching request in its server-side cache.
- If there is a match and it is fresh, it will be returned from the cache. - If there is a match and it is fresh, it will be returned from the cache.
- If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource. - If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.
...@@ -61,7 +61,7 @@ fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) ...@@ -61,7 +61,7 @@ fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
fetch(`https://...`, { next: { revalidate: false | 0 | number } }) fetch(`https://...`, { next: { revalidate: false | 0 | number } })
``` ```
Set the cache lifetime of a resource (in seconds). [Data Cache](/docs/app/guides/caching#data-cache). Set the cache lifetime of a resource (in seconds).
- **`false`** - Cache the resource indefinitely. Semantically equivalent to `revalidate: Infinity`. The HTTP cache may evict older resources over time. - **`false`** - Cache the resource indefinitely. Semantically equivalent to `revalidate: Infinity`. The HTTP cache may evict older resources over time.
- **`0`** - Prevent the resource from being cached. - **`0`** - Prevent the resource from being cached.
...@@ -69,7 +69,7 @@ Set the cache lifetime of a resource (in seconds). [Data Cache](/docs/app/guides ...@@ -69,7 +69,7 @@ Set the cache lifetime of a resource (in seconds). [Data Cache](/docs/app/guides
> **Good to know**: > **Good to know**:
> >
> - If an individual `fetch()` request sets a `revalidate` number lower than the [default `revalidate`](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) of a route, the whole route revalidation interval will be decreased. > - If an individual `fetch()` request sets a `revalidate` number lower than the [default `revalidate`](/docs/app/guides/caching-without-cache-components#route-segment-config-revalidate) of a route, the whole route revalidation interval will be decreased.
> - If two fetch requests with the same URL in the same route have different `revalidate` values, the lower value will be used. > - If two fetch requests with the same URL in the same route have different `revalidate` values, the lower value will be used.
> - Conflicting options such as `{ revalidate: 3600, cache: 'no-store' }` are not allowed, both will be ignored, and in development mode a warning will be printed to the terminal. > - Conflicting options such as `{ revalidate: 3600, cache: 'no-store' }` are not allowed, both will be ignored, and in development mode a warning will be printed to the terminal.
...@@ -81,6 +81,19 @@ fetch(`https://...`, { next: { tags: ['collection'] } }) ...@@ -81,6 +81,19 @@ fetch(`https://...`, { next: { tags: ['collection'] } })
Set the cache tags of a resource. Data can then be revalidated on-demand using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag). The max length for a custom tag is 256 characters and the max tag items is 128. Set the cache tags of a resource. Data can then be revalidated on-demand using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag). The max length for a custom tag is 256 characters and the max tag items is 128.
## Memoization
`fetch` requests using `GET` with the same URL and options are automatically [memoized](/docs/app/glossary#memoization) during a server render pass. If you call the same `fetch` in multiple Server Components, layouts, pages, `generateStaticParams` and `generateViewport`, Next.js executes it only once and shares the result.
To opt out, pass an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) signal to `fetch`:
```js
const { signal } = new AbortController()
fetch(url, { signal })
```
> **Good to know**: Memoization does not apply in [Route Handlers](/docs/app/api-reference/file-conventions/route), since they are not part of the React component tree.
## Troubleshooting ## Troubleshooting
### Fetch default `auto no store` and `cache: 'no-store'` not showing fresh data in development ### Fetch default `auto no store` and `cache: 'no-store'` not showing fresh data in development
......
...@@ -31,7 +31,7 @@ module.exports = { ...@@ -31,7 +31,7 @@ module.exports = {
} }
``` ```
`forbidden` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/updating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route). `forbidden` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/mutating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route).
```tsx filename="app/auth/page.tsx" switcher ```tsx filename="app/auth/page.tsx" switcher
import { verifySession } from '@/app/lib/dal' import { verifySession } from '@/app/lib/dal'
......
...@@ -7,7 +7,7 @@ related: ...@@ -7,7 +7,7 @@ related:
links: links:
- app/api-reference/file-conventions/metadata - app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport - app/api-reference/functions/generate-viewport
- app/getting-started/cache-components - app/getting-started/caching
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
--- ---
...@@ -43,7 +43,7 @@ export default function Page() {} ...@@ -43,7 +43,7 @@ export default function Page() {}
Dynamic metadata depends on **dynamic information**, such as the current route parameters, external data, or `metadata` in parent segments, can be set by exporting a `generateMetadata` function that returns a [`Metadata` object](#metadata-fields). Dynamic metadata depends on **dynamic information**, such as the current route parameters, external data, or `metadata` in parent segments, can be set by exporting a `generateMetadata` function that returns a [`Metadata` object](#metadata-fields).
Resolving `generateMetadata` is part of rendering the page. If the page can be pre-rendered and `generateMetadata` doesn't introduce dynamic behavior, the resulting metadata is included in the page’s initial HTML. Resolving `generateMetadata` is part of rendering the page. If the page can be prerendered and `generateMetadata` doesn't introduce dynamic behavior, the resulting metadata is included in the page's initial HTML.
Otherwise the metadata resolved from `generateMetadata` [can be streamed](/docs/app/api-reference/functions/generate-metadata#streaming-metadata) after sending the initial UI. Otherwise the metadata resolved from `generateMetadata` [can be streamed](/docs/app/api-reference/functions/generate-metadata#streaming-metadata) after sending the initial UI.
...@@ -109,8 +109,8 @@ For type completion of `params` and `searchParams`, you can type the first argum ...@@ -109,8 +109,8 @@ For type completion of `params` and `searchParams`, you can type the first argum
> - Next.js will automatically resolve the metadata, and create the relevant `<head>` tags for the page. > - Next.js will automatically resolve the metadata, and create the relevant `<head>` tags for the page.
> - The `metadata` object and `generateMetadata` function exports are **only supported in Server Components**. > - The `metadata` object and `generateMetadata` function exports are **only supported in Server Components**.
> - You cannot export both the `metadata` object and `generateMetadata` function from the same route segment. > - You cannot export both the `metadata` object and `generateMetadata` function from the same route segment.
> - `fetch` requests inside `generateMetadata` are automatically [memoized](/docs/app/guides/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. > - `fetch` requests inside `generateMetadata` are automatically [memoized](/docs/app/glossary#memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components.
> - React [`cache` can be used](/docs/app/guides/caching#react-cache-function) if `fetch` is unavailable. > - React [`cache` can be used](https://react.dev/reference/react/cache) if `fetch` is unavailable.
> - [File-based metadata](/docs/app/api-reference/file-conventions/metadata) has the higher priority and will override the `metadata` object and `generateMetadata` function. > - [File-based metadata](/docs/app/api-reference/file-conventions/metadata) has the higher priority and will override the `metadata` object and `generateMetadata` function.
## Why `generateMetadata` is Server Component only ## Why `generateMetadata` is Server Component only
...@@ -191,8 +191,8 @@ export function InteractiveComponent() { ...@@ -191,8 +191,8 @@ export function InteractiveComponent() {
> **Good to know**: > **Good to know**:
> >
> - If metadata doesn't depend on runtime information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`. > - If metadata doesn't depend on request information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`.
> - `fetch` requests are automatically [memoized](/docs/app/guides/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/guides/caching#react-cache-function) if `fetch` is unavailable. > - `fetch` requests are automatically memoized for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](https://react.dev/reference/react/cache) if `fetch` is unavailable.
> - `searchParams` are only available in `page.js` segments. > - `searchParams` are only available in `page.js` segments.
> - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`. > - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`.
...@@ -1253,7 +1253,7 @@ Overriding `htmlLimitedBots` could lead to longer response times. Streaming meta ...@@ -1253,7 +1253,7 @@ Overriding `htmlLimitedBots` could lead to longer response times. Streaming meta
### With Cache Components ### With Cache Components
When [Cache Components](/docs/app/getting-started/cache-components) is enabled, `generateMetadata` follows the same rules as other components. If metadata accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time. When [Cache Components](/docs/app/getting-started/caching) is enabled, `generateMetadata` follows the same rules as other components. If metadata accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time.
How Next.js handles this depends on the rest of your page: How Next.js handles this depends on the rest of your page:
......
...@@ -3,7 +3,7 @@ title: generateStaticParams ...@@ -3,7 +3,7 @@ title: generateStaticParams
description: API reference for the generateStaticParams function. description: API reference for the generateStaticParams function.
--- ---
The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/guides/caching#static-rendering) routes at build time instead of on-demand at request time. The `generateStaticParams` function can be used in combination with [dynamic route segments](/docs/app/api-reference/file-conventions/dynamic-routes) to [**statically generate**](/docs/app/glossary#prerendering) routes at build time instead of on-demand at request time.
`generateStaticParams` can be used with: `generateStaticParams` can be used with:
...@@ -54,7 +54,7 @@ export default async function Page({ params }) { ...@@ -54,7 +54,7 @@ export default async function Page({ params }) {
> **Good to know**: > **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 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/api-reference/file-conventions/route-segment-config#dynamic) in order to revalidate (ISR) [paths at runtime](#all-paths-at-runtime). > - 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).
> - During `next dev`, `generateStaticParams` will be called when you navigate to a route. > - 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 `next build`, `generateStaticParams` runs before the corresponding Layouts or Pages are generated.
> - During revalidation (ISR), `generateStaticParams` will not be called again. > - During revalidation (ISR), `generateStaticParams` will not be called again.
...@@ -205,7 +205,7 @@ export default async function Page({ params }) { ...@@ -205,7 +205,7 @@ export default async function Page({ params }) {
## Examples ## Examples
### Static Rendering ### Prerendering
#### All paths at build time #### All paths at build time
...@@ -289,7 +289,7 @@ export async function generateStaticParams() { ...@@ -289,7 +289,7 @@ export async function generateStaticParams() {
#### All paths at runtime #### All paths at runtime
To statically render all paths the first time they're visited, return an empty array (no paths will be rendered at build time) or utilize [`export const dynamic = 'force-static'`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic): To statically render all paths the first time they're visited, return an empty array (no paths will be rendered at build time) or utilize [`export const dynamic = 'force-static'`](/docs/app/guides/caching-without-cache-components#dynamic):
```jsx filename="app/blog/[slug]/page.js" ```jsx filename="app/blog/[slug]/page.js"
export async function generateStaticParams() { export async function generateStaticParams() {
...@@ -307,7 +307,7 @@ export const dynamic = 'force-static' ...@@ -307,7 +307,7 @@ export const dynamic = 'force-static'
#### With Cache Components #### With Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components) with dynamic routes, `generateStaticParams` must return **at least one param**. Empty arrays cause a [build error](/docs/messages/empty-generate-static-params). This allows Cache Components to validate your route doesn't incorrectly access `cookies()`, `headers()`, or `searchParams` at runtime. When using [Cache Components](/docs/app/getting-started/caching) with dynamic routes, `generateStaticParams` must return **at least one param**. Empty arrays cause a [build error](/docs/messages/empty-generate-static-params). This allows Cache Components to validate your route doesn't incorrectly access `cookies()`, `headers()`, or `searchParams` at runtime.
> **Good to know**: If you don't know the actual param values at build time, you can return a placeholder param (e.g., `[{ slug: '__placeholder__' }]`) for validation, then handle it in your page with `notFound()`. However, this prevents build time validation from working effectively and may cause runtime errors. > **Good to know**: If you don't know the actual param values at build time, you can return a placeholder param (e.g., `[{ slug: '__placeholder__' }]`) for validation, then handle it in your page with `notFound()`. However, this prevents build time validation from working effectively and may cause runtime errors.
...@@ -346,7 +346,7 @@ export async function GET(request, { params }) { ...@@ -346,7 +346,7 @@ export async function GET(request, { params }) {
### Route Handlers with Cache Components ### Route Handlers with Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components), combine with `use cache` for optimal caching: When using [Cache Components](/docs/app/getting-started/caching), combine with `use cache` for optimal caching:
```ts filename="app/api/posts/[id]/route.ts" ```ts filename="app/api/posts/[id]/route.ts"
export async function generateStaticParams() { export async function generateStaticParams() {
...@@ -373,7 +373,7 @@ See the [Route Handlers documentation](/docs/app/api-reference/file-conventions/ ...@@ -373,7 +373,7 @@ See the [Route Handlers documentation](/docs/app/api-reference/file-conventions/
### Disable rendering for unspecified paths ### Disable rendering for unspecified paths
To prevent unspecified paths from being statically rendered at runtime, add the `export const dynamicParams = false` option in a route segment. When this config option is used, only paths provided by `generateStaticParams` will be served, and unspecified routes will 404 or match (in the case of [catch-all routes](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments)). To prevent unspecified paths from being prerendered at runtime, add the `export const dynamicParams = false` option in a route segment. When this config option is used, only paths provided by `generateStaticParams` will be served, and unspecified routes will 404 or match (in the case of [catch-all routes](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments)).
### Multiple Dynamic Segments in a Route ### Multiple Dynamic Segments in a Route
...@@ -530,7 +530,7 @@ export async function generateStaticParams({ ...@@ -530,7 +530,7 @@ export async function generateStaticParams({
} }
``` ```
> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/guides/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/guides/caching#react-cache-function) if `fetch` is unavailable. > **Good to know**: `fetch` requests are automatically [memoized](/docs/app/glossary#memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](https://react.dev/reference/react/cache) if `fetch` is unavailable.
## Version History ## Version History
......
...@@ -6,7 +6,7 @@ related: ...@@ -6,7 +6,7 @@ related:
description: View all the Metadata API options. description: View all the Metadata API options.
links: links:
- app/api-reference/file-conventions/metadata - app/api-reference/file-conventions/metadata
- app/getting-started/cache-components - app/getting-started/caching
- app/api-reference/config/next-config-js/cacheComponents - app/api-reference/config/next-config-js/cacheComponents
--- ---
...@@ -64,7 +64,7 @@ export function generateViewport({ params }) { ...@@ -64,7 +64,7 @@ export function generateViewport({ params }) {
> **Good to know**: > **Good to know**:
> >
> - If the viewport doesn't depend on runtime information, it should be defined using the static [`viewport` object](#the-viewport-object) rather than `generateViewport`. > - If the viewport doesn't depend on request information, it should be defined using the static [`viewport` object](#the-viewport-object) rather than `generateViewport`.
## Viewport Fields ## Viewport Fields
...@@ -178,7 +178,7 @@ export const viewport = { ...@@ -178,7 +178,7 @@ export const viewport = {
## With Cache Components ## With Cache Components
When [Cache Components](/docs/app/getting-started/cache-components) is enabled, `generateViewport` follows the same rules as other components. If viewport accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time. When [Cache Components](/docs/app/getting-started/caching) is enabled, `generateViewport` follows the same rules as other components. If viewport accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time.
Unlike metadata, viewport cannot be streamed because it affects initial page load UI. If `generateViewport` defers to request time, the page would need to block until resolved. Unlike metadata, viewport cannot be streamed because it affects initial page load UI. If `generateViewport` defers to request time, the page would need to block until resolved.
......
...@@ -45,7 +45,7 @@ export default async function Page() { ...@@ -45,7 +45,7 @@ export default async function Page() {
- `headers` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function. - `headers` is an **asynchronous** function that returns a promise. You must use `async/await` or React's [`use`](https://react.dev/reference/react/use) function.
- In version 14 and earlier, `headers` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future. - In version 14 and earlier, `headers` was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
- Since `headers` is read-only, you cannot `set` or `delete` the outgoing request headers. - Since `headers` is read-only, you cannot `set` or `delete` the outgoing request headers.
- `headers` is a [Dynamic API](/docs/app/guides/caching#dynamic-rendering) whose returned values cannot be known ahead of time. Using it in will opt a route into **[dynamic rendering](/docs/app/guides/caching#dynamic-rendering)**. - `headers` is a [Request-time API](/docs/app/glossary#request-time-apis) whose returned values cannot be known ahead of time. Using it in will opt a route into **[dynamic rendering](/docs/app/glossary#dynamic-rendering)**.
## Examples ## Examples
......
...@@ -6,7 +6,7 @@ related: ...@@ -6,7 +6,7 @@ related:
- app/api-reference/functions/redirect - app/api-reference/functions/redirect
--- ---
The `permanentRedirect` function allows you to redirect the user to another URL. `permanentRedirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/updating-data). The `permanentRedirect` function allows you to redirect the user to another URL. `permanentRedirect` can be used in Server Components, Client Components, [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data).
When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 308 (Permanent) HTTP redirect response to the caller. When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 308 (Permanent) HTTP redirect response to the caller.
...@@ -27,7 +27,7 @@ permanentRedirect(path, type) ...@@ -27,7 +27,7 @@ permanentRedirect(path, type)
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/updating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/mutating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
The `RedirectType` object contains the available options for the `type` parameter. The `RedirectType` object contains the available options for the `type` parameter.
......
...@@ -6,7 +6,7 @@ related: ...@@ -6,7 +6,7 @@ related:
- app/api-reference/functions/permanentRedirect - app/api-reference/functions/permanentRedirect
--- ---
The `redirect` function allows you to redirect the user to another URL. `redirect` can be used while rendering in [Server and Client Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/updating-data). The `redirect` function allows you to redirect the user to another URL. `redirect` can be used while rendering in [Server and Client Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Server Functions](/docs/app/getting-started/mutating-data).
When used in a [streaming context](/docs/app/getting-started/linking-and-navigating#streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller. When used in a [streaming context](/docs/app/getting-started/linking-and-navigating#streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller.
...@@ -27,7 +27,7 @@ redirect(path, type) ...@@ -27,7 +27,7 @@ redirect(path, type)
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/updating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/mutating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
The `RedirectType` object contains the available options for the `type` parameter. The `RedirectType` object contains the available options for the `type` parameter.
......
...@@ -3,7 +3,7 @@ title: refresh ...@@ -3,7 +3,7 @@ title: refresh
description: API Reference for the refresh function. description: API Reference for the refresh function.
--- ---
`refresh` allows you to refresh the client router from within a [Server Action](/docs/app/getting-started/updating-data). `refresh` allows you to refresh the client router from within a [Server Action](/docs/app/getting-started/mutating-data).
## Usage ## Usage
......
...@@ -3,7 +3,7 @@ title: revalidatePath ...@@ -3,7 +3,7 @@ title: revalidatePath
description: API Reference for the revalidatePath function. description: API Reference for the revalidatePath function.
--- ---
`revalidatePath` allows you to invalidate [cached data](/docs/app/guides/caching) on-demand for a specific path. `revalidatePath` allows you to invalidate [cached data](/docs/app/getting-started/caching) on-demand for a specific path.
## Usage ## Usage
...@@ -37,7 +37,7 @@ The path parameter can point to pages, layouts, or route handlers: ...@@ -37,7 +37,7 @@ The path parameter can point to pages, layouts, or route handlers:
- **Pages**: Invalidates the specific page - **Pages**: Invalidates the specific page
- **Layouts**: Invalidates the layout (the `layout.tsx` at that segment), all nested layouts beneath it, and all pages beneath them - **Layouts**: Invalidates the layout (the `layout.tsx` at that segment), all nested layouts beneath it, and all pages beneath them
- **Route Handlers**: Invalidates Data Cache entries accessed within route handlers. For example `revalidatePath("/api/data")` invalidates this GET handler: - **Route Handlers**: Invalidates cached data accessed within route handlers. For example `revalidatePath("/api/data")` invalidates this GET handler:
```ts filename="app/api/data/route.ts" ```ts filename="app/api/data/route.ts"
export async function GET() { export async function GET() {
...@@ -169,7 +169,7 @@ import { revalidatePath } from 'next/cache' ...@@ -169,7 +169,7 @@ import { revalidatePath } from 'next/cache'
revalidatePath('/', 'layout') revalidatePath('/', 'layout')
``` ```
This will purge the Client-side Router Cache, and invalidate the Data Cache for revalidation on the next page visit. This will purge the [Client Cache](/docs/app/glossary#client-cache), and invalidate all cached data for revalidation on the next page visit.
### Server Function ### Server Function
......
...@@ -3,7 +3,7 @@ title: revalidateTag ...@@ -3,7 +3,7 @@ title: revalidateTag
description: API Reference for the revalidateTag function. description: API Reference for the revalidateTag function.
--- ---
`revalidateTag` allows you to invalidate [cached data](/docs/app/guides/caching) on-demand for a specific cache tag. `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. Users receive stale content while fresh data loads in the background.
...@@ -34,7 +34,7 @@ revalidateTag(tag: string, profile: string | { expire?: number }): void; ...@@ -34,7 +34,7 @@ revalidateTag(tag: string, profile: string | { expire?: number }): void;
Tags must first be assigned to cached data. You can do this in two ways: Tags must first be assigned to cached data. You can do this in two ways:
- Using the [`next.tags`](/docs/app/guides/caching#fetch-optionsnexttags-and-revalidatetag) option with `fetch` for caching external API requests: - Using the [`next.tags`](/docs/app/api-reference/functions/fetch) option with `fetch` for caching external API requests:
```tsx ```tsx
fetch(url, { next: { tags: ['posts'] } }) fetch(url, { next: { tags: ['posts'] } })
......
...@@ -31,7 +31,7 @@ module.exports = { ...@@ -31,7 +31,7 @@ module.exports = {
} }
``` ```
`unauthorized` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/updating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route). `unauthorized` can be invoked in [Server Components](/docs/app/getting-started/server-and-client-components), [Server Functions](/docs/app/getting-started/mutating-data), and [Route Handlers](/docs/app/api-reference/file-conventions/route).
```tsx filename="app/dashboard/page.tsx" switcher ```tsx filename="app/dashboard/page.tsx" switcher
import { verifySession } from '@/app/lib/dal' import { verifySession } from '@/app/lib/dal'
......
...@@ -5,7 +5,7 @@ description: API Reference for the unstable_cache function. ...@@ -5,7 +5,7 @@ description: API Reference for the unstable_cache function.
> **Note:** > **Note:**
> This API has been replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) in Next.js 16. > This API has been replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) in Next.js 16.
> We recommend opting into [Cache Components](/docs/app/getting-started/cache-components) and replacing `unstable_cache` with the `use cache` directive. > We recommend opting into [Cache Components](/docs/app/getting-started/caching) and replacing `unstable_cache` with the `use cache` directive.
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests. `unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
...@@ -26,8 +26,8 @@ export default async function Component({ userID }) { ...@@ -26,8 +26,8 @@ export default async function Component({ userID }) {
> **Good to know**: > **Good to know**:
> >
> - Accessing dynamic data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required dynamic data in as an argument. > - Accessing uncached data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required uncached data in as an argument.
> - This API uses Next.js' built-in [Data Cache](/docs/app/guides/caching#data-cache) to persist the result across requests and deployments. > - This API uses Next.js' built-in cache to persist the result across requests and deployments. See [Caching and Revalidating](/docs/app/getting-started/caching).
## Parameters ## Parameters
......
...@@ -6,7 +6,7 @@ version: legacy ...@@ -6,7 +6,7 @@ version: legacy
**In version 15, we recommend using [`connection`](/docs/app/api-reference/functions/connection) instead of `unstable_noStore`.** **In version 15, we recommend using [`connection`](/docs/app/api-reference/functions/connection) instead of `unstable_noStore`.**
`unstable_noStore` can be used to declaratively opt out of static rendering and indicate a particular component should not be cached. `unstable_noStore` can be used to declaratively opt out of prerendering and indicate a particular component should not be cached.
```jsx ```jsx
import { unstable_noStore as noStore } from 'next/cache'; import { unstable_noStore as noStore } from 'next/cache';
......
...@@ -49,7 +49,7 @@ The following Next.js APIs rely on throwing an error which should be rethrown an ...@@ -49,7 +49,7 @@ The following Next.js APIs rely on throwing an error which should be rethrown an
- [`redirect()`](/docs/app/guides/redirecting#redirect-function) - [`redirect()`](/docs/app/guides/redirecting#redirect-function)
- [`permanentRedirect()`](/docs/app/guides/redirecting#permanentredirect-function) - [`permanentRedirect()`](/docs/app/guides/redirecting#permanentredirect-function)
If a route segment is marked to throw an error unless it's static, a Dynamic API call will also throw an error that should similarly not be caught by the developer. Note that Partial Prerendering (PPR) affects this behavior as well. These APIs are: If a route segment is marked to throw an error unless it's static, a Request-time API call will also throw an error that should similarly not be caught by the developer. Note that Partial Prerendering (PPR) affects this behavior as well. These APIs are:
- [`cookies`](/docs/app/api-reference/functions/cookies) - [`cookies`](/docs/app/api-reference/functions/cookies)
- [`headers`](/docs/app/api-reference/functions/headers) - [`headers`](/docs/app/api-reference/functions/headers)
......
...@@ -3,13 +3,13 @@ title: updateTag ...@@ -3,13 +3,13 @@ title: updateTag
description: API Reference for the updateTag function. description: API Reference for the updateTag function.
--- ---
`updateTag` allows you to update [cached data](/docs/app/guides/caching) on-demand for a specific cache tag from within [Server Actions](/docs/app/getting-started/updating-data). `updateTag` allows you to update cached data on-demand for a specific cache tag from within [Server Actions](/docs/app/getting-started/mutating-data).
This function is designed for **read-your-own-writes** scenarios, where a user makes a change (like creating a post), and the UI immediately shows the change, rather than stale data. This function is designed for **read-your-own-writes** scenarios, where a user makes a change (like creating a post), and the UI immediately shows the change, rather than stale data.
## Usage ## Usage
`updateTag` can **only** be called from within [Server Actions](/docs/app/getting-started/updating-data). It cannot be used in Route Handlers, Client Components, or any other context. `updateTag` can **only** be called from within [Server Actions](/docs/app/getting-started/mutating-data). It cannot be used in Route Handlers, Client Components, or any other context.
If you need to invalidate cache tags in Route Handlers or other contexts, use [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead. If you need to invalidate cache tags in Route Handlers or other contexts, use [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead.
...@@ -25,7 +25,7 @@ updateTag(tag: string): void; ...@@ -25,7 +25,7 @@ updateTag(tag: string): void;
Tags must first be assigned to cached data. You can do this in two ways: Tags must first be assigned to cached data. You can do this in two ways:
- Using the [`next.tags`](/docs/app/guides/caching#fetch-optionsnexttags-and-revalidatetag) option with `fetch` for caching external API requests: - Using the [`next.tags`](/docs/app/api-reference/functions/fetch) option with `fetch` for caching external API requests:
```tsx ```tsx
fetch(url, { next: { tags: ['posts'] } }) fetch(url, { next: { tags: ['posts'] } })
......
...@@ -36,7 +36,7 @@ For example, a Client Component with `usePathname` will be rendered into HTML on ...@@ -36,7 +36,7 @@ For example, a Client Component with `usePathname` will be rendered into HTML on
> **Good to know**: > **Good to know**:
> >
> - Reading the current URL from a [Server Component](/docs/app/getting-started/server-and-client-components) is not supported. This design is intentional to support layout state being preserved across page navigations. > - Reading the current URL from a [Server Component](/docs/app/getting-started/server-and-client-components) is not supported. This design is intentional to support layout state being preserved across page navigations.
> - If your page is being statically pre-rendered and your app has [rewrites](/docs/app/api-reference/config/next-config-js/rewrites) in `next.config` or a [Proxy](/docs/app/api-reference/file-conventions/proxy) file, reading the pathname with `usePathname()` can result in hydration mismatch errors—because the initial value comes from the server and may not match the actual browser pathname after routing. See our [example](#avoid-hydration-mismatch-with-rewrites) for a way to mitigate this issue. > - If your page is being statically prerendered and your app has [rewrites](/docs/app/api-reference/config/next-config-js/rewrites) in `next.config` or a [Proxy](/docs/app/api-reference/file-conventions/proxy) file, reading the pathname with `usePathname()` can result in hydration mismatch errors—because the initial value comes from the server and may not match the actual browser pathname after routing. See our [example](#avoid-hydration-mismatch-with-rewrites) for a way to mitigate this issue.
<details> <details>
...@@ -103,7 +103,7 @@ function ExampleClientComponent() { ...@@ -103,7 +103,7 @@ function ExampleClientComponent() {
### Avoid hydration mismatch with rewrites ### Avoid hydration mismatch with rewrites
When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Proxy`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client. When a page is prerendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Proxy`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client.
To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount. To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount.
......
...@@ -400,7 +400,7 @@ However, you can set `Cache-Control` headers for other responses or data. ...@@ -400,7 +400,7 @@ However, you can set `Cache-Control` headers for other responses or data.
<AppOnly> <AppOnly>
Learn more about [caching](/docs/app/guides/caching) with the App Router. Learn more about [caching](/docs/app/getting-started/caching) with the App Router.
</AppOnly> </AppOnly>
......
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