Skip to content

Commit 3177443

Browse files
authored
Make Instant Navigation Testing full-page loads work when deployed (#95222)
This makes full-page loads work under the Instant Navigation Testing API on a deployment, not just under `next dev` and `next start`. With the API active, a full-page load (a reload, an MPA navigation, or direct URL entry) on a deployment failed with a minified React hydration error, and releasing the lock then hard-reloaded the page instead of resolving client-side. Client-side navigations under the lock already worked; the gap was full-page loads. The API works by injecting an inline script that sets `self.__next_instant_test`, which the client reads at `app-index` init as its hydration source. That read only happens on a full-page load; client-side navigations go through the segment cache and the lock and never read it. The script was previously injected at request time through a transform stream, which runs only when the function renders the document. On a deployed full-page load the browser instead parses the prebuilt static prelude served from the edge cache, which was prerendered without the cookie and so carried no script, leaving `self.__next_instant_test` undefined. When the testing API is enabled (in development, or in a production build via `experimental.exposeTestingApiInProductionBuild`), we embed the cookie-guarded bootstrap into the prerendered prelude through React's `bootstrapScriptContent`, so it lands in the cached static shell and runs before the client bootstrap module. That production-build flag is meant for protected preview environments, so a normal production build never embeds the script, and even where it is embedded it stays inert on requests without the instant-navigation cookie (the prelude is shared across all requests). The same content is folded into the dynamic render path in `renderToStream`, and the now-redundant request-time transform is removed.
1 parent f15aa4e commit 3177443

9 files changed

Lines changed: 112 additions & 132 deletions

File tree

‎packages/next/src/build/templates/app-page.ts‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,6 @@ import {
8080
} from '../../lib/constants' with { 'turbopack-transition': 'next-server-utility' }
8181
import type { CacheControl } from '../../server/lib/cache-control'
8282
import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags' with { 'turbopack-transition': 'next-server-utility' }
83-
import { createInstantTestScriptInsertionTransformStream } from '../../server/stream-utils/node-web-streams-helper' with { 'turbopack-transition': 'next-server-utility' }
8483
import { sendRenderResult } from '../../server/send-payload' with { 'turbopack-transition': 'next-server-utility' }
8584
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external' with { 'turbopack-transition': 'next-server-utility' }
8685
import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit' with { 'turbopack-transition': 'next-server-utility' }
@@ -934,6 +933,7 @@ export async function handler(
934933
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
935934
nextConfig.experimental.maxPostponedStateSize
936935
),
936+
exposeTestingApi,
937937
},
938938

