Unverified Commit 953b4c51 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix potential race condition with request ID in dev mode (#84532)

In development mode, the request ID needs to be available before the
bootstrap script executes and triggers hydration. Previously, the
request ID was set inline with the flight data stream in a script tag
that was inserted after the bootstrap script, which could lead to a race
condition where `self.__next_r` was accessed before it was defined.

With this PR, we're moving the request ID initialization to
`bootstrapScriptContent`, which is inserted as a script tag by React
immediately before the bootstrap script. This ensures that the request
ID is always defined when the bootstrap script runs.

I wasn't actually able to reproduce the issue, so I also couldn't add a
test for it. But we did receive reports from users that this was
happening, which is plausible given the previous script order.
parent 665977f2
...@@ -2206,6 +2206,13 @@ async function renderToStream( ...@@ -2206,6 +2206,13 @@ async function renderToStream(
page page
) )
// In development mode, set the request ID as a global variable, before the
// bootstrap script is executed, which depends on it during hydration.
const bootstrapScriptContent =
process.env.NODE_ENV !== 'production'
? `self.__next_r=${JSON.stringify(requestId)}`
: undefined
const reactServerErrorsByDigest: Map<string, DigestedError> = new Map() const reactServerErrorsByDigest: Map<string, DigestedError> = new Map()
const silenceLogger = false const silenceLogger = false
function onHTMLRenderRSCError(err: DigestedError) { function onHTMLRenderRSCError(err: DigestedError) {
...@@ -2377,8 +2384,7 @@ async function renderToStream( ...@@ -2377,8 +2384,7 @@ async function renderToStream(
const inlinedReactServerDataStream = createInlinedDataReadableStream( const inlinedReactServerDataStream = createInlinedDataReadableStream(
reactServerResult.tee(), reactServerResult.tee(),
nonce, nonce,
formState, formState
requestId
) )
return chainStreams( return chainStreams(
...@@ -2425,8 +2431,7 @@ async function renderToStream( ...@@ -2425,8 +2431,7 @@ async function renderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consume(), reactServerResult.consume(),
nonce, nonce,
formState, formState
requestId
), ),
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
...@@ -2459,6 +2464,7 @@ async function renderToStream( ...@@ -2459,6 +2464,7 @@ async function renderToStream(
}) })
}, },
maxHeadersLength: reactMaxHeadersLength, maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent,
bootstrapScripts: [bootstrapScript], bootstrapScripts: [bootstrapScript],
formState, formState,
} }
...@@ -2495,8 +2501,7 @@ async function renderToStream( ...@@ -2495,8 +2501,7 @@ async function renderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consume(), reactServerResult.consume(),
nonce, nonce,
formState, formState
requestId
), ),
isStaticGeneration: generateStaticHTML, isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true, isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true,
...@@ -2613,6 +2618,7 @@ async function renderToStream( ...@@ -2613,6 +2618,7 @@ async function renderToStream(
), ),
streamOptions: { streamOptions: {
nonce, nonce,
bootstrapScriptContent,
// Include hydration scripts in the HTML // Include hydration scripts in the HTML
bootstrapScripts: [errorBootstrapScript], bootstrapScripts: [errorBootstrapScript],
formState, formState,
...@@ -2645,8 +2651,7 @@ async function renderToStream( ...@@ -2645,8 +2651,7 @@ async function renderToStream(
// render // render
reactServerResult.consume(), reactServerResult.consume(),
nonce, nonce,
formState, formState
requestId
), ),
isStaticGeneration: generateStaticHTML, isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true, isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true,
...@@ -3362,7 +3367,6 @@ async function prerenderToStream( ...@@ -3362,7 +3367,6 @@ async function prerenderToStream(
nonce, nonce,
pagePath, pagePath,
renderOpts, renderOpts,
requestId,
workStore, workStore,
} = ctx } = ctx
...@@ -4154,8 +4158,7 @@ async function prerenderToStream( ...@@ -4154,8 +4158,7 @@ async function prerenderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(), reactServerResult.consumeAsStream(),
nonce, nonce,
formState, formState
requestId
), ),
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
...@@ -4403,8 +4406,7 @@ async function prerenderToStream( ...@@ -4403,8 +4406,7 @@ async function prerenderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(), reactServerResult.consumeAsStream(),
nonce, nonce,
formState, formState
requestId
), ),
getServerInsertedHTML, getServerInsertedHTML,
getServerInsertedMetadata, getServerInsertedMetadata,
...@@ -4501,8 +4503,7 @@ async function prerenderToStream( ...@@ -4501,8 +4503,7 @@ async function prerenderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(), reactServerResult.consumeAsStream(),
nonce, nonce,
formState, formState
requestId
), ),
isStaticGeneration: true, isStaticGeneration: true,
isBuildTimePrerendering: isBuildTimePrerendering:
...@@ -4680,8 +4681,7 @@ async function prerenderToStream( ...@@ -4680,8 +4681,7 @@ async function prerenderToStream(
inlinedDataStream: createInlinedDataReadableStream( inlinedDataStream: createInlinedDataReadableStream(
flightStream, flightStream,
nonce, nonce,
formState, formState
requestId
), ),
isStaticGeneration: true, isStaticGeneration: true,
isBuildTimePrerendering: isBuildTimePrerendering:
......
...@@ -103,8 +103,7 @@ export function useFlightStream<T>( ...@@ -103,8 +103,7 @@ export function useFlightStream<T>(
export function createInlinedDataReadableStream( export function createInlinedDataReadableStream(
flightStream: ReadableStream<Uint8Array>, flightStream: ReadableStream<Uint8Array>,
nonce: string | undefined, nonce: string | undefined,
formState: unknown | null, formState: unknown | null
requestId: string
): ReadableStream<Uint8Array> { ): ReadableStream<Uint8Array> {
const startScriptTag = nonce const startScriptTag = nonce
? `<script nonce=${JSON.stringify(nonce)}>` ? `<script nonce=${JSON.stringify(nonce)}>`
...@@ -117,12 +116,7 @@ export function createInlinedDataReadableStream( ...@@ -117,12 +116,7 @@ export function createInlinedDataReadableStream(
type: 'bytes', type: 'bytes',
start(controller) { start(controller) {
try { try {
writeInitialInstructions( writeInitialInstructions(controller, startScriptTag, formState)
controller,
startScriptTag,
formState,
requestId
)
} catch (error) { } catch (error) {
// during encoding or enqueueing forward the error downstream // during encoding or enqueueing forward the error downstream
controller.error(error) controller.error(error)
...@@ -166,18 +160,12 @@ export function createInlinedDataReadableStream( ...@@ -166,18 +160,12 @@ export function createInlinedDataReadableStream(
function writeInitialInstructions( function writeInitialInstructions(
controller: ReadableStreamDefaultController, controller: ReadableStreamDefaultController,
scriptStart: string, scriptStart: string,
formState: unknown | null, formState: unknown | null
requestId: string
) { ) {
let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString( let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP]) JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])
)})` )})`
if (process.env.NODE_ENV !== 'production') {
// The request ID is only needed in development mode.
scriptContents = `self.__next_r=${JSON.stringify(requestId)};${scriptContents}`
}
if (formState != null) { if (formState != null) {
scriptContents += `;self.__next_f.push(${htmlEscapeJsonString( scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState]) JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])
......
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