Unverified Commit 6dff8853 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

ensure component tree is only rendered once during SSG/revalidations (#67680)

### What
When statically generating a page, Next.js will attempt to render the
application tree twice, resulting in unexpected calls to upstream APIs
and also slowing down the application during build as it needs to make 2
passes for the same data.

### Why
Next.js currently calls React's `renderToReadableStream` API in two
spots: once for the HTML render, and again for the Flight render. This
is because we want to generate a `.rsc` output for statically generated
pages, so that on navigation, we don't need to call the server to
retrieve the flight payload.

### How
Rather than calling `renderToReadableStream` twice, this refactors the
approach to instead only perform it once. This introduces a new type to
describe the response from calls to `createFromFetch`: `RSCPayload`,
including a set of utils to access the relevant payload data, as it can
change depending on calling context.

- During the initial SSR response & when statically generating the
flight payload, this will be an object containing the top-level props
that are used to render `<AppRouter />`
- For dynamic pages, this will only return the diffed component tree,
which is computed by `walkTreeWithFlightRouterState` traversing the
provided `next-router-state-tree` (from the client) to determine where
to start rendering (**this is unchanged from today**)
- For server actions, this will return the action result, in addition to
the same payload as above (**this is also unchanged**)

Fixes #58736
Fixes #43254
Fixes #60562

Closes NDX-17
parent 36e8c2f4
......@@ -172,9 +172,9 @@ const initialServerResponse = createFromReadableStream(readable, {
})
function ServerRoot(): React.ReactNode {
const initialRSCPayload = use<InitialRSCPayload>(initialServerResponse)
const initialResponse = use<InitialRSCPayload>(initialServerResponse)
return <AppRouter initialRSCPayload={initialRSCPayload} />
return <AppRouter initialRSCPayload={initialResponse} />
}
const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP
......
......@@ -214,20 +214,16 @@ function Router({
() =>
createInitialRouterState({
buildId: initialRSCPayload.b,
initialSeedData: initialRSCPayload.d,
initialFlightData: initialRSCPayload.f,
initialCanonicalUrl: initialRSCPayload.c,
initialTree: initialRSCPayload.t,
initialParallelRoutes,
location: !isServer ? window.location : null,
initialHead: initialRSCPayload.h,
couldBeIntercepted: initialRSCPayload.i,
}),
[
initialRSCPayload.b,
initialRSCPayload.c,
initialRSCPayload.t,
initialRSCPayload.d,
initialRSCPayload.h,
initialRSCPayload.f,
initialRSCPayload.i,
]
)
......
......@@ -35,23 +35,23 @@ describe('createInitialRouterState', () => {
const state = createInitialRouterState({
buildId,
initialTree,
initialFlightData: [
[initialTree, ['', {}, children, null], <title>Test</title>],
],
initialCanonicalUrl,
initialSeedData: ['', {}, children, null],
initialParallelRoutes,
location: new URL('/linking', 'https://localhost') as any,
initialHead: <title>Test</title>,
couldBeIntercepted: false,
})
const state2 = createInitialRouterState({
buildId,
initialTree,
initialFlightData: [
[initialTree, ['', {}, children, null], <title>Test</title>],
],
initialCanonicalUrl,
initialSeedData: ['', {}, children, null],
initialParallelRoutes,
location: new URL('/linking', 'https://localhost') as any,
initialHead: <title>Test</title>,
})
const expectedCache: CacheNode = {
......
import type { ReactNode } from 'react'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type {
FlightRouterState,
CacheNodeSeedData,
FlightData,
} from '../../../server/app-render/types'
import type { FlightDataPath } from '../../../server/app-render/types'
import { createHrefFromUrl } from './create-href-from-url'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
......@@ -15,25 +10,24 @@ import { addRefreshMarkerToActiveParallelSegments } from './refetch-inactive-par
export interface InitialRouterStateParameters {
buildId: string
initialTree: FlightRouterState
initialCanonicalUrl: string
initialSeedData: CacheNodeSeedData
initialParallelRoutes: CacheNode['parallelRoutes']
initialFlightData: FlightDataPath[]
location: Location | null
initialHead: ReactNode
couldBeIntercepted?: boolean
}
export function createInitialRouterState({
buildId,
initialTree,
initialSeedData,
initialFlightData,
initialCanonicalUrl,
initialParallelRoutes,
location,
initialHead,
couldBeIntercepted,
}: InitialRouterStateParameters) {
// The initialFlightData is an array of FlightDataPath arrays.
// For the root render, there'll only be a top-level FlightDataPath array.
const [initialTree, initialSeedData, initialHead] = initialFlightData[0]
const isServer = !location
const rsc = initialSeedData[2]
......@@ -105,9 +99,6 @@ export function createInitialRouterState({
location.origin
)
const initialFlightData: FlightData = [
[initialTree, initialSeedData, initialHead],
]
createPrefetchCacheEntryForInitialLoad({
url,
kind: PrefetchKind.AUTO,
......
......@@ -14,7 +14,7 @@ const { createFromFetch } = (
import type {
FlightRouterState,
FlightData,
NextFlightResponse,
NavigationFlightResponse,
} from '../../../server/app-render/types'
import {
NEXT_ROUTER_PREFETCH_HEADER,
......@@ -183,14 +183,18 @@ export async function fetchServerResponse(
}
// Handle the `fetch` readable stream that can be unwrapped by `React.use`.
const [buildIdFromResponse, flightData]: NextFlightResponse =
await createFromFetch(Promise.resolve(res), { callServer })
const response: NavigationFlightResponse = await createFromFetch(
Promise.resolve(res),
{
callServer,
}
)
if (buildId !== buildIdFromResponse) {
if (buildId !== response.b) {
return doMpaNavigation(res.url)
}
return [flightData, canonicalUrl, postponed, interception]
return [response.f, canonicalUrl, postponed, interception]
} catch (err) {
console.error(
`Failed to fetch RSC payload for ${url}. Falling back to browser navigation.`,
......
......@@ -120,19 +120,16 @@ async function fetchServerAction(
if (location) {
// if it was a redirection, then result is just a regular RSC payload
const [, actionFlightData] = (response as any) ?? []
return {
actionFlightData: actionFlightData,
actionFlightData: response.f,
redirectLocation,
revalidatedParts,
}
}
// otherwise it's a tuple of [actionResult, actionFlightData]
const [actionResult, [, actionFlightData]] = (response as any) ?? []
return {
actionResult,
actionFlightData,
actionResult: response.a,
actionFlightData: response.f,
redirectLocation,
revalidatedParts,
}
......
import type {
ActionResult,
DynamicParamTypesShort,
FlightData,
FlightRouterState,
FlightSegmentPath,
RenderOpts,
Segment,
CacheNodeSeedData,
PreloadCallbacks,
RSCPayload,
FlightData,
InitialRSCPayload,
} from './types'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
......@@ -143,7 +144,7 @@ type AppRenderBaseContext = {
parsedRequestHeaders: ParsedRequestHeaders
}
export type GenerateFlight = typeof generateFlight
export type GenerateFlight = typeof generateDynamicFlightRenderResult
export type AppRenderContext = AppRenderBaseContext & {
getDynamicParamFromSegment: GetDynamicParamFromSegment
......@@ -317,25 +318,25 @@ function NonIndex({ ctx }: { ctx: AppRenderContext }) {
return null
}
// Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`.
async function generateFlight(
/**
* This is used by server actions & client-side navigations to generate RSC data from a client-side request.
* This function is only called on "dynamic" requests (ie, there wasn't already a static response).
* It uses request headers (namely `Next-Router-State-Tree`) to determine where to start rendering.
*/
async function generateDynamicRSCPayload(
ctx: AppRenderContext,
options?: {
actionResult: ActionResult
skipFlight: boolean
asNotFound?: boolean
}
): Promise<RenderResult> {
): Promise<RSCPayload> {
// Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request.
let flightData: FlightData | null = null
const {
componentMod: {
tree: loaderTree,
renderToReadableStream,
createDynamicallyTrackedSearchParams,
},
componentMod: { tree: loaderTree, createDynamicallyTrackedSearchParams },
getDynamicParamFromSegment,
appUsingSizeAdjustment,
requestStore: { url },
......@@ -344,9 +345,9 @@ async function generateFlight(
flightRouterState,
} = ctx
const preloadCallbacks: PreloadCallbacks = []
if (!options?.skipFlight) {
const preloadCallbacks: PreloadCallbacks = []
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree: loaderTree,
query,
......@@ -382,14 +383,49 @@ async function generateFlight(
).map((path) => path.slice(1)) // remove the '' (root) segment
}
const buildIdFlightDataPair = [ctx.renderOpts.buildId, flightData]
// If we have an action result, then this is a server action response.
// We can rely on this because `ActionResult` will always be a promise, even if
// the result is falsey.
if (options?.actionResult) {
return {
a: options.actionResult,
f: flightData,
b: ctx.renderOpts.buildId,
}
}
// Otherwise, it's a regular RSC response.
return {
b: ctx.renderOpts.buildId,
// Anything besides an action response should have non-null flightData.
// We don't ever expect this to be null because `skipFlight` is only
// used when invoked by a server action, which is covered above.
// The client router can handle an empty string (treating it as an MPA navigation),
// so we'll use that as a fallback.
f: flightData ?? '',
}
}
/**
* Produces a RenderResult containing the Flight data for the given request. See
* `generateDynamicRSCPayload` for information on the contents of the render result.
*/
async function generateDynamicFlightRenderResult(
ctx: AppRenderContext,
options?: {
actionResult: ActionResult
skipFlight: boolean
asNotFound?: boolean
componentTree?: CacheNodeSeedData
preloadCallbacks?: PreloadCallbacks
}
): Promise<RenderResult> {
const rscPayload = await generateDynamicRSCPayload(ctx, options)
// For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
// which contains the subset React.
const flightReadableStream = renderToReadableStream(
options
? [options.actionResult, buildIdFlightDataPair]
: buildIdFlightDataPair,
const flightReadableStream = ctx.componentMod.renderToReadableStream(
rscPayload,
ctx.clientReferenceManifest.clientModules,
{
onError: ctx.flightDataRendererErrorHandler,
......@@ -417,41 +453,12 @@ type RenderToStreamOptions = {
formState: any
}
/**
* Creates a resolver that eagerly generates a flight payload that is then
* resolved when the resolver is called.
*/
function createFlightDataResolver(ctx: AppRenderContext) {
// Generate the flight data and as soon as it can, convert it into a string.
const promise = generateFlight(ctx)
.then(async (result) => ({
flightData: await result.toUnchunkedBuffer(true),
}))
// Otherwise if it errored, return the error.
.catch((err) => ({ err }))
return async () => {
// Resolve the promise to get the flight data or error.
const result = await promise
// If the flight data failed to render due to an error, re-throw the error
// here.
if ('err' in result) {
throw result.err
}
// Otherwise, return the flight data.
return result.flightData
}
}
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered
async function getRSCPayload(
tree: LoaderTree,
ctx: AppRenderContext,
asNotFound: boolean
) {
// Create full component tree from root to leaf.
const injectedCSS = new Set<string>()
const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
......@@ -525,12 +532,10 @@ async function getRSCPayload(
p: ctx.assetPrefix,
c: url.pathname + url.search,
i: couldBeIntercepted,
t: initialTree,
d: seedData,
h: initialHead,
f: [[initialTree, seedData, initialHead]],
m: missingSlots,
G: GlobalError,
} as InitialRSCPayload & { P: React.ReactNode }
} satisfies RSCPayload & { P: React.ReactNode }
}
/**
......@@ -602,12 +607,11 @@ async function getErrorRSCPayload(
b: ctx.renderOpts.buildId,
p: ctx.assetPrefix,
c: url.pathname + url.search,
m: undefined,
i: false,
t: initialTree,
d: initialSeedData,
h: initialHead,
f: [[initialTree, initialSeedData, initialHead]],
G: GlobalError,
} as InitialRSCPayload
} satisfies RSCPayload
}
// This component must run in an SSR context. It will render the RSC root component
......@@ -623,7 +627,7 @@ function ReactServerEntrypoint<T>({
nonce?: string
}): JSX.Element {
preinitScripts()
const initialRSCPayload = React.use(
const response = React.use(
useFlightStream<InitialRSCPayload>(
reactServerStream,
clientReferenceManifest,
......@@ -631,7 +635,7 @@ function ReactServerEntrypoint<T>({
)
)
return <AppRouter initialRSCPayload={initialRSCPayload} />
return <AppRouter initialRSCPayload={response} />
}
// We use a trick with TS Generics to branch streams with a type so we can
......@@ -936,18 +940,9 @@ async function renderToHTMLOrFlightImpl(
}
if (isRSCRequest && !isStaticGeneration) {
return generateFlight(ctx)
return generateDynamicFlightRenderResult(ctx)
}
// Create the resolver that can get the flight payload when it's ready or
// throw the error if it occurred. If we are not generating static HTML, we
// don't need to generate the flight payload because it's a dynamic request
// which means we're either getting the flight payload only or just the
// regular HTML.
const flightDataResolver = isStaticGeneration
? createFlightDataResolver(ctx)
: null
const validateRootLayout = dev
const { HeadManagerContext } =
......@@ -1004,13 +999,13 @@ async function renderToHTMLOrFlightImpl(
nonce
)
const RSCPayload = await getRSCPayload(tree, ctx, asNotFound)
const rscPayload = await getRSCPayload(tree, ctx, asNotFound)
// We kick off the Flight Request (render) here. It is ok to initiate the render in an arbitrary
// place however it is critical that we only construct the Flight Response inside the SSR
// render so that directives like preloads are correctly piped through
const serverStream = ComponentMod.renderToReadableStream(
RSCPayload,
rscPayload,
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
......@@ -1098,6 +1093,15 @@ async function renderToHTMLOrFlightImpl(
},
})
let flightRenderResult: FlightRenderResult | undefined = undefined
// Tee the data stream so that we can create a static flight payload.
if (isStaticGeneration) {
const [original, flightSpy] = dataStream.tee()
dataStream = original
flightRenderResult = new FlightRenderResult(flightSpy)
}
try {
const result = await renderer.render(children)
......@@ -1118,6 +1122,10 @@ async function renderToHTMLOrFlightImpl(
* all server inserted HTML and flight data
*/
// We need to provide flightData to the page metadata so it can be written to disk
metadata.flightData =
await flightRenderResult?.toUnchunkedBuffer(true)
// First we check if we have any dynamic holes in our HTML prerender
if (usedDynamicAPIs(prerenderState)) {
if (result.postponed != null) {
......@@ -1264,6 +1272,11 @@ async function renderToHTMLOrFlightImpl(
// This may be a static render or a dynamic render
// @TODO factor this further to make the render types more clearly defined and remove
// the deluge of optional params that passed to configure the various behaviors
// Since this is a potentially static branch, we need to provide flightData to the page metadata so it can be written to disk
metadata.flightData =
await flightRenderResult?.toUnchunkedBuffer(true)
return {
stream: await continueFizzStream(result.stream, {
inlinedDataStream: createInlinedDataReadableStream(
......@@ -1384,6 +1397,10 @@ async function renderToHTMLOrFlightImpl(
},
})
// Since this is a potentially static branch, we need to provide flightData to the page metadata so it can be written to disk
metadata.flightData =
await flightRenderResult?.toUnchunkedBuffer(true)
return {
// Returning the error that was thrown so it can be used to handle
// the response in the caller.
......@@ -1430,7 +1447,7 @@ async function renderToHTMLOrFlightImpl(
res,
ComponentMod,
serverModuleMap,
generateFlight,
generateFlight: generateDynamicFlightRenderResult,
staticGenerationStore,
requestStore,
serverActions,
......@@ -1514,25 +1531,12 @@ async function renderToHTMLOrFlightImpl(
}
}
if (!flightDataResolver) {
throw new Error(
'Invariant: Flight data resolver is missing when generating static HTML'
)
}
// If we encountered any unexpected errors during build we fail the
// prerendering phase and the build.
if (buildFailingError) {
throw buildFailingError
}
// Wait for and collect the flight payload data if we don't have it
// already
const flightData = await flightDataResolver()
if (flightData) {
metadata.flightData = flightData
}
// If force static is specifically set to false, we should not revalidate
// the page.
if (staticGenerationStore.forceStatic === false) {
......
......@@ -117,15 +117,6 @@ export type FlightData = Array<FlightDataPath> | string
export type ActionResult = Promise<any>
// Response from `createFromFetch` for normal rendering
export type NextFlightResponse = [buildId: string, flightData: FlightData]
// Response from `createFromFetch` for server actions. Action's flight data can be null
export type ActionFlightResponse =
| [ActionResult, [buildId: string, flightData: FlightData | null]]
// This case happens when `redirect()` is called in a server action.
| NextFlightResponse
export type ServerOnInstrumentationRequestError = (
error: unknown,
// The request could be middleware, node server or web server request,
......@@ -212,14 +203,33 @@ export type InitialRSCPayload = {
c: string
/** couldBeIntercepted */
i: boolean
/** initialTree */
t: FlightRouterState
/** initialSeedData */
d: CacheNodeSeedData
/** initialHead */
h: React.ReactNode
/** initialFlightData */
f: FlightDataPath[]
/** missingSlots */
m: Set<string> | undefined
/** GlobalError */
G: React.ComponentType<any>
}
// Response from `createFromFetch` for normal rendering
export type NavigationFlightResponse = {
/** buildId */
b: string
/** flightData */
f: FlightData
}
// Response from `createFromFetch` for server actions. Action's flight data can be null
export type ActionFlightResponse = {
/** actionResult */
a: ActionResult
/** buildId */
b: string
/** flightData */
f: FlightData | null
}
export type RSCPayload =
| InitialRSCPayload
| NavigationFlightResponse
| ActionFlightResponse
......@@ -18,8 +18,8 @@ import {
} from './create-flight-router-state-from-loader-tree'
import type { CreateSegmentPath, AppRenderContext } from './app-render'
import { hasLoadingComponentInTree } from './has-loading-component-in-tree'
import { createComponentTree } from './create-component-tree'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import { createComponentTree } from './create-component-tree'
/**
* Use router state to decide at what common layout to render the page.
......
......@@ -53,13 +53,13 @@ describe('ppr-unstable-cache', () => {
env: { TEST_DATA_SERVER: `http://localhost:${port}/` },
})
expect(generations).toHaveLength(3)
expect(generations).toHaveLength(2)
const first = await next
.render$('/')
.then(($) => JSON.parse($('#data').text()))
expect(generations).toHaveLength(3)
expect(generations).toHaveLength(2)
expect(first.data.forceCache).toBeOneOf(generations)
expect(first.data.noStore).toBeOneOf(generations)
......@@ -70,7 +70,7 @@ describe('ppr-unstable-cache', () => {
.render$('/')
.then(($) => JSON.parse($('#data').text()))
expect(generations).toHaveLength(3)
expect(generations).toHaveLength(2)
expect(first).toEqual(again)
}
......@@ -85,13 +85,13 @@ describe('ppr-unstable-cache', () => {
// Expect that the `cache: no-store` value has been updated, but not
// the `cache: force-cache` value.
expect(generations).toHaveLength(5)
expect(generations).toHaveLength(3)
// We know now that the generations have been updated, so let's try to
// validate the value. We don't need to do this within the retry.
expect(revalidated.random).not.toEqual(first.random)
expect(revalidated.data.forceCache).toBeOneOf(generations.slice(0, 3))
expect(revalidated.data.noStore).toBeOneOf(generations.slice(3))
expect(revalidated.data.forceCache).toBe(generations[1])
expect(revalidated.data.noStore).toBe(generations[2])
expect(revalidated).not.toEqual(first)
// Ensure that the `force-cache` value has not been updated, and only called
......
......@@ -444,7 +444,11 @@ describe('app dir - rsc basics', () => {
.then(async (response) => {
const result = await resolveStreamResponse(response)
expect(result).toContain('component:index.server')
expect(result).toMatch(isNextDev ? /0:\["development",/ : /0:\[".*?",/)
if (isNextDev) {
expect(result).toContain('"b":"development"')
} else {
expect(result).toMatch(/"b":".*?"/)
}
})
})
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const revalidate = 1
export default async function Home() {
console.log('home page rendered')
const randomNumber = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return (
<div>
<p id="random-number">{randomNumber}</p>
</div>
)
}
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET() {
revalidatePath('/')
return NextResponse.json({ success: true })
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('ssg-single-pass', () => {
const { next, skipped } = nextTestSetup({
skipDeployment: true,
files: __dirname,
})
if (skipped) {
return
}
it('should only render the page once during build', async () => {
expect(next.cliOutput).toIncludeRepeated('home page rendered', 1)
})
it('should only render the page once during an ISR revalidation', async () => {
let logOccurrences = next.cliOutput.split('home page rendered').length - 1
expect(logOccurrences).toBe(1)
logOccurrences = 0
const browser = await next.browser('/')
const initialRandomNumber = await browser
.elementById('random-number')
.text()
expect(initialRandomNumber).toMatch(/\d+/)
// grab the index of the last log message so we can start
// parsing future logs from there
const outputIndex = next.cliOutput.length
// trigger a revalidation
const response = await (await next.fetch('/revalidate')).json()
expect(response.success).toBe(true)
await retry(async () => {
// Retry until the data has been revalidated
browser.refresh()
const newRandomNumber = await browser.elementById('random-number').text()
expect(newRandomNumber).toMatch(/\d+/)
expect(newRandomNumber).not.toBe(initialRandomNumber)
expect(next.cliOutput.slice(outputIndex)).toIncludeRepeated(
'home page rendered',
1
)
})
})
})
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