939939
waitUntil: ctx.waitUntil,
@@ -1875,12 +1875,13 @@ export async function handler(
18751875
// This is a request for HTML data.
18761876
const body = cachedData.html
18771877

1878-
// Instant Navigation Testing API: serve the static shell with an
1879-
// injected script that sets self.__next_instant_test and kicks off a
1880-
// static RSC fetch for hydration. The transform stream also appends
1881-
// closing </body></html> tags so the browser can parse the full document.
1882-
// In dev mode, also inject self.__next_r so the HMR WebSocket and
1883-
// debug channel can initialize.
1878+
// Instant Navigation Testing API: serve the static shell without resuming
1879+
// the dynamic render. The cookie-guarded bootstrap that sets
1880+
// self.__next_instant_test is embedded in the prerendered shell via
1881+
// `bootstrapScriptContent`, so it is already present (in the served shell
1882+
// for a fresh render, or in the cached prelude on deploy). Since the
1883+
// render is not resumed, append the closing tags so the browser can parse
1884+
// a complete document.
18841885
if (isInstantNavigationTest && isDebugStaticShell) {
18851886
// If the static shell came back empty, the page reads a dynamic value
18861887
// (e.g. `await cookies()`) at the root with no Suspense boundary above
@@ -1901,12 +1902,13 @@ export async function handler(
19011902
)
19021903
}
19031904

1904-
const instantTestRequestId =
1905-
routeModule.isDev === true ? crypto.randomUUID() : null
1906-
body.pipeThrough(
1907-
await createInstantTestScriptInsertionTransformStream(
1908-
instantTestRequestId
1909-
)
1905+
body.push(
1906+
new ReadableStream({
1907+
start(controller) {
1908+
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
1909+
controller.close()
1910+
},
1911+
})
19101912
)
19111913
return sendRenderResult({
19121914
req,

‎packages/next/src/build/templates/edge-ssr-app.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,9 @@ async function requestHandler(
184184
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
185185
nextConfig.experimental.maxPostponedStateSize
186186
),
187+
exposeTestingApi:
188+
pageRouteModule.isDev === true ||
189+
nextConfig.experimental.exposeTestingApiInProductionBuild === true,
187190
},
188191

189192
incrementalCache: await pageRouteModule.getIncrementalCache(

‎packages/next/src/export/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,8 @@ async function exportAppImpl(
523523
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
524524
nextConfig.experimental.maxPostponedStateSize
525525
),
526+
exposeTestingApi:
527+
nextConfig.experimental.exposeTestingApiInProductionBuild === true,
526528
},
527529
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
528530
}

‎packages/next/src/server/app-render/app-render.tsx‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import {
6565
createNodeInlinedDataStream,
6666
} from './stream-ops'
6767
import type { AnyStream } from './stream-ops'
68+
import { getInstantTestBootstrapScriptContent } from './instant-test-bootstrap'
6869
import { stripInternalQueries } from '../internal-utils'
6970
import {
7071
NEXT_HMR_REFRESH_HEADER,
@@ -3307,10 +3308,20 @@ async function renderToStream(
33073308
// bootstrap script is executed, which depends on it during hydration.
33083309
// For MPA navigations (page reload, direct URL entry), the request ID
33093310
// header is not present, so we generate a random one.
3310-
const bootstrapScriptContent = process.env.__NEXT_DEV_SERVER
3311+
let bootstrapScriptContent = process.env.__NEXT_DEV_SERVER
33113312
? `self.__next_r=${JSON.stringify(requestId ?? crypto.randomUUID())}`
33123313
: undefined
33133314

3315+
// Instant Navigation Testing API: embed the cookie-guarded bootstrap so it
3316+
// runs before the client bootstrap module reads self.__next_instant_test as
3317+
// its hydration source. This mirrors the prerender path so a dynamically
3318+
// rendered document carries the same script as the cached static prelude.
3319+
if (ctx.renderOpts.experimental.exposeTestingApi) {
3320+
bootstrapScriptContent =
3321+
(bootstrapScriptContent ? `${bootstrapScriptContent};` : '') +
3322+
(await getInstantTestBootstrapScriptContent())
3323+
}
3324+
33143325
// Create the "render route (app)" span manually so we can keep it open during streaming.
33153326
// This is necessary because errors inside Suspense boundaries are reported asynchronously
33163327
// during stream consumption, after a typical wrapped function would have ended the span.
@@ -7617,6 +7628,25 @@ async function prerenderToStream(
76177628
page
76187629
)
76197630

7631+
// Instant Navigation Testing API: when exposed, embed the cookie-guarded
7632+
// bootstrap into the prerendered prelude so the cached static shell carries
7633+
// it and it runs before the client bootstrap module reads
7634+
// self.__next_instant_test.
7635+
let bootstrapScriptContent = renderOpts.experimental.exposeTestingApi
7636+
? await getInstantTestBootstrapScriptContent()
7637+
: undefined
7638+
7639+
// In development the static shell is served without a dynamic resume, so it
7640+
// must carry the debug-channel request id (self.__next_r) itself for
7641+
// app-index to initialize the HMR/debug channel. renderToStream provides this
7642+
// for dynamic renders; prepend it here so it runs before the bootstrap
7643+
// module.
7644+
if (process.env.__NEXT_DEV_SERVER && bootstrapScriptContent) {
7645+
bootstrapScriptContent =
7646+
`self.__next_r=${JSON.stringify(ctx.requestId ?? crypto.randomUUID())};` +
7647+
bootstrapScriptContent
7648+
}
7649+
76207650
const { reactServerErrorsByDigest } = workStore
76217651
// We don't report errors during prerendering through our instrumentation hooks
76227652
const reportErrors = !experimental.isRoutePPREnabled
@@ -8415,6 +8445,7 @@ async function prerenderToStream(
84158445
},
84168446
onHeaders: finalClientOnHeaders,
84178447
maxHeadersLength: reactMaxHeadersLength,
8448+
bootstrapScriptContent,
84188449
bootstrapScripts: [bootstrapScript],
84198450
}
84208451
)
@@ -8635,6 +8666,7 @@ async function prerenderToStream(
86358666
onError: htmlRendererErrorHandler,
86368667
onHeaders: pprOnHeaders,
86378668
maxHeadersLength: reactMaxHeadersLength,
8669+
bootstrapScriptContent,
86388670
bootstrapScripts: [bootstrapScript],
86398671
}
86408672
)
@@ -8857,6 +8889,7 @@ async function prerenderToStream(
88578889
{
88588890
onError: htmlRendererErrorHandler,
88598891
nonce,
8892+
bootstrapScriptContent,
88608893
bootstrapScripts: [bootstrapScript],
88618894
},
88628895
{ waitForAllReady: true }
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import {
2+
RSC_HEADER,
3+
NEXT_ROUTER_PREFETCH_HEADER,
4+
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
5+
NEXT_RSC_UNION_QUERY,
6+
NEXT_INSTANT_TEST_COOKIE,
7+
} from '../../client/components/app-router-headers'
8+
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
9+
10+
/**
11+
* Builds the inline bootstrap script content for the Instant Navigation Testing
12+
* API. It is embedded via React's `bootstrapScriptContent` into the prerendered
13+
* shell (and dynamic renders) so that it ends up in the cached static prelude
14+
* and runs before the client bootstrap module (app-index) reads
15+
* self.__next_instant_test as its hydration source.
16+
*
17+
* The script is cookie-guarded so it is inert unless the instant test cookie is
18+
* present (the prelude is shared across all requests). The fetch mirrors the
19+
* __NEXT_CLIENT_RESUME prefetch used for fallback routes; the instant test
20+
* cookie rides along on the same-origin request, so the server returns
21+
* static-only data, which doubles as the feature flag (truthy = instant mode).
22+
*/
23+
export async function getInstantTestBootstrapScriptContent(): Promise<string> {
24+
const segmentPath = '/_full'
25+
const cacheBustingHeader = await computeCacheBustingSearchParam(
26+
'1',
27+
segmentPath,
28+
undefined,
29+
undefined
30+
)
31+
const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`
32+
return `if(document.cookie.indexOf('${NEXT_INSTANT_TEST_COOKIE}=')>-1){self.__next_instant_test=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}':'1','${NEXT_ROUTER_PREFETCH_HEADER}':'1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}':'${segmentPath}'}})}`
33+
}

‎packages/next/src/server/app-render/types.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,14 @@ export interface RenderOptsPartial {
178178
* requests. Used to calculate decompression limits (5x this value).
179179
*/
180180
maxPostponedStateSizeBytes: number | undefined
181+
182+
/**
183+
* Whether the Instant Navigation Testing API is exposed (dev mode or the
184+
* `exposeTestingApiInProductionBuild` flag). When true, the prerendered
185+
* shell and dynamic renders embed a cookie-guarded bootstrap script that
186+
* drives instant navigation tests.
187+
*/
188+
exposeTestingApi: boolean
181189
}
182190
postponed?: string
183191

‎packages/next/src/server/base-server.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,10 @@ export default abstract class Server<
592592
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
593593
this.nextConfig.experimental.maxPostponedStateSize
594594
),
595+
exposeTestingApi:
596+
this.dev === true ||
597+
this.nextConfig.experimental.exposeTestingApiInProductionBuild ===
598+
true,
595599
},
596600
onInstrumentationRequestError:
597601
this.instrumentationOnRequestError.bind(this),

