Unverified Commit b0dde9cf authored by Joseph's avatar Joseph Committed by GitHub

docs: expand io reference (#95147)

Rewrites the `io()` API reference around what it expresses: with Cache
Components `await io()` keeps the operation that follow afterward out of
the static shell.

Adds Server/Client usage examples and a composition note, a "When you
don't need `io()`" section, and reframes the `connection()` comparison
around prefetching.

---------
Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
parent 1d8e8381
...@@ -81,6 +81,7 @@ function connection(): Promise<void> ...@@ -81,6 +81,7 @@ function connection(): Promise<void>
- `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 Request-time APIs are not used. - The function is only necessary when dynamic rendering is required and common Request-time APIs are not used.
- With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), prefer [`io()`](/docs/app/api-reference/functions/io) for excluding content from the static shell. It works the same way but can also be cached and prefetched. Reach for `connection()` only when rendering should wait for a real user request.
### Version History ### Version History
......
--- ---
title: io title: io
description: API Reference for the io function. description: API Reference for the io function.
version: draft
--- ---
`io()` informs Next.js that an IO operation will follow this call. When [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is not enabled or when rendering in Pages Router, signifying IO in this way is not meaningful and the call will always resolve immediately. When Cache Components is enabled, you may be required to add `await io()` preceding synchronous IO that is encountered while prerendering pages (`new Date()` for example). Additionally, if you want to avoid having genuine uncached IO invoked while prerendering, you shield it by preceeding it with `await io()`. When [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled, Next.js needs you to decide whether to capture a synchronous value like `new Date()` or `Math.random()` once and reuse it for every visitor, or produce it fresh for each request.
```ts filename="app/page.tsx" switcher To capture the value in the [static shell](/docs/app/glossary#static-shell), wrap it in [`"use cache"`](/docs/app/api-reference/directives/use-cache). To keep it out of the static shell, use `await io()`, which suspends during prerendering.
During a request, inside cached scopes, in the browser, and apps without Cache Components (including the Pages Router), calling `io()` resolves immediately.
## Usage
Call `io()` to inform Next.js that an IO operation follows.
In a Server Component, call `await io()` before reading a value like `new Date()`, `Math.random()`, `crypto.randomUUID()`, or a synchronous database driver such as [`node:sqlite`](https://nodejs.org/api/sqlite.html):
```tsx filename="app/page.tsx" highlight={13} switcher
import { Suspense } from 'react'
import { io } from 'next/cache' import { io } from 'next/cache'
import { db } from '@/lib/db'
export default async function Page() { export default function Page() {
// Synchronous IO: new Date() would fail during prerender without this return (
<Suspense fallback={<p>Loading...</p>}>
<CurrentTime />
</Suspense>
)
}
async function CurrentTime() {
await io() await io()
const now = new Date().toISOString() return <p>{new Date().toISOString()}</p>
}
```
// Async IO: the query would run and be discarded during prerender; ```jsx filename="app/page.js" highlight={13} switcher
// io() above lets Next.js skip it entirely import { Suspense } from 'react'
const orders = await db.query('SELECT * FROM orders LIMIT 10') import { io } from 'next/cache'
export default function Page() {
return ( return (
<main> <Suspense fallback={<p>Loading...</p>}>
<p>Generated at: {now}</p> <CurrentTime />
<ul> </Suspense>
{orders.map((order) => (
<li key={order.id}>{order.name}</li>
))}
</ul>
</main>
) )
} }
async function CurrentTime() {
await io()
return <p>{new Date().toISOString()}</p>
}
``` ```
```js filename="app/page.js" switcher In this route `CurrentTime` is wrapped in a `<Suspense>` boundary, during prerender, the `await io()` suspends and the fallback ships in the static shell. If `CurrentTime` were rendered inside a [`"use cache"`](/docs/app/api-reference/directives/use-cache) scope instead, `io()` would be a no-op, the value is captured into the static shell and no `<Suspense>` boundary is required.
In a Client Component, call `io()` with React's [`use`](https://react.dev/reference/react/use) hook before reading a synchronous source like `Date.now()`. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell:
```tsx filename="app/components.tsx" highlight={6} switcher
'use client'
import { use } from 'react'
import { io } from 'next/cache' import { io } from 'next/cache'
import { db } from '@/lib/db'
export default async function Page() { export function CurrentTime() {
// Synchronous IO: new Date() would fail during prerender without this use(io())
await io() return <div>{Date.now()}</div>
const now = new Date().toISOString() }
```
// Async IO: the query would run and be discarded during prerender; ```jsx filename="app/components.js" highlight={6} switcher
// io() above lets Next.js skip it entirely 'use client'
const orders = await db.query('SELECT * FROM orders LIMIT 10') import { use } from 'react'
import { io } from 'next/cache'
return ( export function CurrentTime() {
<main> use(io())
<p>Generated at: {now}</p> return <div>{Date.now()}</div>
<ul>
{orders.map((order) => (
<li key={order.id}>{order.name}</li>
))}
</ul>
</main>
)
} }
``` ```
## How is this different from `connection()`? ## When you don't need `io()`
[`connection()`](/docs/app/api-reference/functions/connection) requires an active HTTP request context and signals that the component needs request-specific data. It is imported from `next/server`. - The component already uses a [Request-time API](/docs/app/glossary#request-time-apis) like `cookies()` or `headers()`. The request-time API is itself the suspension point.
- The data comes from an awaited `fetch` or async database query wrapped in `<Suspense>`. The `await` is the suspension point.
`io()` does not require a request context. It can be used inside `"use cache"` scopes, client components, and anywhere you perform IO that should not be included in a static prerender. It is imported from `next/cache`. ## How `io()` differs from `connection()`
Use `connection()` when you need the request itself (cookies, headers, etc.). Use `io()` when you perform IO that is independent of the request but should still prevent static prerendering. The [`connection()`](/docs/app/api-reference/functions/connection) function excludes the code that follows it from the static shell, but it stays suspended until a full user navigation reaches the server, so it also blocks [prefetches](/docs/app/guides/prefetching). `io()` suspends like any other asynchronous function, so the code after it can be wrapped in [`"use cache"`](/docs/app/api-reference/directives/use-cache) and prefetched and cached on the client. Prefer `io()` over `connection()`, and reach for `connection()` only when you need to wait for a real user request.
## Reference ## Reference
...@@ -80,16 +100,10 @@ function io(): Promise<void> ...@@ -80,16 +100,10 @@ function io(): Promise<void>
### Returns ### Returns
- A `Promise<void>` that resolves immediately during a real request or inside a cache scope, and suspends indefinitely during prerendering to prevent static output from including IO-dependent content. A `Promise<void>`. With Cache Components enabled, awaiting this promise stops prerendering so the code that follows is excluded from the prerender output. In every other context (real requests, cache scopes, [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), the browser, and routes without Cache Components), it resolves immediately.
## Good to know
- `io()` is imported from `next/cache`, not `next/server`.
- Inside `"use cache"` scopes, `io()` resolves immediately. The cache captures the IO result at fill time.
- In client components, `io()` resolves immediately since there is no prerender context in the browser.
### Version History ## Version History
| Version | Changes | | Version | Changes |
| --------- | ----------- | | --------- | ----------- |
| `v16.x.x` | `io` added. | | `v16.3.0` | `io` added. |
...@@ -174,6 +174,40 @@ The user sees the placeholder briefly before the real value. For interactions th ...@@ -174,6 +174,40 @@ The user sees the placeholder briefly before the real value. For interactions th
- Only [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) ships to the browser. Node-only APIs (`crypto.randomBytes`, `crypto.generateKeyPairSync`) are not available on the client. If you're seeing this error for one of those, the call lives on the server: see [Crypto APIs during prerendering](/docs/messages/blocking-prerender-crypto). - Only [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) ships to the browser. Node-only APIs (`crypto.randomBytes`, `crypto.generateKeyPairSync`) are not available on the client. If you're seeing this error for one of those, the call lives on the server: see [Crypto APIs during prerendering](/docs/messages/blocking-prerender-crypto).
- When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves. - When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves.
## Other options
### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/request-id.js"
'use client'
import { use } from 'react'
import { io } from 'next/cache'
export function RequestId() {
use(io())
return <span>Request {crypto.randomUUID()}</span>
}
```
Wrap the component in `<Suspense>` so the surrounding shell stays prerendered.
```jsx filename="app/page.js"
import { Suspense } from 'react'
import { RequestId } from './components/request-id'
export default function Page() {
return (
<Suspense fallback={null}>
<RequestId />
</Suspense>
)
}
```
Learn more: [`io()`](/docs/app/api-reference/functions/io).
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `crypto.randomUUID()` and related APIs return a different value on every call, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
......
...@@ -75,7 +75,7 @@ export async function CsrfToken() { ...@@ -75,7 +75,7 @@ export async function CsrfToken() {
#### Alternative: `await io()` #### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/csrf-token.js" ```jsx filename="app/dashboard/csrf-token.js"
import { io } from 'next/cache' import { io } from 'next/cache'
......
...@@ -217,6 +217,38 @@ export default async function Layout({ children }) { ...@@ -217,6 +217,38 @@ export default async function Layout({ children }) {
Learn more: [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time). Learn more: [`Date.now()` during prerendering](/docs/messages/blocking-prerender-current-time).
### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/last-updated.js"
'use client'
import { use } from 'react'
import { io } from 'next/cache'
export function LastUpdated() {
use(io())
return <span>Updated at {new Date().toLocaleTimeString()}</span>
}
```
Wrap the component in `<Suspense>` so the surrounding shell stays prerendered.
```jsx filename="app/page.js"
import { Suspense } from 'react'
import { LastUpdated } from './components/last-updated'
export default function Page() {
return (
<Suspense fallback={null}>
<LastUpdated />
</Suspense>
)
}
```
Learn more: [`io()`](/docs/app/api-reference/functions/io).
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `new Date()` and `Date.now()` return a different value on every render, so the prerender can't bake them into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
......
...@@ -85,7 +85,7 @@ export async function UpdatedAt() { ...@@ -85,7 +85,7 @@ export async function UpdatedAt() {
#### Alternative: `await io()` #### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/updated-at.js" ```jsx filename="app/dashboard/updated-at.js"
import { io } from 'next/cache' import { io } from 'next/cache'
......
...@@ -167,6 +167,40 @@ The user sees the placeholder briefly before the real value. For interactions th ...@@ -167,6 +167,40 @@ The user sees the placeholder briefly before the real value. For interactions th
- If the value needs to be hydration-stable (the SSR HTML and the hydrated render must match exactly), use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead. - If the value needs to be hydration-stable (the SSR HTML and the hydrated render must match exactly), use [Wrap in or move into Suspense](#wrap-in-or-move-into-suspense) instead.
- When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves. - When you call `setState` from inside [`useEffect`](https://react.dev/reference/react/useEffect), wrap it in [`startTransition`](https://react.dev/reference/react/startTransition). Cascading state updates during hydration can cause an outer [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary's fallback to briefly flash. `startTransition` marks the update as non-blocking so React keeps the existing UI in place while the new value resolves.
## Other options
### Suspend with `use(io())`
When the read genuinely needs to happen per visit and you can't move it to an effect or event, call [`io()`](/docs/app/api-reference/functions/io) from `next/cache` before the read with React's [`use`](https://react.dev/reference/react/use) hook. Client Components prerender on the server during SSR, where the read would otherwise be included in the static shell. `use(io())` suspends the prerender so the component is excluded from the shell and rendered on every request from the nearest [`<Suspense>`](https://react.dev/reference/react/Suspense) boundary.
```jsx filename="app/components/random-banner.js"
'use client'
import { use } from 'react'
import { io } from 'next/cache'
export function RandomBanner() {
use(io())
return <span>Banner #{Math.floor(Math.random() * 100)}</span>
}
```
Wrap the component in `<Suspense>` so the surrounding shell stays prerendered.
```jsx filename="app/page.js"
import { Suspense } from 'react'
import { RandomBanner } from './components/random-banner'
export default function Page() {
return (
<Suspense fallback={null}>
<RandomBanner />
</Suspense>
)
}
```
Learn more: [`io()`](/docs/app/api-reference/functions/io).
## Why `instant = false` doesn't clear this error ## Why `instant = false` doesn't clear this error
This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above. This error fires from the prerender, not from instant-navigation validation. `Math.random()` returns a different value on every render, so the prerender can't bake it into a static shell regardless of the segment's `instant` config or [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults). Use one of the fixes above.
......
...@@ -77,7 +77,7 @@ export async function RequestTrace() { ...@@ -77,7 +77,7 @@ export async function RequestTrace() {
#### Alternative: `await io()` #### Alternative: `await io()`
To avoid tying the read to an HTTP request context, use [`io()`](/docs/app/api-reference/functions/io) from `next/cache`. It marks the read as request-time IO and behaves like `connection()` for streaming, with the added benefit that it also works inside `"use cache"` scopes and Client Components, where `connection()` throws. Use [`io()`](/docs/app/api-reference/functions/io) from `next/cache` to keep the read out of the static shell. Unlike [`connection()`](/docs/app/api-reference/functions/connection), `io()` doesn't block prefetches and works inside `"use cache"` scopes and Client Components.
```jsx filename="app/dashboard/request-trace.js" ```jsx filename="app/dashboard/request-trace.js"
import { io } from 'next/cache' import { io } from 'next/cache'
......
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