Unverified Commit 683a318d authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Omit params to from client segments (#84883)

If a layout or page is marked with "use client", we do not need to pass
any runtime params from the server; the client can parse them from the
URL, or (in the case of a rewrite) from the x-next-rewritten-path and
x-next-rewritten-query headers. This means the client can treat the
segment as fully static, and no dynamic request is necessary upon
navigation.
parent d58f7aa0
...@@ -3,7 +3,10 @@ import ReactDOMClient from 'react-dom/client' ...@@ -3,7 +3,10 @@ import ReactDOMClient from 'react-dom/client'
import React from 'react' import React from 'react'
// TODO: Explicitly import from client.browser // TODO: Explicitly import from client.browser
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { createFromReadableStream as createFromReadableStreamBrowser } from 'react-server-dom-webpack/client' import {
createFromReadableStream as createFromReadableStreamBrowser,
createFromFetch as createFromFetchBrowser,
} from 'react-server-dom-webpack/client'
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime' import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'
import { onRecoverableError } from './react-client-callbacks/on-recoverable-error' import { onRecoverableError } from './react-client-callbacks/on-recoverable-error'
import { import {
...@@ -22,11 +25,14 @@ import { createInitialRouterState } from './components/router-reducer/create-ini ...@@ -22,11 +25,14 @@ import { createInitialRouterState } from './components/router-reducer/create-ini
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime' import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id' import { setAppBuildId } from './app-build-id'
import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-app' import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-app'
import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-helpers'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
const appElement: HTMLElement | Document = document const appElement: HTMLElement | Document = document
...@@ -173,16 +179,38 @@ if ( ...@@ -173,16 +179,38 @@ if (
debugChannel = createDebugChannel(undefined) debugChannel = createDebugChannel(undefined)
} }
const initialServerResponse = createFromReadableStream<InitialRSCPayload>( const clientResumeFetch: Promise<Response> | undefined =
readable, // @ts-expect-error
{ window.__NEXT_CLIENT_RESUME
callServer,
findSourceMapURL, let initialServerResponse: Promise<InitialRSCPayload>
debugChannel, if (clientResumeFetch) {
// @ts-expect-error This is not yet part of the React types initialServerResponse = Promise.resolve(
startTime: 0, createFromFetch<InitialRSCPayload>(clientResumeFetch, {
} callServer,
) findSourceMapURL,
debugChannel,
// @ts-expect-error This is not yet part of the React types
startTime: 0,
})
).then(async (fallbackInitialRSCPayload) =>
createInitialRSCPayloadFromFallbackPrerender(
await clientResumeFetch,
fallbackInitialRSCPayload
)
)
} else {
initialServerResponse = createFromReadableStream<InitialRSCPayload>(
readable,
{
callServer,
findSourceMapURL,
debugChannel,
// @ts-expect-error This is not yet part of the React types
startTime: 0,
}
)
}
function ServerRoot({ function ServerRoot({
initialRSCPayload, initialRSCPayload,
......
...@@ -434,6 +434,7 @@ function Router({ ...@@ -434,6 +434,7 @@ function Router({
parentTree: tree, parentTree: tree,
parentCacheNode: cache, parentCacheNode: cache,
parentSegmentPath: null, parentSegmentPath: null,
parentParams: {},
// Root node always has `url` // Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl, url: canonicalUrl,
......
...@@ -4,6 +4,10 @@ import type { ParsedUrlQuery } from 'querystring' ...@@ -4,6 +4,10 @@ import type { ParsedUrlQuery } from 'querystring'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime'
import { use } from 'react'
import { urlSearchParamsToParsedUrlQuery } from '../route-params'
import { SearchParamsContext } from '../../shared/lib/hooks-client-context.shared-runtime'
/** /**
* When the Page is a client component we send the params and searchParams to this client wrapper * When the Page is a client component we send the params and searchParams to this client wrapper
...@@ -15,16 +19,35 @@ import type { Params } from '../../server/request/params' ...@@ -15,16 +19,35 @@ import type { Params } from '../../server/request/params'
*/ */
export function ClientPageRoot({ export function ClientPageRoot({
Component, Component,
searchParams, serverProvidedParams,
params,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promises,
}: { }: {
Component: React.ComponentType<any> Component: React.ComponentType<any>
searchParams: ParsedUrlQuery serverProvidedParams: null | {
params: Params searchParams: ParsedUrlQuery
promises?: Array<Promise<any>> params: Params
promises: Array<Promise<any>> | null
}
}) { }) {
let searchParams: ParsedUrlQuery
let params: Params
if (serverProvidedParams !== null) {
searchParams = serverProvidedParams.searchParams
params = serverProvidedParams.params
} else {
// When Cache Components is enabled, the server does not pass the params as
// props; they are parsed on the client and passed via context.
const layoutRouterContext = use(LayoutRouterContext)
params =
layoutRouterContext !== null ? layoutRouterContext.parentParams : {}
// This is an intentional behavior change: when Cache Components is enabled,
// client segments receive the "canonical" search params, not the
// rewritten ones. Users should either call useSearchParams directly or pass
// the rewritten ones in from a Server Component.
// TODO: Log a deprecation error when this object is accessed
searchParams = urlSearchParamsToParsedUrlQuery(use(SearchParamsContext)!)
}
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { workAsyncStorage } = const { workAsyncStorage } =
require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external') require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime'
import { use } from 'react'
/** /**
* When the Page is a client component we send the params to this client wrapper * When the Page is a client component we send the params to this client wrapper
...@@ -15,15 +17,26 @@ import type { Params } from '../../server/request/params' ...@@ -15,15 +17,26 @@ import type { Params } from '../../server/request/params'
export function ClientSegmentRoot({ export function ClientSegmentRoot({
Component, Component,
slots, slots,
params, serverProvidedParams,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promise,
}: { }: {
Component: React.ComponentType<any> Component: React.ComponentType<any>
slots: { [key: string]: React.ReactNode } slots: { [key: string]: React.ReactNode }
params: Params serverProvidedParams: null | {
promise?: Promise<any> params: Params
promises: Array<Promise<any>> | null
}
}) { }) {
let params: Params
if (serverProvidedParams !== null) {
params = serverProvidedParams.params
} else {
// When Cache Components is enabled, the server does not pass the params
// as props; they are parsed on the client and passed via context.
const layoutRouterContext = use(LayoutRouterContext)
params =
layoutRouterContext !== null ? layoutRouterContext.parentParams : {}
}
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { workAsyncStorage } = const { workAsyncStorage } =
require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external') require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')
......
...@@ -47,6 +47,8 @@ import { ...@@ -47,6 +47,8 @@ import {
NavigationPromisesContext, NavigationPromisesContext,
type NavigationPromises, type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { getParamValueFromCacheKey } from '../route-params'
import type { Params } from '../../server/request/params'
/** /**
* Add refetch marker to router state at the point of the current layout segment. * Add refetch marker to router state at the point of the current layout segment.
...@@ -337,12 +339,14 @@ function InnerLayoutRouter({ ...@@ -337,12 +339,14 @@ function InnerLayoutRouter({
tree, tree,
segmentPath, segmentPath,
cacheNode, cacheNode,
params,
url, url,
isActive, isActive,
}: { }: {
tree: FlightRouterState tree: FlightRouterState
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
cacheNode: CacheNode cacheNode: CacheNode
params: Params
url: string url: string
isActive: boolean isActive: boolean
}) { }) {
...@@ -464,6 +468,7 @@ function InnerLayoutRouter({ ...@@ -464,6 +468,7 @@ function InnerLayoutRouter({
parentTree: tree, parentTree: tree,
parentCacheNode: cacheNode, parentCacheNode: cacheNode,
parentSegmentPath: segmentPath, parentSegmentPath: segmentPath,
parentParams: params,
// TODO-APP: overriding of url for parallel routes // TODO-APP: overriding of url for parallel routes
url: url, url: url,
...@@ -565,8 +570,14 @@ export default function OuterLayoutRouter({ ...@@ -565,8 +570,14 @@ export default function OuterLayoutRouter({
throw new Error('invariant expected layout router to be mounted') throw new Error('invariant expected layout router to be mounted')
} }
const { parentTree, parentCacheNode, parentSegmentPath, url, isActive } = const {
context parentTree,
parentCacheNode,
parentSegmentPath,
parentParams,
url,
isActive,
} = context
// Get the CacheNode for this segment by reading it from the parent segment's // Get the CacheNode for this segment by reading it from the parent segment's
// child map. // child map.
...@@ -668,6 +679,23 @@ export default function OuterLayoutRouter({ ...@@ -668,6 +679,23 @@ export default function OuterLayoutRouter({
) )
} }
let params = parentParams
if (Array.isArray(segment)) {
// This segment contains a route param. Accumulate these as we traverse
// down the router tree. The result represents the set of params that
// the layout/page components are permitted to access below this point.
const paramName = segment[0]
const paramCacheKey = segment[1]
const paramType = segment[2]
const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType)
if (paramValue !== null) {
params = {
...parentParams,
[paramName]: paramValue,
}
}
}
// TODO: The loading module data for a segment is stored on the parent, then // TODO: The loading module data for a segment is stored on the parent, then
// applied to each of that parent segment's parallel route slots. In the // applied to each of that parent segment's parallel route slots. In the
// simple case where there's only one parallel route (the `children` slot), // simple case where there's only one parallel route (the `children` slot),
...@@ -697,6 +725,7 @@ export default function OuterLayoutRouter({ ...@@ -697,6 +725,7 @@ export default function OuterLayoutRouter({
<InnerLayoutRouter <InnerLayoutRouter
url={url} url={url}
tree={tree} tree={tree}
params={params}
cacheNode={cacheNode} cacheNode={cacheNode}
segmentPath={segmentPath} segmentPath={segmentPath}
isActive={isActive && stateKey === activeStateKey} isActive={isActive && stateKey === activeStateKey}
......
...@@ -6,8 +6,18 @@ import type { ...@@ -6,8 +6,18 @@ import type {
FlightSegmentPath, FlightSegmentPath,
Segment, Segment,
HeadData, HeadData,
InitialRSCPayload,
} from '../shared/lib/app-router-types' } from '../shared/lib/app-router-types'
import { PAGE_SEGMENT_KEY } from '../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../shared/lib/segment'
import type { NormalizedSearch } from './components/segment-cache'
import {
getCacheKeyForDynamicParam,
parseDynamicParamFromURLPart,
doesStaticSegmentAppearInURL,
getRenderedPathname,
getRenderedSearch,
} from './route-params'
import { createHrefFromUrl } from './components/router-reducer/create-href-from-url'
export type NormalizedFlightData = { export type NormalizedFlightData = {
/** /**
...@@ -58,6 +68,129 @@ export function getFlightDataPartsFromPath( ...@@ -58,6 +68,129 @@ export function getFlightDataPartsFromPath(
} }
} }
export function createInitialRSCPayloadFromFallbackPrerender(
response: Response,
fallbackInitialRSCPayload: InitialRSCPayload
): InitialRSCPayload {
// This is a static fallback page. In order to hydrate the page, we need to
// parse the client params from the URL, but to account for the possibility
// that the page was rewritten, we need to check the response headers
// for x-nextjs-rewritten-path or x-nextjs-rewritten-query headers. Since
// we can't access the headers of the initial document response, the client
// performs a fetch request to the current location. Since it's possible that
// the fetch request will be dynamically rewritten to a different path than
// the initial document, this fetch request delivers _all_ the hydration data
// for the page; it was not inlined into the document, like it normally
// would be.
//
// TODO: Consider treating the case where fetch is rewritten to a different
// path from the document as a special deopt case. We should optimistically
// assume this won't happen, inline the data into the document, and perform
// a minimal request (like a HEAD or range request) to verify that the
// response matches. Tricky to get right because we need to account for
// all the different deployment environments we support, like output:
// "export" mode, where we currently don't assume that custom response
// headers are present.
// Patch the Flight data sent by the server with the correct params parsed
// from the URL + response object.
const renderedPathname = getRenderedPathname(response)
const renderedSearch = getRenderedSearch(response)
const canonicalUrl = createHrefFromUrl(new URL(location.href))
const originalFlightDataPath = fallbackInitialRSCPayload.f[0]
const originalFlightRouterState = originalFlightDataPath[0]
return {
b: fallbackInitialRSCPayload.b,
c: canonicalUrl.split('/'),
q: renderedSearch,
i: fallbackInitialRSCPayload.i,
f: [
[
fillInFallbackFlightRouterState(
originalFlightRouterState,
renderedPathname,
renderedSearch as NormalizedSearch
),
originalFlightDataPath[1],
originalFlightDataPath[2],
originalFlightDataPath[2],
],
],
m: fallbackInitialRSCPayload.m,
G: fallbackInitialRSCPayload.G,
s: fallbackInitialRSCPayload.s,
S: fallbackInitialRSCPayload.S,
}
}
function fillInFallbackFlightRouterState(
flightRouterState: FlightRouterState,
renderedPathname: string,
renderedSearch: NormalizedSearch
): FlightRouterState {
const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')
const index = 0
return fillInFallbackFlightRouterStateImpl(
flightRouterState,
renderedSearch,
pathnameParts,
index
)
}
function fillInFallbackFlightRouterStateImpl(
flightRouterState: FlightRouterState,
renderedSearch: NormalizedSearch,
pathnameParts: Array<string>,
pathnamePartsIndex: number
): FlightRouterState {
const originalSegment = flightRouterState[0]
let newSegment: Segment
let doesAppearInURL: boolean
if (typeof originalSegment === 'string') {
newSegment = originalSegment
doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment)
} else {
const paramName = originalSegment[0]
const paramType = originalSegment[2]
const paramValue = parseDynamicParamFromURLPart(
paramType,
pathnameParts,
pathnamePartsIndex
)
const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch)
newSegment = [paramName, cacheKey, paramType]
doesAppearInURL = true
}
// Only increment the index if the segment appears in the URL. If it's a
// "virtual" segment, like a route group, it remains the same.
const childPathnamePartsIndex = doesAppearInURL
? pathnamePartsIndex + 1
: pathnamePartsIndex
const children = flightRouterState[1]
const newChildren: { [key: string]: FlightRouterState } = {}
for (let key in children) {
const childFlightRouterState = children[key]
newChildren[key] = fillInFallbackFlightRouterStateImpl(
childFlightRouterState,
renderedSearch,
pathnameParts,
childPathnamePartsIndex
)
}
const newState: FlightRouterState = [
newSegment,
newChildren,
null,
flightRouterState[3],
flightRouterState[4],
]
return newState
}
export function getNextFlightSegmentPath( export function getNextFlightSegmentPath(
flightSegmentPath: FlightSegmentPath flightSegmentPath: FlightSegmentPath
): FlightSegmentPath { ): FlightSegmentPath {
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
} from './components/app-router-headers' } from './components/app-router-headers'
import type { NormalizedSearch } from './components/segment-cache' import type { NormalizedSearch } from './components/segment-cache'
import type { RSCResponse } from './components/router-reducer/fetch-server-response' import type { RSCResponse } from './components/router-reducer/fetch-server-response'
import type { ParsedUrlQuery } from 'querystring'
export type RouteParamValue = string | Array<string> | null export type RouteParamValue = string | Array<string> | null
...@@ -22,7 +23,7 @@ export type RouteParam = { ...@@ -22,7 +23,7 @@ export type RouteParam = {
} }
export function getRenderedSearch( export function getRenderedSearch(
response: RSCResponse<unknown> response: RSCResponse<unknown> | Response
): NormalizedSearch { ): NormalizedSearch {
// If the server performed a rewrite, the search params used to render the // If the server performed a rewrite, the search params used to render the
// page will be different from the params in the request URL. In this case, // page will be different from the params in the request URL. In this case,
...@@ -39,7 +40,9 @@ export function getRenderedSearch( ...@@ -39,7 +40,9 @@ export function getRenderedSearch(
.search as NormalizedSearch .search as NormalizedSearch
} }
export function getRenderedPathname(response: RSCResponse<unknown>): string { export function getRenderedPathname(
response: RSCResponse<unknown> | Response
): string {
// If the server performed a rewrite, the pathname used to render the // If the server performed a rewrite, the pathname used to render the
// page will be different from the pathname in the request URL. In this case, // page will be different from the pathname in the request URL. In this case,
// the response will include a header that gives the rewritten pathname. // the response will include a header that gives the rewritten pathname.
...@@ -180,3 +183,22 @@ export function getParamValueFromCacheKey( ...@@ -180,3 +183,22 @@ export function getParamValueFromCacheKey(
} }
return paramCacheKey return paramCacheKey
} }
export function urlSearchParamsToParsedUrlQuery(
searchParams: URLSearchParams
): ParsedUrlQuery {
// Converts a URLSearchParams object to the same type used by the server when
// creating search params props, i.e. the type returned by Node's
// "querystring" module.
const result: ParsedUrlQuery = {}
for (const [key, value] of searchParams.entries()) {
if (result[key] === undefined) {
result[key] = value
} else if (Array.isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [result[key], value]
}
}
return result
}
...@@ -45,6 +45,7 @@ import { ...@@ -45,6 +45,7 @@ import {
continueDynamicHTMLResume, continueDynamicHTMLResume,
streamToBuffer, streamToBuffer,
streamToString, streamToString,
continueStaticFallbackPrerender,
} from '../stream-utils/node-web-streams-helper' } from '../stream-utils/node-web-streams-helper'
import { stripInternalQueries } from '../internal-utils' import { stripInternalQueries } from '../internal-utils'
import { import {
...@@ -1174,7 +1175,7 @@ function prepareInitialCanonicalUrl(url: RequestStore['url']) { ...@@ -1174,7 +1175,7 @@ function prepareInitialCanonicalUrl(url: RequestStore['url']) {
return (url.pathname + url.search).split('/') return (url.pathname + url.search).split('/')
} }
function querystringEncode(query: NextParsedUrlQuery): string { function getRenderedSearch(query: NextParsedUrlQuery): string {
// Inlined implementation of querystring.encode, which is not available in // Inlined implementation of querystring.encode, which is not available in
// the Edge runtime. // the Edge runtime.
const pairs = [] const pairs = []
...@@ -1193,7 +1194,18 @@ function querystringEncode(query: NextParsedUrlQuery): string { ...@@ -1193,7 +1194,18 @@ function querystringEncode(query: NextParsedUrlQuery): string {
) )
} }
} }
return pairs.join('&')
// The result should match the format of a web URL's `search` property, since
// this is the format that's stored in the App Router state.
// TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query
// header omits the leading question mark. Should refactor to always do
// that instead.
if (pairs.length === 0) {
// If the search string is empty, return an empty string.
return ''
}
// Prepend '?' to the search params string.
return '?' + pairs.join('&')
} }
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered // This is the data necessary to render <AppRouter /> when no SSR errors are encountered
...@@ -1311,7 +1323,7 @@ async function getRSCPayload( ...@@ -1311,7 +1323,7 @@ async function getRSCPayload(
}), }),
b: ctx.sharedContext.buildId, b: ctx.sharedContext.buildId,
c: prepareInitialCanonicalUrl(url), c: prepareInitialCanonicalUrl(url),
q: querystringEncode(query), q: getRenderedSearch(query),
i: !!couldBeIntercepted, i: !!couldBeIntercepted,
f: [ f: [
[ [
...@@ -1436,7 +1448,7 @@ async function getErrorRSCPayload( ...@@ -1436,7 +1448,7 @@ async function getErrorRSCPayload(
return { return {
b: ctx.sharedContext.buildId, b: ctx.sharedContext.buildId,
c: prepareInitialCanonicalUrl(url), c: prepareInitialCanonicalUrl(url),
q: querystringEncode(query), q: getRenderedSearch(query),
m: undefined, m: undefined,
i: false, i: false,
f: [ f: [
...@@ -4579,14 +4591,7 @@ async function prerenderToStream( ...@@ -4579,14 +4591,7 @@ async function prerenderToStream(
renderOpts renderOpts
) )
// If there are fallback route params, the RSC data is inherently dynamic if (serverIsDynamic) {
// today because it's encoded into the flight router state. Until we can
// move the fallback route params out of the flight router state, we need
// to always perform a dynamic resume after the static prerender.
const hasFallbackRouteParams =
fallbackRouteParams && fallbackRouteParams.size > 0
if (serverIsDynamic || hasFallbackRouteParams) {
// Dynamic case // Dynamic case
// We will always need to perform a "resume" render of some kind when this route is accessed // We will always need to perform a "resume" render of some kind when this route is accessed
// because the RSC data itself is dynamic. We determine if there are any HTML holes or not // because the RSC data itself is dynamic. We determine if there are any HTML holes or not
...@@ -4674,10 +4679,52 @@ async function prerenderToStream( ...@@ -4674,10 +4679,52 @@ async function prerenderToStream(
htmlStream = chainStreams(prelude, resumeStream) htmlStream = chainStreams(prelude, resumeStream)
} }
return { let finalStream
digestErrorsMap: reactServerErrorsByDigest, const hasFallbackRouteParams =
ssrErrors: allCapturedErrors, fallbackRouteParams && fallbackRouteParams.size > 0
stream: await continueStaticPrerender(htmlStream, { if (hasFallbackRouteParams) {
// This is a "static fallback" prerender: although the page didn't
// access any runtime params in a Server Component, it may have
// accessed a runtime param in a client segment.
//
// TODO: If there were no client segments, we can use the fully static
// path instead.
//
// Rather than use a dynamic server resume to fill in the params,
// we can rely on the client to parse the params from the URL and use
// that to hydrate the page.
//
// Send an empty InitialRSCPayload to the server component renderer
// The data will be fetched by the client instead.
// TODO: In the future, rather than defer the entire hydration payload
// to be fetched by the client, we should only defer the client
// segments, since those are the only ones whose data is not complete.
const emptyReactServerResult =
await createReactServerPrerenderResultFromRender(
ComponentMod.renderToReadableStream(
[],
clientReferenceManifest.clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
}
)
)
finalStream = await continueStaticFallbackPrerender(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
emptyReactServerResult.consumeAsStream(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
})
} else {
// Normal static prerender case, no fallback param handling needed
finalStream = await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(), reactServerResult.consumeAsStream(),
nonce, nonce,
...@@ -4688,7 +4735,13 @@ async function prerenderToStream( ...@@ -4688,7 +4735,13 @@ async function prerenderToStream(
isBuildTimePrerendering: isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true, ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId, buildId: ctx.workStore.buildId,
}), })
}
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: finalStream,
dynamicAccess: consumeDynamicAccess( dynamicAccess: consumeDynamicAccess(
serverDynamicTracking, serverDynamicTracking,
clientDynamicTracking clientDynamicTracking
......
...@@ -154,6 +154,9 @@ export async function collectSegmentData( ...@@ -154,6 +154,9 @@ export async function collectSegmentData(
const treeBuffer = await streamToBuffer(treeStream) const treeBuffer = await streamToBuffer(treeStream)
resultMap.set('/_tree' as SegmentRequestKey, treeBuffer) resultMap.set('/_tree' as SegmentRequestKey, treeBuffer)
// Also output the entire full page data response
resultMap.set('/_full' as SegmentRequestKey, fullPageDataBuffer)
// Now that we've finished rendering the route tree, all the segment tasks // Now that we've finished rendering the route tree, all the segment tasks
// should have been spawned. Await them in parallel and write the segment // should have been spawned. Await them in parallel and write the segment
// prefetches to the result map. // prefetches to the result map.
......
...@@ -103,7 +103,7 @@ async function createComponentTreeInternal( ...@@ -103,7 +103,7 @@ async function createComponentTreeInternal(
isRoot: boolean isRoot: boolean
): Promise<CacheNodeSeedData> { ): Promise<CacheNodeSeedData> {
const { const {
renderOpts: { nextConfigOutput, experimental }, renderOpts: { nextConfigOutput, experimental, cacheComponents },
workStore, workStore,
componentMod: { componentMod: {
createElement, createElement,
...@@ -742,22 +742,33 @@ async function createComponentTreeInternal( ...@@ -742,22 +742,33 @@ async function createComponentTreeInternal(
// Assign searchParams to props if this is a page // Assign searchParams to props if this is a page
let pageElement: React.ReactNode let pageElement: React.ReactNode
if (isClientComponent) { if (isClientComponent) {
if (isStaticGeneration) { if (cacheComponents) {
// Params are omitted when Cache Components is enabled
pageElement = createElement(ClientPageRoot, {
Component: PageComponent,
serverProvidedParams: null,
})
} else if (isStaticGeneration) {
const promiseOfParams = const promiseOfParams =
createPrerenderParamsForClientSegment(currentParams) createPrerenderParamsForClientSegment(currentParams)
const promiseOfSearchParams = const promiseOfSearchParams =
createPrerenderSearchParamsForClientPage(workStore) createPrerenderSearchParamsForClientPage(workStore)
pageElement = createElement(ClientPageRoot, { pageElement = createElement(ClientPageRoot, {
Component: PageComponent, Component: PageComponent,
searchParams: query, serverProvidedParams: {
params: currentParams, searchParams: query,
promises: [promiseOfSearchParams, promiseOfParams], params: currentParams,
promises: [promiseOfSearchParams, promiseOfParams],
},
}) })
} else { } else {
pageElement = createElement(ClientPageRoot, { pageElement = createElement(ClientPageRoot, {
Component: PageComponent, Component: PageComponent,
searchParams: query, serverProvidedParams: {
params: currentParams, searchParams: query,
params: currentParams,
promises: null,
},
}) })
} }
} else { } else {
...@@ -834,22 +845,33 @@ async function createComponentTreeInternal( ...@@ -834,22 +845,33 @@ async function createComponentTreeInternal(
if (isClientComponent) { if (isClientComponent) {
let clientSegment: React.ReactNode let clientSegment: React.ReactNode
if (cacheComponents) {
if (isStaticGeneration) { // Params are omitted when Cache Components is enabled
clientSegment = createElement(ClientSegmentRoot, {
Component: SegmentComponent,
slots: parallelRouteProps,
serverProvidedParams: null,
})
} else if (isStaticGeneration) {
const promiseOfParams = const promiseOfParams =
createPrerenderParamsForClientSegment(currentParams) createPrerenderParamsForClientSegment(currentParams)
clientSegment = createElement(ClientSegmentRoot, { clientSegment = createElement(ClientSegmentRoot, {
Component: SegmentComponent, Component: SegmentComponent,
slots: parallelRouteProps, slots: parallelRouteProps,
params: currentParams, serverProvidedParams: {
promise: promiseOfParams, params: currentParams,
promises: [promiseOfParams],
},
}) })
} else { } else {
clientSegment = createElement(ClientSegmentRoot, { clientSegment = createElement(ClientSegmentRoot, {
Component: SegmentComponent, Component: SegmentComponent,
slots: parallelRouteProps, slots: parallelRouteProps,
params: currentParams, serverProvidedParams: {
params: currentParams,
promises: null,
},
}) })
} }
......
...@@ -11,6 +11,13 @@ import { ...@@ -11,6 +11,13 @@ import {
} from './uint8array-helpers' } from './uint8array-helpers'
import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants' import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'
import { insertBuildIdComment } from '../../shared/lib/segment-cache/output-export-prefetch-encoding' import { insertBuildIdComment } from '../../shared/lib/segment-cache/output-export-prefetch-encoding'
import {
RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_RSC_UNION_QUERY,
} from '../../client/components/app-router-headers'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
function voidCatch() { function voidCatch() {
// this catcher is designed to be used with pipeTo where we expect the underlying // this catcher is designed to be used with pipeTo where we expect the underlying
...@@ -422,6 +429,66 @@ function createHeadInsertionTransformStream( ...@@ -422,6 +429,66 @@ function createHeadInsertionTransformStream(
}) })
} }
function createClientResumeScriptInsertionTransformStream(): TransformStream<
Uint8Array,
Uint8Array
> {
const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam(
'1', // headers[NEXT_ROUTER_PREFETCH_HEADER]
'/_full', // headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]
undefined, // headers[NEXT_ROUTER_STATE_TREE_HEADER]
undefined // headers[NEXT_URL]
)
const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`
const NEXT_CLIENT_RESUME_SCRIPT = `<script>__NEXT_CLIENT_RESUME=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}': '1','${NEXT_ROUTER_PREFETCH_HEADER}': '1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '${segmentPath}'}})</script>`
let didAlreadyInsert = false
return new TransformStream({
transform(chunk, controller) {
if (didAlreadyInsert) {
// Already inserted the script into the head. Pass through.
controller.enqueue(chunk)
return
}
// TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.
const headClosingTagIndex = indexOfUint8Array(
chunk,
ENCODED_TAGS.CLOSED.HEAD
)
if (headClosingTagIndex === -1) {
// In fully static rendering or non PPR rendering cases:
// `/head>` will always be found in the chunk in first chunk rendering.
controller.enqueue(chunk)
return
}
const encodedInsertion = encoder.encode(NEXT_CLIENT_RESUME_SCRIPT)
// Get the total count of the bytes in the chunk and the insertion
// e.g.
// chunk = <head><meta charset="utf-8"></head>
// insertion = <script>...</script>
// output = <head><meta charset="utf-8"> [ <script>...</script> ] </head>
const insertedHeadContent = new Uint8Array(
chunk.length + encodedInsertion.length
)
// Append the first part of the chunk, before the head tag
insertedHeadContent.set(chunk.slice(0, headClosingTagIndex))
// Append the server inserted content
insertedHeadContent.set(encodedInsertion, headClosingTagIndex)
// Append the rest of the chunk
insertedHeadContent.set(
chunk.slice(headClosingTagIndex),
headClosingTagIndex + encodedInsertion.length
)
controller.enqueue(insertedHeadContent)
didAlreadyInsert = true
},
})
}
// Suffix after main body content - scripts before </body>, // Suffix after main body content - scripts before </body>,
// but wait for the major chunks to be enqueued. // but wait for the major chunks to be enqueued.
function createDeferredSuffixStream( function createDeferredSuffixStream(
...@@ -831,6 +898,42 @@ export async function continueStaticPrerender( ...@@ -831,6 +898,42 @@ export async function continueStaticPrerender(
) )
} }
export async function continueStaticFallbackPrerender(
prerenderStream: ReadableStream<Uint8Array>,
{
inlinedDataStream,
getServerInsertedHTML,
getServerInsertedMetadata,
isBuildTimePrerendering,
buildId,
}: ContinueStaticPrerenderOptions
) {
// Same as `continueStaticPrerender`, but also inserts an additional script
// to instruct the client to start fetching the hydration data as early
// as possible.
return (
prerenderStream
// Buffer everything to avoid flushing too frequently
.pipeThrough(createBufferedTransformStream())
// Add build id comment to start of the HTML document (in export mode)
.pipeThrough(
createPrefetchCommentStream(isBuildTimePrerendering, buildId)
)
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert the client resume script into the head
.pipeThrough(createClientResumeScriptInsertionTransformStream())
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(
createFlightDataInjectionTransformStream(inlinedDataStream, true)
)
// Close tags should always be deferred to the end
.pipeThrough(createMoveSuffixStream())
)
}
type ContinueResumeOptions = { type ContinueResumeOptions = {
inlinedDataStream: ReadableStream<Uint8Array> inlinedDataStream: ReadableStream<Uint8Array>
getServerInsertedHTML: () => Promise<string> getServerInsertedHTML: () => Promise<string>
......
...@@ -4,6 +4,7 @@ import type { ...@@ -4,6 +4,7 @@ import type {
FocusAndScrollRef, FocusAndScrollRef,
PrefetchKind, PrefetchKind,
} from '../../client/components/router-reducer/router-reducer-types' } from '../../client/components/router-reducer/router-reducer-types'
import type { Params } from '../../server/request/params'
import type { import type {
FlightRouterState, FlightRouterState,
FlightSegmentPath, FlightSegmentPath,
...@@ -61,6 +62,7 @@ export const LayoutRouterContext = React.createContext<{ ...@@ -61,6 +62,7 @@ export const LayoutRouterContext = React.createContext<{
parentTree: FlightRouterState parentTree: FlightRouterState
parentCacheNode: CacheNode parentCacheNode: CacheNode
parentSegmentPath: FlightSegmentPath | null parentSegmentPath: FlightSegmentPath | null
parentParams: Params
url: string url: string
isActive: boolean isActive: boolean
} | null>(null) } | null>(null)
......
...@@ -25,7 +25,7 @@ describe('Lazy Module Init', () => { ...@@ -25,7 +25,7 @@ describe('Lazy Module Init', () => {
expect(next.cliOutput).toContain('○ /server') expect(next.cliOutput).toContain('○ /server')
expect(next.cliOutput).toContain('○ /client') expect(next.cliOutput).toContain('○ /client')
expect(next.cliOutput).toContain('◐ /client-page') expect(next.cliOutput).toContain('○ /client-page')
expect(next.cliOutput).toContain('◐ /[dyn]') expect(next.cliOutput).toContain('◐ /[dyn]')
let $ let $
......
...@@ -238,13 +238,13 @@ describe('Cache Components Errors', () => { ...@@ -238,13 +238,13 @@ describe('Cache Components Errors', () => {
at ScrollAndFocusHandler (bundler:///<next-src>) at ScrollAndFocusHandler (bundler:///<next-src>)
at RenderFromTemplateContext (bundler:///<next-src>) at RenderFromTemplateContext (bundler:///<next-src>)
at OuterLayoutRouter (bundler:///<next-src>) at OuterLayoutRouter (bundler:///<next-src>)
335 | */ 337 | */
336 | function InnerLayoutRouter({ 338 | function InnerLayoutRouter({
> 337 | tree, > 339 | tree,
| ^ | ^
338 | segmentPath, 340 | segmentPath,
339 | cacheNode, 341 | cacheNode,
340 | url, 342 | params,
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/dynamic-metadata-error-route" in your browser to investigate the error. To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/dynamic-metadata-error-route" in your browser to investigate the error.
Error occurred prerendering page "/dynamic-metadata-error-route". Read more: https://nextjs.org/docs/messages/prerender-error Error occurred prerendering page "/dynamic-metadata-error-route". Read more: https://nextjs.org/docs/messages/prerender-error
...@@ -745,13 +745,13 @@ describe('Cache Components Errors', () => { ...@@ -745,13 +745,13 @@ describe('Cache Components Errors', () => {
at ScrollAndFocusHandler (bundler:///<next-src>) at ScrollAndFocusHandler (bundler:///<next-src>)
at RenderFromTemplateContext (bundler:///<next-src>) at RenderFromTemplateContext (bundler:///<next-src>)
at OuterLayoutRouter (bundler:///<next-src>) at OuterLayoutRouter (bundler:///<next-src>)
335 | */ 337 | */
336 | function InnerLayoutRouter({ 338 | function InnerLayoutRouter({
> 337 | tree, > 339 | tree,
| ^ | ^
338 | segmentPath, 340 | segmentPath,
339 | cacheNode, 341 | cacheNode,
340 | url, 342 | params,
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/dynamic-root" in your browser to investigate the error. To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/dynamic-root" in your browser to investigate the error.
Error occurred prerendering page "/dynamic-root". Read more: https://nextjs.org/docs/messages/prerender-error Error occurred prerendering page "/dynamic-root". Read more: https://nextjs.org/docs/messages/prerender-error
...@@ -2141,13 +2141,13 @@ describe('Cache Components Errors', () => { ...@@ -2141,13 +2141,13 @@ describe('Cache Components Errors', () => {
at ScrollAndFocusHandler (bundler:///<next-src>) at ScrollAndFocusHandler (bundler:///<next-src>)
at RenderFromTemplateContext (<anonymous>) at RenderFromTemplateContext (<anonymous>)
at OuterLayoutRouter (bundler:///<next-src>) at OuterLayoutRouter (bundler:///<next-src>)
335 | */ 337 | */
336 | function InnerLayoutRouter({ 338 | function InnerLayoutRouter({
> 337 | tree, > 339 | tree,
| ^ | ^
338 | segmentPath, 340 | segmentPath,
339 | cacheNode, 341 | cacheNode,
340 | url, 342 | params,
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/sync-attribution/unguarded-async-guarded-clientsync" in your browser to investigate the error. To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/sync-attribution/unguarded-async-guarded-clientsync" in your browser to investigate the error.
Error occurred prerendering page "/sync-attribution/unguarded-async-guarded-clientsync". Read more: https://nextjs.org/docs/messages/prerender-error Error occurred prerendering page "/sync-attribution/unguarded-async-guarded-clientsync". Read more: https://nextjs.org/docs/messages/prerender-error
...@@ -3157,13 +3157,13 @@ describe('Cache Components Errors', () => { ...@@ -3157,13 +3157,13 @@ describe('Cache Components Errors', () => {
at ScrollAndFocusHandler (bundler:///<next-src>) at ScrollAndFocusHandler (bundler:///<next-src>)
at RenderFromTemplateContext (bundler:///<next-src>) at RenderFromTemplateContext (bundler:///<next-src>)
at OuterLayoutRouter (bundler:///<next-src>) at OuterLayoutRouter (bundler:///<next-src>)
335 | */ 337 | */
336 | function InnerLayoutRouter({ 338 | function InnerLayoutRouter({
> 337 | tree, > 339 | tree,
| ^ | ^
338 | segmentPath, 340 | segmentPath,
339 | cacheNode, 341 | cacheNode,
340 | url, 342 | params,
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/use-cache-private-without-suspense" in your browser to investigate the error. To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/use-cache-private-without-suspense" in your browser to investigate the error.
Error occurred prerendering page "/use-cache-private-without-suspense". Read more: https://nextjs.org/docs/messages/prerender-error Error occurred prerendering page "/use-cache-private-without-suspense". Read more: https://nextjs.org/docs/messages/prerender-error
......
...@@ -18,7 +18,7 @@ export default function Page({ searchParams }: { searchParams: Promise<any> }) { ...@@ -18,7 +18,7 @@ export default function Page({ searchParams }: { searchParams: Promise<any> }) {
<p> <p>
Without PPR this page is fully dynamic because a dynamic API was used. Without PPR this page is fully dynamic because a dynamic API was used.
</p> </p>
<Suspense fallback={<Fallback>loading...</Fallback>}> <Suspense fallback={<div id="fallback-component-one-">loading...</div>}>
<ComponentOne searchParams={searchParams} /> <ComponentOne searchParams={searchParams} />
</Suspense> </Suspense>
<Suspense fallback={<Fallback>loading too...</Fallback>}> <Suspense fallback={<Fallback>loading too...</Fallback>}>
......
...@@ -113,7 +113,12 @@ describe('cache-components', () => { ...@@ -113,7 +113,12 @@ describe('cache-components', () => {
} }
}) })
it('should partially prerender pages that use params in a client components', async () => { // Since #85155, we intentionally omit search params from client segments
// if the page is otherwise static, and resume using a client fetch
// instead. So it's expected that the value is missing pre-hydration.
// There are separate tests that verify that it is eventually hydrated.
// TODO: Rewrite or update this test.
it.skip('should partially prerender pages that use params in a client components', async () => {
expect(getLines('Route "/params')).toEqual([]) expect(getLines('Route "/params')).toEqual([])
let $ = await next.render$( let $ = await next.render$(
...@@ -291,7 +296,12 @@ describe('cache-components', () => { ...@@ -291,7 +296,12 @@ describe('cache-components', () => {
} }
}) })
it('should fully prerender pages that check individual param keys after `use`ing params in a client component', async () => { // Since #85155, we intentionally omit search params from client segments
// if the page is otherwise static, and resume using a client fetch
// instead. So it's expected that the value is missing pre-hydration.
// There are separate tests that verify that it is eventually hydrated.
// TODO: Rewrite or update this test.
it.skip('should fully prerender pages that check individual param keys after `use`ing params in a client component', async () => {
expect(getLines('Route "/params')).toEqual([]) expect(getLines('Route "/params')).toEqual([])
let $ = await next.render$( let $ = await next.render$(
'/params/semantics/one/build/layout-has/client' '/params/semantics/one/build/layout-has/client'
...@@ -475,7 +485,12 @@ describe('cache-components', () => { ...@@ -475,7 +485,12 @@ describe('cache-components', () => {
} }
}) })
it('should partially prerender pages that spread `use`ed params in a client component', async () => { // Since #85155, we intentionally omit search params from client segments
// if the page is otherwise static, and resume using a client fetch
// instead. So it's expected that the value is missing pre-hydration.
// There are separate tests that verify that it is eventually hydrated.
// TODO: Rewrite or update this test.
it.skip('should partially prerender pages that spread `use`ed params in a client component', async () => {
expect(getLines('Route "/params')).toEqual([]) expect(getLines('Route "/params')).toEqual([])
let $ = await next.render$( let $ = await next.render$(
'/params/semantics/one/build/layout-spread/client' '/params/semantics/one/build/layout-spread/client'
...@@ -611,7 +626,12 @@ describe('cache-components', () => { ...@@ -611,7 +626,12 @@ describe('cache-components', () => {
} }
}) })
it('should correctly allow param names like then, value, and status when `use`ing params in a client component', async () => { // Since #85155, we intentionally omit search params from client segments
// if the page is otherwise static, and resume using a client fetch
// instead. So it's expected that the value is missing pre-hydration.
// There are separate tests that verify that it is eventually hydrated.
// TODO: Rewrite or update this test.
it.skip('should correctly allow param names like then, value, and status when `use`ing params in a client component', async () => {
expect(getLines('Route "/params')).toEqual([]) expect(getLines('Route "/params')).toEqual([])
let $ = await next.render$( let $ = await next.render$(
'/params/shadowing/foo/bar/baz/qux/layout/client' '/params/shadowing/foo/bar/baz/qux/layout/client'
......
...@@ -50,8 +50,15 @@ describe('cache-components', () => { ...@@ -50,8 +50,15 @@ describe('cache-components', () => {
expect($('#layout').text()).toBe('at buildtime') expect($('#layout').text()).toBe('at buildtime')
expect($('main').text()).toContain('inner loading...') expect($('main').text()).toContain('inner loading...')
expect($('main').text()).not.toContain('outer loading...') expect($('main').text()).not.toContain('outer loading...')
expect($('#value').text()).toBe('hello') // Since #85155, we intentionally omit search params from client segments
expect($('#page').text()).toBe('at runtime') // if the page is otherwise static, and resume using a client fetch
// instead. So it's expected that the value is missing pre-hydration.
// There are separate tests that verify that it is eventually hydrated.
// TODO: Rewrite or update this test.
// expect($('#value').text()).toBe('hello')
// expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toBe('')
expect($('#page').text()).toBe('')
} }
}) })
}) })
...@@ -259,7 +259,11 @@ describe('cache-components', () => { ...@@ -259,7 +259,11 @@ describe('cache-components', () => {
// The second component renders before the first one aborts so we end up // The second component renders before the first one aborts so we end up
// capturing the static value during buildtime // capturing the static value during buildtime
expect($('#inner').text()).toBe('at buildtime') expect($('#inner').text()).toBe('at buildtime')
expect($('#value').text()).toBe('my sentinel') // Since there was no dynamic data access on this page, the search params
// are completely ommitted from the HTML document and filled in by
// the client
expect($('#value').text()).toBe('')
expect($('#fallback-component-one-').text()).toBe('loading...')
} }
}) })
......
'use client'
import { Suspense, use } from 'react'
function Content({
params,
searchParams,
}: {
params: Promise<{ product: string }>
searchParams: Promise<{ foo: string }>
}) {
const { product } = use(params)
const searchParamsDict = use(searchParams)
let query = null
if (Object.keys(searchParamsDict).length > 0) {
query = JSON.stringify(searchParamsDict)
}
return (
<>
<p id="product">Product: {product}</p>
<p id="query">Query: {query ? query : '(none)'}</p>
</>
)
}
export default function ProductPage({
params,
searchParams,
}: {
params: Promise<{ product: string }>
searchParams: Promise<{ foo: string }>
}) {
return (
<Suspense fallback="Loading...">
<Content params={params} searchParams={searchParams} />
</Suspense>
)
}
'use client'
import { Suspense, use } from 'react'
function Content({ params }: { params: Promise<{ category: string }> }) {
const { category } = use(params)
return <h1 id="category-header">Category: {category}</h1>
}
export default function CategoryLayout({
params,
children,
}: {
params: Promise<{ category: string }>
children: React.ReactNode
}) {
return (
<div>
<Suspense fallback="Loading...">
<Content params={params} />
</Suspense>
{children}
</div>
)
}
'use client'
import { Suspense, use } from 'react'
function Content({ searchParams }: { searchParams: Promise<{ foo: string }> }) {
const searchParamsDict = use(searchParams)
let query = null
if (Object.keys(searchParamsDict).length > 0) {
query = JSON.stringify(searchParamsDict)
}
return (
<>
<p id="query">Query: {query ? query : '(none)'}</p>
</>
)
}
export default function ClientPageWithSearchParam({
searchParams,
}: {
searchParams: Promise<{ foo: string }>
}) {
return (
<Suspense fallback="Loading...">
<Content searchParams={searchParams} />
</Suspense>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<>
<ul>
<li>
<LinkAccordion href="/clothing/1">/clothing/1</LinkAccordion>
</li>
<li>
<LinkAccordion href="/clothing/2">/clothing/2</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shoes/3">/shoes/3</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shoes/4?foo=bar">
/shoes/4?foo=bar
</LinkAccordion>
</li>
</ul>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('client params', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('prefetching is disabled', () => {})
return
}
it('client segments that access dynamic params are fully statically prefetchable', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch the page. Although this page access dynamic params, it only
// does so inside segments that are marked with "use cache". So we should
// be able to fully prefetch them, without invoking a dynamic server render.
const toggleLinkVisibility = await browser.elementByCss(
'input[data-link-accordion="/clothing/1"]'
)
await act(async () => {
await toggleLinkVisibility.click()
})
// Navigate to the fully prefetched page. There should be no
// additionalrequest.
const link = await browser.elementByCss('a[href="/clothing/1"]')
await act(async () => {
await link.click()
}, 'no-requests')
// Confirm the dynamic params were correctly rendered by the client.
const categoryHeader = await browser.elementById('category-header')
expect(await categoryHeader.text()).toBe('Category: clothing')
const product = await browser.elementById('product')
expect(await product.text()).toBe('Product: 1')
})
})
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
cacheComponents: true,
},
}
module.exports = nextConfig
...@@ -32,6 +32,7 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -32,6 +32,7 @@ export const expectedWhenTrailingSlashTrue = [
'404.html', '404.html',
'404/index.html', '404/index.html',
'__next.__PAGE__.txt', '__next.__PAGE__.txt',
'__next._full.txt',
'__next._index.txt', '__next._index.txt',
'__next._tree.txt', '__next._tree.txt',
// Turbopack and plain next.js have different hash output for the file name // Turbopack and plain next.js have different hash output for the file name
...@@ -45,16 +46,19 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -45,16 +46,19 @@ export const expectedWhenTrailingSlashTrue = [
? ['_next/static/test-build-id/_clientMiddlewareManifest.json'] ? ['_next/static/test-build-id/_clientMiddlewareManifest.json']
: []), : []),
'_next/static/test-build-id/_ssgManifest.js', '_next/static/test-build-id/_ssgManifest.js',
'_not-found/__next._full.txt',
'_not-found/__next._index.txt', '_not-found/__next._index.txt',
'_not-found/__next._not-found.__PAGE__.txt', '_not-found/__next._not-found.__PAGE__.txt',
'_not-found/__next._not-found.txt', '_not-found/__next._not-found.txt',
'_not-found/__next._tree.txt', '_not-found/__next._tree.txt',
'_not-found/index.html', '_not-found/index.html',
'_not-found/index.txt', '_not-found/index.txt',
'another/__next._full.txt',
'another/__next._index.txt', 'another/__next._index.txt',
'another/__next._tree.txt', 'another/__next._tree.txt',
'another/__next.another.__PAGE__.txt', 'another/__next.another.__PAGE__.txt',
'another/__next.another.txt', 'another/__next.another.txt',
'another/first/__next._full.txt',
'another/first/__next._index.txt', 'another/first/__next._index.txt',
'another/first/__next._tree.txt', 'another/first/__next._tree.txt',
'another/first/__next.another.$d$slug.__PAGE__.txt', 'another/first/__next.another.$d$slug.__PAGE__.txt',
...@@ -64,6 +68,7 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -64,6 +68,7 @@ export const expectedWhenTrailingSlashTrue = [
'another/first/index.txt', 'another/first/index.txt',
'another/index.html', 'another/index.html',
'another/index.txt', 'another/index.txt',
'another/second/__next._full.txt',
'another/second/__next._index.txt', 'another/second/__next._index.txt',
'another/second/__next._tree.txt', 'another/second/__next._tree.txt',
'another/second/__next.another.$d$slug.__PAGE__.txt', 'another/second/__next.another.$d$slug.__PAGE__.txt',
...@@ -73,6 +78,7 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -73,6 +78,7 @@ export const expectedWhenTrailingSlashTrue = [
'another/second/index.txt', 'another/second/index.txt',
'api/json', 'api/json',
'api/txt', 'api/txt',
'client/__next._full.txt',
'client/__next._index.txt', 'client/__next._index.txt',
'client/__next._tree.txt', 'client/__next._tree.txt',
'client/__next.client.__PAGE__.txt', 'client/__next.client.__PAGE__.txt',
...@@ -80,6 +86,7 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -80,6 +86,7 @@ export const expectedWhenTrailingSlashTrue = [
'client/index.html', 'client/index.html',
'client/index.txt', 'client/index.txt',
'favicon.ico', 'favicon.ico',
'image-import/__next._full.txt',
'image-import/__next._index.txt', 'image-import/__next._index.txt',
'image-import/__next._tree.txt', 'image-import/__next._tree.txt',
'image-import/__next.image-import.__PAGE__.txt', 'image-import/__next.image-import.__PAGE__.txt',
...@@ -94,6 +101,7 @@ export const expectedWhenTrailingSlashTrue = [ ...@@ -94,6 +101,7 @@ export const expectedWhenTrailingSlashTrue = [
const expectedWhenTrailingSlashFalse = [ const expectedWhenTrailingSlashFalse = [
'404.html', '404.html',
'__next.__PAGE__.txt', '__next.__PAGE__.txt',
'__next._full.txt',
'__next._index.txt', '__next._index.txt',
'__next._tree.txt', '__next._tree.txt',
// Turbopack will output favicon in the _next/static/media folder // Turbopack will output favicon in the _next/static/media folder
...@@ -108,18 +116,21 @@ const expectedWhenTrailingSlashFalse = [ ...@@ -108,18 +116,21 @@ const expectedWhenTrailingSlashFalse = [
'_next/static/test-build-id/_ssgManifest.js', '_next/static/test-build-id/_ssgManifest.js',
'_not-found.html', '_not-found.html',
'_not-found.txt', '_not-found.txt',
'_not-found/__next._full.txt',
'_not-found/__next._index.txt', '_not-found/__next._index.txt',
'_not-found/__next._not-found.__PAGE__.txt', '_not-found/__next._not-found.__PAGE__.txt',
'_not-found/__next._not-found.txt', '_not-found/__next._not-found.txt',
'_not-found/__next._tree.txt', '_not-found/__next._tree.txt',
'another.html', 'another.html',
'another.txt', 'another.txt',
'another/__next._full.txt',
'another/__next._index.txt', 'another/__next._index.txt',
'another/__next._tree.txt', 'another/__next._tree.txt',
'another/__next.another.__PAGE__.txt', 'another/__next.another.__PAGE__.txt',
'another/__next.another.txt', 'another/__next.another.txt',
'another/first.html', 'another/first.html',
'another/first.txt', 'another/first.txt',
'another/first/__next._full.txt',
'another/first/__next._index.txt', 'another/first/__next._index.txt',
'another/first/__next._tree.txt', 'another/first/__next._tree.txt',
'another/first/__next.another.$d$slug.__PAGE__.txt', 'another/first/__next.another.$d$slug.__PAGE__.txt',
...@@ -127,6 +138,7 @@ const expectedWhenTrailingSlashFalse = [ ...@@ -127,6 +138,7 @@ const expectedWhenTrailingSlashFalse = [
'another/first/__next.another.txt', 'another/first/__next.another.txt',
'another/second.html', 'another/second.html',
'another/second.txt', 'another/second.txt',
'another/second/__next._full.txt',
'another/second/__next._index.txt', 'another/second/__next._index.txt',
'another/second/__next._tree.txt', 'another/second/__next._tree.txt',
'another/second/__next.another.$d$slug.__PAGE__.txt', 'another/second/__next.another.$d$slug.__PAGE__.txt',
...@@ -136,6 +148,7 @@ const expectedWhenTrailingSlashFalse = [ ...@@ -136,6 +148,7 @@ const expectedWhenTrailingSlashFalse = [
'api/txt', 'api/txt',
'client.html', 'client.html',
'client.txt', 'client.txt',
'client/__next._full.txt',
'client/__next._index.txt', 'client/__next._index.txt',
'client/__next._tree.txt', 'client/__next._tree.txt',
'client/__next.client.__PAGE__.txt', 'client/__next.client.__PAGE__.txt',
...@@ -143,6 +156,7 @@ const expectedWhenTrailingSlashFalse = [ ...@@ -143,6 +156,7 @@ const expectedWhenTrailingSlashFalse = [
'favicon.ico', 'favicon.ico',
'image-import.html', 'image-import.html',
'image-import.txt', 'image-import.txt',
'image-import/__next._full.txt',
'image-import/__next._index.txt', 'image-import/__next._index.txt',
'image-import/__next._tree.txt', 'image-import/__next._tree.txt',
'image-import/__next.image-import.__PAGE__.txt', 'image-import/__next.image-import.__PAGE__.txt',
......
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