Unverified Commit e3d634e0 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix `isHeadPartial` when hydrating from a static fallback shell (#96400)

When a static fallback shell is served as-is — e.g. from a CDN in a
deployed environment — the client can't hydrate from inline Flight data;
it fetches the full RSC payload separately and reconstructs the initial
payload on the client. During that reconstruction, the head's partiality
flag was accidentally set to the head itself. Since the head is always
truthy, the head was unconditionally treated as partial.

This happens to be unobservable today: the only flows that reach the
reconstruction are fallback-shell prerenders, where the server
pessimistically marks the head partial anyway, and when Cache Components
is enabled the client ignores the per-payload flag entirely in favor of
response-level partiality. But we're about to rework the RSC response
format so that head partiality has a single, load-bearing source of
truth, so the flag needs to survive the reconstruction correctly rather
than by coincidence.

While auditing the payload consumers, I also fixed the payload shape
check in segment prefetch generation (it used `&&` where `||` was
intended, so it accepted any shape) and deleted
`should-hard-navigate.ts`, which no longer has any callers on the
client.

Adds e2e coverage asserting that metadata survives hydrating a fallback
shell page: the title is correct after hydration, the head is included
in prefetched data, and a return navigation is served entirely from the
cache that was populated during initial hydration. In deployed
environments this exercises the client resume path, which is where the
reconstruction runs.
parent 38f0cdee
import React from 'react'
import {
PrefetchHint,
type FlightData,
type FlightRouterState,
} from '../../../shared/lib/app-router-types'
import { shouldHardNavigate } from './should-hard-navigate'
describe('shouldHardNavigate', () => {
it('should return false if the segments match', () => {
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
return [
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
['about', {}, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
],
]
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
initialRouterStateTree
)
expect(result).toBe(false)
})
it('should return false if segments are dynamic and match', () => {
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'link-hard-push',
{
children: [
['id', '123', 'd', null],
{
children: ['', {}],
},
],
},
],
},
null,
null,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
return [
[
'children',
'link-hard-push',
'children',
['id', '123', 'd', null],
[
['id', '123', 'd', null],
{
children: ['', {}],
},
],
[['id', '123', 'd', null], {}, null],
null,
],
]
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
initialRouterStateTree
)
expect(result).toBe(false)
})
it('should return true if segments are dynamic and mismatch', () => {
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'link-hard-push',
{
children: [
['id', '456', 'd', null],
{
children: ['', {}],
},
],
},
],
},
null,
null,
PrefetchHint.IsRootLayoutOrAbove,
]
const initialRouterStateTree = getInitialRouterStateTree()
const getFlightData = (): FlightData => {
return [
[
'children',
'link-hard-push',
'children',
['id', '123', 'd', null],
[
['id', '123', 'd', null],
{
children: ['', {}],
},
],
[['id', '123', 'd', null], {}, null],
null,
false,
],
]
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(0, -4)
const result = shouldHardNavigate(
['', ...flightSegmentPath],
initialRouterStateTree
)
expect(result).toBe(true)
})
})
import type {
FlightRouterState,
FlightDataPath,
Segment,
} from '../../../shared/lib/app-router-types'
import { getNextFlightSegmentPath } from '../../flight-data-helpers'
import { matchSegment } from '../match-segments'
// TODO-APP: flightSegmentPath will be empty in case of static response, needs to be handled.
export function shouldHardNavigate(
flightSegmentPath: FlightDataPath,
flightRouterState: FlightRouterState
): boolean {
const [segment, parallelRoutes] = flightRouterState
// TODO-APP: Check if `as` can be replaced.
const [currentSegment, parallelRouteKey] = flightSegmentPath as [
Segment,
string,
]
// Check if current segment matches the existing segment.
if (!matchSegment(currentSegment, segment)) {
// If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.
if (Array.isArray(currentSegment)) {
return true
}
// If the existing segment did not match soft navigation is triggered.
return false
}
const lastSegment = flightSegmentPath.length <= 2
if (lastSegment) {
return false
}
return shouldHardNavigate(
getNextFlightSegmentPath(flightSegmentPath),
parallelRoutes[parallelRouteKey]
)
}
......@@ -112,7 +112,10 @@ export function createInitialRSCPayloadFromFallbackPrerender(
),
originalFlightDataPath[1],
originalFlightDataPath[2],
originalFlightDataPath[2],
// isHeadPartial. Previously this incorrectly passed the head itself
// (index 2), which is truthy, so the head was always treated
// as partial.
originalFlightDataPath[3],
],
],
m: fallbackInitialRSCPayload.m,
......
......@@ -246,7 +246,9 @@ function onSegmentPrerenderError(error: unknown) {
/**
* Extract the FlightRouterState, seed data, and head from a prerendered
* InitialRSCPayload. Returns null if the payload doesn't match the expected
* shape (single path with 3 elements).
* shape: a single root path with no segment prefix, which has 4 elements
* ([tree, seedData, head, isHeadPartial], per getRSCPayload) or 3 when
* reconstructed without the isHeadPartial flag (per instant-validation).
*/
function extractFlightData(initialRSCPayload: InitialRSCPayload): {
buildId: string | undefined
......@@ -256,7 +258,10 @@ function extractFlightData(initialRSCPayload: InitialRSCPayload): {
} | null {
const flightDataPaths = initialRSCPayload.f
// FlightDataPath is an unsound type, hence the additional checks.
if (flightDataPaths.length !== 1 && flightDataPaths[0].length !== 3) {
if (
flightDataPaths.length !== 1 ||
(flightDataPaths[0].length !== 3 && flightDataPaths[0].length !== 4)
) {
console.error(
'Internal Next.js error: InitialRSCPayload does not match the expected ' +
'shape for a prerendered page during segment prefetch generation.'
......
......@@ -665,9 +665,16 @@ export async function createCombinedPayloadStream(
}
function getRootDataFromPayload(initialRSCPayload: InitialRSCPayload) {
// FlightDataPath is an unsound type, hence the additional checks.
// FlightDataPath is an unsound type, hence the additional checks. The
// valid shapes are a single root path with no segment prefix: 4 elements
// ([tree, seedData, head, isHeadPartial], per getRSCPayload) or 3 when
// reconstructed without the isHeadPartial flag (see the payload literals
// in this module).
const flightDataPaths = initialRSCPayload.f
if (flightDataPaths.length !== 1 && flightDataPaths[0].length !== 3) {
if (
flightDataPaths.length !== 1 ||
(flightDataPaths[0].length !== 3 && flightDataPaths[0].length !== 4)
) {
throw new InvariantError(
'InitialRSCPayload does not match the expected shape during instant validation.'
)
......
import { LinkAccordion } from '../../../components/link-accordion'
export const metadata = {
title: 'Metadata Hub Title',
}
export default function Page() {
return (
<>
<div id="hub">Metadata hub page content</div>
<div>
<LinkAccordion href="/without-io/with-metadata/world">
Back to fallback page
</LinkAccordion>
</div>
</>
)
}
import { LinkAccordion } from '../../../../components/link-accordion'
export const metadata = {
title: 'Fallback Shell Metadata Title',
}
export default async function Page({ params }) {
const { slug } = await params
return (
<>
<div id="slug">Hello /{slug}</div>
<div>
<LinkAccordion href="/without-io/metadata-hub">
Go to metadata hub
</LinkAccordion>
</div>
</>
)
}
export async function generateStaticParams() {
return [{ slug: 'foo' }]
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
id,
}: {
href: string
children: string
prefetch?: LinkProps['prefetch']
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
id={id}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { assertNoConsoleErrors } from 'next-test-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('fallback-shells', () => {
const { next, isNextDev, isNextDeploy, isNextStart } = nextTestSetup({
......@@ -18,6 +20,91 @@ describe('fallback-shells', () => {
// response, and therefore shouldn't have sent the postponed header.
expect(headers['x-nextjs-postponed']).not.toBe('1')
})
// Coverage for the head (metadata) surviving hydration of a fallback
// shell page for an uncovered param: the title must be correct after
// hydration, the head must be included in prefetched data, and a return
// navigation must be served entirely from the cache that was populated
// during the initial hydration.
//
// NOTE: This does not exercise the client resume path
// (createInitialRSCPayloadFromFallbackPrerender). In deployed
// environments an uncovered param currently gets a blocking on-demand
// render rather than the prerendered fallback shell, and `next start`
// renders uncovered params on demand as well. The resume script is only
// present in the build-time fallback shell artifact.
describe('with metadata', () => {
if (isNextDev) {
// Fallback shells (and prefetching) only exist in production builds.
test('disabled in development', () => {})
return
}
it('preserves metadata when hydrating a fallback shell page', async () => {
let act: ReturnType<typeof createRouterAct>
const { browser, response } = await next.browserWithResponse(
'/without-io/with-metadata/world',
{
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
}
)
expect(response.headers()['x-nextjs-postponed']).not.toBe('1')
expect(await browser.elementById('slug').text()).toBe('Hello /world')
expect(await browser.eval('document.title')).toBe(
'Fallback Shell Metadata Title'
)
// Prefetch the hub page. The head (title) should be included in the
// prefetched data.
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/without-io/metadata-hub"]'
)
await toggle.click()
},
{ includes: 'Metadata Hub Title' }
)
// Navigate to the hub. It was fully prefetched, so no additional
// requests should be needed. This also proves hydration of the
// initial page completed, since it requires the client router to
// be interactive.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/without-io/metadata-hub"]'
)
await link.click()
}, 'no-requests')
expect(await browser.elementById('hub').text()).toBe(
'Metadata hub page content'
)
expect(await browser.eval('document.title')).toBe('Metadata Hub Title')
// Navigate back to the fallback page. Hydrating the initial page
// wrote its data — including the head — into the segment cache, so
// the return navigation should be served entirely from the cache.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/without-io/with-metadata/world"]'
)
await toggle.click()
}, 'no-requests')
await act(async () => {
const link = await browser.elementByCss(
'a[href="/without-io/with-metadata/world"]'
)
await link.click()
}, 'no-requests')
expect(await browser.elementById('slug').text()).toBe('Hello /world')
expect(await browser.eval('document.title')).toBe(
'Fallback Shell Metadata Title'
)
await assertNoConsoleErrors(browser)
})
})
})
describe('with cached IO', () => {
......
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