Unverified Commit d44ee523 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs(opengraph-image): load assets at module scope to keep route static under…

docs(opengraph-image): load assets at module scope to keep route static under Cache Components (#95246)

### What?

Document loading request-independent assets at module scope, and update
the OG image examples to follow it.

### Why?

Reading a local asset inside the component is async I/O during render,
so the route defers to request time. A top-level `await` at module scope
keeps the route prerendered without reaching for `use cache`. The
pattern previously only lived as an inline snippet in the OG image docs.

### How?

- Add an "Asynchronous I/O at module scope" section to the Cache
Components guide as the canonical explanation.
- Load fonts and local assets at module scope in `opengraph-image.mdx`
and `image-response.mdx`, and link both to the new section.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarJoseph <joseph.chamochumbi@vercel.com>
parent 34d92a50
...@@ -382,9 +382,9 @@ You don't need to memorize which operations behave this way. The dev overlay sur ...@@ -382,9 +382,9 @@ You don't need to memorize which operations behave this way. The dev overlay sur
/> />
</FixCardGrid> </FixCardGrid>
## Synchronous I/O and pure computations ## Predictable values
Unlike random or time-based APIs, synchronous I/O, module imports, and pure computations are predictable: the same inputs produce the same outputs. Components using only these operations are prerendered automatically, and their output becomes part of the static HTML at build time. Unlike random values and timestamps, which can vary between renders, module imports, synchronous I/O, and pure computations produce the same result every time they run. Components using only these operations are prerendered automatically, and their output becomes part of the static HTML at build time.
```tsx filename="page.tsx" ```tsx filename="page.tsx"
import fs from 'node:fs' import fs from 'node:fs'
...@@ -409,13 +409,36 @@ export default async function Page() { ...@@ -409,13 +409,36 @@ export default async function Page() {
> **Good to know:** This includes queries to embedded databases with synchronous APIs, such as `better-sqlite3` or Node.js's built-in [`node:sqlite`](https://nodejs.org/api/sqlite.html). If you need per-request data from a synchronous source, call [`connection()`](/docs/app/api-reference/functions/connection) before the query. > **Good to know:** This includes queries to embedded databases with synchronous APIs, such as `better-sqlite3` or Node.js's built-in [`node:sqlite`](https://nodejs.org/api/sqlite.html). If you need per-request data from a synchronous source, call [`connection()`](/docs/app/api-reference/functions/connection) before the query.
Some asynchronous APIs read local resources that don't depend on the incoming request, such as fonts or configuration files. When those resources are expected to be the same for every request, read them once at module scope instead of during rendering
If the data should instead be computed during rendering and reused across requests, wrap the read in [`use cache`](/docs/app/api-reference/directives/use-cache). If the data depends on the incoming request or is expected to change over time, read it during request-time rendering.
```tsx filename="page.tsx"
import { readFile } from 'node:fs/promises'
const content = await readFile('./config.json', 'utf-8')
const items = JSON.parse(content).items ?? []
export default function Page() {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.value}</li>
))}
</ul>
)
}
```
In this example, the configuration file is expected to be the same for every request, so it is read once at module scope. Calling `await readFile()` inside the component would be treated as uncached data that must be either accessed within `use cache` or behind a `<Suspense>` boundary. Since this file does not depend on the request and is not expected to change, module scope is the simplest option.
## Prerendering ## Prerendering
At build time, Next.js renders your route's component tree. How each component is handled depends on the APIs it uses: At build time, Next.js renders your route's component tree. How each component is handled depends on the APIs it uses:
- [`use cache`](#usage): the result is cached and included in the static shell, as long as its lifetime [isn't too short](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) - [`use cache`](#usage): the result is cached and included in the static shell, as long as its lifetime [isn't too short](/docs/app/api-reference/functions/cacheLife#prerendering-behavior)
- [`<Suspense>`](#streaming-uncached-data): fallback UI is included in the static shell while the content streams at request time - [`<Suspense>`](#streaming-uncached-data): fallback UI is included in the static shell while the content streams at request time
- [Synchronous I/O and pure computations](#synchronous-io-and-pure-computations): module imports, `fs.readFileSync`, and pure computations complete during prerender and are included in the static shell automatically - [Predictable values](#predictable-values): module imports, `fs.readFileSync`, and pure computations complete during prerender and are included in the static shell automatically
- [Random values and timestamps](#random-values-and-timestamps): use `connection()` + `<Suspense>` to get a unique value per request, or `use cache` to share one across users - [Random values and timestamps](#random-values-and-timestamps): use `connection()` + `<Suspense>` to get a unique value per request, or `use cache` to share one across users
This generates a static shell consisting of HTML for initial page loads and a serialized [RSC Payload](/docs/app/getting-started/server-and-client-components#on-the-server) for client-side navigation, ensuring the browser receives fully rendered content instantly whether users navigate directly to the URL or transition from another page. This rendering approach is called **Partial Prerendering (PPR)**, the default behavior with Cache Components. This generates a static shell consisting of HTML for initial page loads and a serialized [RSC Payload](/docs/app/getting-started/server-and-client-components#on-the-server) for client-side navigation, ensuring the browser receives fully rendered content instantly whether users navigate directly to the URL or transition from another page. This rendering approach is called **Partial Prerendering (PPR)**, the default behavior with Cache Components.
......
...@@ -108,13 +108,12 @@ export const size = { ...@@ -108,13 +108,12 @@ export const size = {
export const contentType = 'image/png' export const contentType = 'image/png'
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
// Image generation // Image generation
export default async function Image() { export default async function Image() {
// Font loading, process.cwd() is Next.js project directory
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
return new ImageResponse( return new ImageResponse(
( (
// ImageResponse JSX element // ImageResponse JSX element
...@@ -164,13 +163,12 @@ export const size = { ...@@ -164,13 +163,12 @@ export const size = {
export const contentType = 'image/png' export const contentType = 'image/png'
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
// Image generation // Image generation
export default async function Image() { export default async function Image() {
// Font loading, process.cwd() is Next.js project directory
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
return new ImageResponse( return new ImageResponse(
( (
// ImageResponse JSX element // ImageResponse JSX element
...@@ -418,15 +416,17 @@ export default async function Image({ params }) { ...@@ -418,15 +416,17 @@ export default async function Image({ params }) {
These examples use the Node.js runtime to fetch a local image from the file system and pass it to the `<img>` `src` attribute, either as a base64 string or an `ArrayBuffer`. Place the local asset relative to the project root, not the example source file. These examples use the Node.js runtime to fetch a local image from the file system and pass it to the `<img>` `src` attribute, either as a base64 string or an `ArrayBuffer`. Place the local asset relative to the project root, not the example source file.
The asset doesn't depend on request data, so read it once at module scope. See [Predictable values](/docs/app/getting-started/caching#predictable-values).
```tsx filename="app/opengraph-image.tsx" switcher ```tsx filename="app/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
import { join } from 'node:path' import { join } from 'node:path'
import { readFile } from 'node:fs/promises' import { readFile } from 'node:fs/promises'
export default async function Image() { const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64')
const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64') const logoSrc = `data:image/png;base64,${logoData}`
const logoSrc = `data:image/png;base64,${logoData}`
export default async function Image() {
return new ImageResponse( return new ImageResponse(
( (
<div <div
...@@ -448,10 +448,10 @@ import { ImageResponse } from 'next/og' ...@@ -448,10 +448,10 @@ import { ImageResponse } from 'next/og'
import { join } from 'node:path' import { join } from 'node:path'
import { readFile } from 'node:fs/promises' import { readFile } from 'node:fs/promises'
export default async function Image() { const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64')
const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64') const logoSrc = `data:image/png;base64,${logoData}`
const logoSrc = `data:image/png;base64,${logoData}`
export default async function Image() {
return new ImageResponse( return new ImageResponse(
( (
<div <div
...@@ -475,10 +475,10 @@ import { ImageResponse } from 'next/og' ...@@ -475,10 +475,10 @@ import { ImageResponse } from 'next/og'
import { join } from 'node:path' import { join } from 'node:path'
import { readFile } from 'node:fs/promises' import { readFile } from 'node:fs/promises'
export default async function Image() { const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoData = await readFile(join(process.cwd(), 'logo.png')) const logoSrc = Uint8Array.from(logoData).buffer
const logoSrc = Uint8Array.from(logoData).buffer
export default async function Image() {
return new ImageResponse( return new ImageResponse(
( (
<div <div
...@@ -501,10 +501,10 @@ import { ImageResponse } from 'next/og' ...@@ -501,10 +501,10 @@ import { ImageResponse } from 'next/og'
import { join } from 'node:path' import { join } from 'node:path'
import { readFile } from 'node:fs/promises' import { readFile } from 'node:fs/promises'
export default async function Image() { const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoData = await readFile(join(process.cwd(), 'logo.png')) const logoSrc = Uint8Array.from(logoData).buffer
const logoSrc = Uint8Array.from(logoData).buffer
export default async function Image() {
return new ImageResponse( return new ImageResponse(
( (
<div <div
......
...@@ -158,7 +158,7 @@ export default async function Image() { ...@@ -158,7 +158,7 @@ export default async function Image() {
### Custom fonts ### Custom fonts
You can use custom fonts in your `ImageResponse` by providing a `fonts` array in the options. You can use custom fonts in your `ImageResponse` by providing a `fonts` array in the options. The font doesn't depend on request data, so read it once at module scope. See [Predictable values](/docs/app/getting-started/caching#predictable-values).
```tsx filename="app/opengraph-image.tsx" ```tsx filename="app/opengraph-image.tsx"
import { ImageResponse } from 'next/og' import { ImageResponse } from 'next/og'
...@@ -174,9 +174,6 @@ export const size = { ...@@ -174,9 +174,6 @@ export const size = {
export const contentType = 'image/png' export const contentType = 'image/png'
// Load the font once at module scope. process.cwd() is the Next.js project
// directory. Reading it inside the component would be treated as dynamic I/O
// under Cache Components and opt the route out of static generation.
const interSemiBold = await readFile( const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf') join(process.cwd(), 'assets/Inter-SemiBold.ttf')
) )
......
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