‎packages/next/src/server/stream-utils/node-web-streams-helper.ts‎

Lines changed: 0 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -585,92 +585,6 @@ async function createClientResumeScriptInsertionTransformStream(): Promise<
585585
})
586586
}
587587

588-
/**
589-
* Creates a transform stream that injects an inline script as the first
590-
* element inside <head>. Used during instant navigation testing to set
591-
* self.__next_instant_test before any async bootstrap scripts execute.
592-
*/
593-
export async function createInstantTestScriptInsertionTransformStream(
594-
requestId: string | null
595-
): Promise<TransformStream<Uint8Array, Uint8Array>> {
596-
// Kick off a fetch for the static RSC payload. This is the hydration
597-
// source for the locked static shell — same as the __NEXT_CLIENT_RESUME
598-
// fetch used for fallback routes. The instant test cookie is sent
599-
// automatically with the same-origin fetch, so the server returns
600-
// static-only data.
601-
//
602-
// The fetch promise is stored as self.__next_instant_test, which doubles
603-
// as the feature flag (truthy = instant test mode). The client processes
604-
// this as a fallback prerender payload for hydration.
605-
const segmentPath = '/_full'
606-
const cacheBustingHeader = await computeCacheBustingSearchParam(
607-
'1',
608-
segmentPath,
609-
undefined,
610-
undefined
611-
)
612-
const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`
613-
// In dev mode, inject self.__next_r (request ID) so that HMR WebSocket
614-
// and debug channel initialization don't crash. The static shell
615-
// bypasses renderToFizzStream which normally injects this via
616-
// bootstrapScriptContent.
617-
const requestIdScript =
618-
requestId !== null ? `self.__next_r=${JSON.stringify(requestId)};` : ''
619-
const INSTANT_TEST_SCRIPT = `<script>${requestIdScript}self.__next_instant_test=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}':'1','${NEXT_ROUTER_PREFETCH_HEADER}':'1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}':'${segmentPath}'}})</script>`
620-
621-
let didAlreadyInsert = false
622-
return new TransformStream({
623-
transform(chunk, controller) {
624-
if (didAlreadyInsert) {
625-
// Already inserted the script into the head. Pass through.
626-
controller.enqueue(chunk)
627-
return
628-
}
629-
630-
// Find the opening <head tag (may have attributes like <head class="...">)
631-
const headOpenIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HEAD)
632-
633-
if (headOpenIndex === -1) {
634-
controller.enqueue(chunk)
635-
return
636-
}
637-
638-
// Find the closing > of the <head ...> tag
639-
const headCloseAngle = chunk.indexOf(
640-
62, // '>'
641-
headOpenIndex + ENCODED_TAGS.OPENING.HEAD.length
642-
)
643-
if (headCloseAngle === -1) {
644-
controller.enqueue(chunk)
645-
return
646-
}
647-
648-
const encodedInsertion = encoder.encode(INSTANT_TEST_SCRIPT)
649-
const insertionPoint = headCloseAngle + 1
650-
// e.g.
651-
// chunk = <!DOCTYPE html><html><head><meta charset="utf-8">...
652-
// insertion = <script>self.__next_instant_test=fetch(...)</script>
653-
// output = <!DOCTYPE html><html><head> [ <script>...</script> ] <meta charset="utf-8">...
654-
const insertedHeadContent = new Uint8Array(
655-
chunk.length + encodedInsertion.length
656-
)
657-
insertedHeadContent.set(chunk.slice(0, insertionPoint))
658-
insertedHeadContent.set(encodedInsertion, insertionPoint)
659-
insertedHeadContent.set(
660-
chunk.slice(insertionPoint),
661-
insertionPoint + encodedInsertion.length
662-
)
663-
664-
controller.enqueue(insertedHeadContent)
665-
didAlreadyInsert = true
666-
},
667-
flush(controller) {
668-
// Append closing tags so the browser can parse the full document.
669-
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
670-
},
671-
})
672-
}
673-
674588
// Suffix after main body content - scripts before </body>,
675589
// but wait for the major chunks to be enqueued.
676590
export function createDeferredSuffixStream(

0 commit comments

Comments
 (0)