Unverified Commit f9d5df3b authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Fix crash with search params (#89922)

In dev validation, we're disassembling a payload from a dynamic render.
If the request had search params, page segments in the router state will
have them attached: `__PAGE__?{"q":"123"}`. In
`findNavigationsToValidate`, we do the equivalent of constructing a
flightRouterState, so we need to match that, otherwise we'll name the
segment `__PAGE__` instead and then can't look it up in the cache, and
crash during validation.
parent 14865920
...@@ -4178,7 +4178,8 @@ async function validateInstantConfigs( ...@@ -4178,7 +4178,8 @@ async function validateInstantConfigs(
try { try {
init = await findNavigationsToValidate( init = await findNavigationsToValidate(
ctx.componentMod.routeModule.userland.loaderTree, ctx.componentMod.routeModule.userland.loaderTree,
ctx.getDynamicParamFromSegment ctx.getDynamicParamFromSegment,
ctx.query
) )
} catch (err) { } catch (err) {
debug?.('Error while planning validations.') debug?.('Error while planning validations.')
......
...@@ -41,6 +41,8 @@ import { createDebugChannel } from '../debug-channel-server' ...@@ -41,6 +41,8 @@ import { createDebugChannel } from '../debug-channel-server'
import { createFromNodeStream } from 'react-server-dom-webpack/client' import { createFromNodeStream } from 'react-server-dom-webpack/client'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { renderToReadableStream } from 'react-server-dom-webpack/server' import { renderToReadableStream } from 'react-server-dom-webpack/server'
import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'
import type { NextParsedUrlQuery } from '../../request-meta'
const filterStackFrame = const filterStackFrame =
process.env.NODE_ENV !== 'production' process.env.NODE_ENV !== 'production'
...@@ -94,7 +96,8 @@ export type RouteTree = { ...@@ -94,7 +96,8 @@ export type RouteTree = {
* */ * */
export async function findNavigationsToValidate( export async function findNavigationsToValidate(
rootLoaderTree: LoaderTree, rootLoaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment,
query: NextParsedUrlQuery | null
) { ) {
type ValidationTask = { target: SegmentPath; parents: SegmentPath[] } type ValidationTask = { target: SegmentPath; parents: SegmentPath[] }
...@@ -104,9 +107,17 @@ export async function findNavigationsToValidate( ...@@ -104,9 +107,17 @@ export async function findNavigationsToValidate(
const segmentsWithInstantConfigs: SegmentPath[] = [] const segmentsWithInstantConfigs: SegmentPath[] = []
const treeNodes = new Map<SegmentPath, RouteTree>() const treeNodes = new Map<SegmentPath, RouteTree>()
function getSegment(loaderTree: LoaderTree): Segment { function getSegmentFromLoaderTree(loaderTree: LoaderTree): Segment {
const dynamicParam = getDynamicParamFromSegment(loaderTree) const dynamicParam = getDynamicParamFromSegment(loaderTree)
return dynamicParam ? dynamicParam.treeSegment : loaderTree[0] if (dynamicParam) {
return dynamicParam.treeSegment
}
const segment = loaderTree[0]
// In dev, the segment paths for all the page segments will include search params (`__PAGE__?{"q":"123"`}
// because the payload we're reassembling had them encoded in the router state,
// so we need to match that here.
// TODO(instant-validation): this will likely need some restructuring for build
return query ? addSearchParamsIfPageSegment(segment, query) : segment
} }
async function visit( async function visit(
...@@ -120,7 +131,7 @@ export async function findNavigationsToValidate( ...@@ -120,7 +131,7 @@ export async function findNavigationsToValidate(
const { mod: layoutOrPageMod, modType } = const { mod: layoutOrPageMod, modType } =
await getLayoutOrPageModule(loaderTree) await getLayoutOrPageModule(loaderTree)
const segment = getSegment(loaderTree) const segment = getSegmentFromLoaderTree(loaderTree)
const segmentPath = const segmentPath =
parentPath === null parentPath === null
? stringifySegment(segment) ? stringifySegment(segment)
...@@ -294,6 +305,8 @@ function traverseCacheNodeSegments( ...@@ -294,6 +305,8 @@ function traverseCacheNodeSegments(
} }
const childRoute = childRoutes[parallelRouteKey] const childRoute = childRoutes[parallelRouteKey]
// NOTE: if this is a __PAGE__ segment, it might have search params appended.
// Whoever reads from the cache needs to append them as well.
const [childSegment] = childRoute const [childSegment] = childRoute
const childPath = createChildSegmentPath( const childPath = createChildSegmentPath(
path, path,
......
...@@ -12,7 +12,10 @@ export default async function Page() { ...@@ -12,7 +12,10 @@ export default async function Page() {
<DebugLinks href="/suspense-in-root/runtime/suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/runtime/suspense-around-dynamic" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/runtime/no-suspense-around-params/123" /> <DebugLinks href="/suspense-in-root/runtime/valid-no-suspense-around-params/123" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-no-suspense-around-search-params?foo=bar" />
</li> </li>
<li> <li>
<DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic" /> <DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic" />
...@@ -48,6 +51,9 @@ export default async function Page() { ...@@ -48,6 +51,9 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-params/123" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-params/123" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-search-params?foo=bar" />
</li>
<li> <li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic-layout" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic-layout" />
</li> </li>
......
...@@ -11,11 +11,12 @@ export default async function Page({ ...@@ -11,11 +11,12 @@ export default async function Page({
}: { }: {
params: Promise<{ param: string }> params: Promise<{ param: string }>
}) { }) {
const { param } = await params
return ( return (
<main> <main>
<div> <div>
<p>Params don't need a suspense boundary when runtime-prefetched:</p> <p>Params don't need a suspense boundary when runtime-prefetched:</p>
<Runtime params={params} /> <div id="runtime-content">Param value: {param}</div>
</div> </div>
<div> <div>
...@@ -28,11 +29,6 @@ export default async function Page({ ...@@ -28,11 +29,6 @@ export default async function Page({
) )
} }
async function Runtime({ params }: { params: Promise<{ param: string }> }) {
const { param } = await params
return <div id="runtime-content">Param value: {param}</div>
}
async function Dynamic() { async function Dynamic() {
await connection() await connection()
return <div id="dynamic-content">Dynamic content from page</div> return <div id="dynamic-content">Dynamic content from page</div>
......
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>
}) {
const search = await searchParams
return (
<main>
<div>
<p>Params don't need a suspense boundary when runtime-prefetched:</p>
<div id="runtime-content">Search: {JSON.stringify(search)}</div>
</div>
<div>
<p>But dynamic content does:</p>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
export const unstable_instant = { prefetch: 'static' }
export default async function Page({ searchParams }) {
const search = await searchParams
return (
<main>
<p>
This page awaits search params, so it should fail validation. That isn't
really relevant here, we just need it to fail so that we can assert that
validation ran.
</p>
<div>Search: {JSON.stringify(search)}</div>
</main>
)
}
...@@ -267,9 +267,50 @@ describe.each([ ...@@ -267,9 +267,50 @@ describe.each([
} }
`) `)
}) })
it('valid - runtime prefetch - does not require Suspense around params', async () => { it('valid - runtime prefetch - does not require Suspense around params', async () => {
const browser = await navigateTo( const browser = await navigateTo(
'/suspense-in-root/runtime/no-suspense-around-params/123' '/suspense-in-root/runtime/valid-no-suspense-around-params/123'
)
await waitForNoErrorToast(browser)
})
it('invalid - static prefetch - missing suspense around search params', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/missing-suspense-around-search-params?foo=bar'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/missing-suspense-around-search-params/page.tsx (4:18) @ Page
> 4 | const search = await searchParams
| ^",
"stack": [
"Page app/suspense-in-root/static/missing-suspense-around-search-params/page.tsx (4:18)",
],
}
`)
})
it('valid - runtime prefetch - does not require Suspense around search params', async () => {
const browser = await navigateTo(
'/suspense-in-root/runtime/valid-no-suspense-around-search-params?foo=bar'
) )
await waitForNoErrorToast(browser) await waitForNoErrorToast(browser)
}) })
......
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