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

Hydrate page loads during instant navigation testing (#91207)

Previously, MPA page loads (reload, anchor navigation) while the instant
navigation lock was held would skip hydration entirely and hard-reload
when the lock released. This meant the page was non-interactive during
the locked period and tests couldn't assert on the hydrated React tree.

Now the page actually hydrates from the static shell. The server injects
a script that fetches the static RSC payload, and the client uses
createFromFetch with allowPartialStream so React can hydrate without
erroring on the incomplete Suspense boundaries. When the lock is
released, a soft refresh fetches the dynamic data (falling back to hard
reload if the router hasn't initialized yet).

Also refactors the cookie protocol to encode the lock state as a JSON
array (`[0]` = pending, `[1, null]` = captured MPA, `[1, {}]` = captured
SPA) for better integration with the devtools UI. This is somewhat
entangled with the hydration changes so they're grouped together, but
can be reviewed as atomic commits.
parent 0b5f67d7
......@@ -146,6 +146,7 @@
"@next/polyfill-module": "workspace:*",
"@next/polyfill-nomodule": "workspace:*",
"@next/swc": "workspace:*",
"@next/playwright": "workspace:*",
"@next/third-parties": "workspace:*",
"@opentelemetry/api": "1.4.1",
"@picocss/pico": "1.5.10",
......
......@@ -16,7 +16,12 @@ interface PlaywrightBrowserContext {
path?: string
}>
): Promise<void>
clearCookies(options?: { name?: string }): Promise<void>
cookies(): Promise<Array<{ name: string; value: string }>>
clearCookies(options?: {
name?: string
domain?: string
path?: string
}): Promise<void>
}
interface PlaywrightPage {
......@@ -52,6 +57,17 @@ export async function instant<T>(
fn: () => Promise<T>,
options?: { baseURL?: string }
): Promise<T> {
// Check for nested instant() calls. The cookie is scoped to the browser
// context, so we can detect nesting by checking if it's already set.
const existingCookies = await page.context().cookies()
if (existingCookies.some((c) => c.name === INSTANT_COOKIE)) {
throw new Error(
'An instant() scope is already active. Nesting instant() ' +
'calls is not supported. Did you forget to await the ' +
'previous instant() call?'
)
}
// Acquire the lock by setting the cookie via the browser context. This
// ensures the cookie is present even on the very first navigation.
// The cookie triggers the CookieStore change event in
......@@ -61,16 +77,16 @@ export async function instant<T>(
page
.context()
.addCookies([
{ name: INSTANT_COOKIE, value: '1', domain: hostname, path: '/' },
{ name: INSTANT_COOKIE, value: '[0]', domain: hostname, path: '/' },
])
)
try {
return await fn()
} finally {
// Release the lock by clearing the cookie. For SPA navigations, this
// triggers the CookieStore change event which resolves the in-memory
// lock. For MPA navigations (reload, plain anchor), the listener in
// app-bootstrap.ts triggers a page reload to fetch dynamic data.
// Release the lock by clearing the cookie. Next.js may have updated the
// cookie value (e.g. from [0] to [1,null]) during the lock scope. We
// clear by name to remove the cookie regardless of its current value or
// which domain variant it was stored under.
await step('Release Instant Lock', () =>
page.context().clearCookies({ name: INSTANT_COOKIE })
)
......
......@@ -354,7 +354,6 @@ export async function handler(
// with blocking happening on the client side.
const isInstantNavigationTest =
exposeTestingApi &&
couldSupportPPR &&
(req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' ||
(req.headers[RSC_HEADER] === undefined &&
typeof req.headers.cookie === 'string' &&
......@@ -363,7 +362,11 @@ export async function handler(
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled: boolean =
couldSupportPPR &&
// When the instant navigation testing API is active, enable the PPR
// prerender path even without Cache Components. In dev mode without CC,
// static pages need this path to produce buffered segment data (the
// legacy prerender path hangs in dev mode).
(couldSupportPPR || isInstantNavigationTest) &&
((
prerenderManifest.routes[normalizedSrcPage] ??
prerenderManifest.dynamicRoutes[normalizedSrcPage]
......@@ -1522,19 +1525,26 @@ export async function handler(
// This is a request for HTML data.
const body = cachedData.html
// When serving a static shell for instant navigation testing, inject
// self.__next_instant_test=1 as the first thing inside <head> so the
// client can detect the static shell. This must be before any async
// bootstrap scripts — otherwise a cached async script can execute
// before the global is set.
//
// TODO: Currently the client skips hydration entirely during
// instant navigation testing. Ideally we would still hydrate but
// without the dynamic data — the static shell is valid HTML that
// could be hydrated. This is just an implementation gap; the
// page gets reloaded when the instant scope ends anyway.
// Instant Navigation Testing API: serve the static shell with an
// injected script that sets self.__next_instant_test and kicks off a
// static RSC fetch for hydration. The transform stream also appends
// closing </body></html> tags so the browser can parse the full document.
// In dev mode, also inject self.__next_r so the HMR WebSocket and
// debug channel can initialize.
if (isInstantNavigationTest && isDebugStaticShell) {
body.pipeThrough(createInstantTestScriptInsertionTransformStream())
const instantTestRequestId =
routeModule.isDev === true ? crypto.randomUUID() : null
body.pipeThrough(
createInstantTestScriptInsertionTransformStream(instantTestRequestId)
)
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: { revalidate: 0, expire: undefined },
})
}
// If there's no postponed state, we should just serve the HTML. This
......@@ -1571,22 +1581,16 @@ export async function handler(
// HTML will be the static shell so all the Dynamic API's will be used
// during static generation.
if (isDebugStaticShell || isDebugDynamicAccesses) {
if (!isInstantNavigationTest) {
// Since we're not resuming the render, we need to at least add the
// closing body and html tags to create valid HTML.
body.push(
new ReadableStream({
start(controller) {
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
controller.close()
},
})
)
}
// When in instant navigation testing mode, we intentionally omit
// the closing </body></html> tags so the client interprets the
// response as a partial stream rather than a complete document
// with incoherent content.
// Since we're not resuming the render, we need to at least add the
// closing body and html tags to create valid HTML.
body.push(
new ReadableStream({
start(controller) {
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
controller.close()
},
})
)
return sendRenderResult({
req,
......
......@@ -76,32 +76,6 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
}
}
// Instant Navigation Testing: When the cookie is set, set up a
// CookieStore listener that auto-reloads when the cookie is cleared.
// This is shared infrastructure for both the dev tools toggle and
// external test frameworks.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing'
if (
document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
typeof cookieStore !== 'undefined'
) {
cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
for (const cookie of event.deleted) {
if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
window.location.reload()
return
}
}
})
} else if (self.__next_instant_test) {
// The server returned a static shell but we couldn't set up the
// cookie listener (document.cookie is empty or cookieStore is
// unavailable). Reload immediately to get the full response.
window.location.reload()
}
}
hydrate(assetPrefix)
})
}
......@@ -37,6 +37,14 @@ const createFromFetch =
const appElement: HTMLElement | Document = document
// Instant Navigation Testing API: captured once at module init. When truthy,
// this is the fetch promise for the static RSC payload (set by an injected
// <script> tag in the static shell HTML).
const instantTestStaticFetch: Promise<Response> | undefined =
self.__next_instant_test
? (self.__next_instant_test as unknown as Promise<Response>)
: undefined
const encoder = new TextEncoder()
let initialServerDataBuffer: (string | Uint8Array)[] | undefined = undefined
......@@ -120,12 +128,20 @@ function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val)
})
if (initialServerDataLoaded && !initialServerDataFlushed) {
// Instant Navigation Testing API: don't close or error the inline
// Flight stream. The static shell has no inline Flight data, so the
// stream is empty. Closing it would cause React to log an error about
// missing data. Leaving it open lets React treat any holes as
// "still suspended." Hydration uses the separately fetched RSC payload
// (self.__next_instant_test), not this stream.
if (isStreamErrorOrUnfinished(ctr)) {
ctr.error(
new Error(
'The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.'
if (!instantTestStaticFetch) {
ctr.error(
new Error(
'The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.'
)
)
)
}
} else {
ctr.close()
}
......@@ -204,12 +220,35 @@ if (
debugChannel = createDebugChannel(undefined)
}
const clientResumeFetch: Promise<Response> | undefined =
let initialServerResponse: Promise<InitialRSCPayload>
if (instantTestStaticFetch) {
// Instant Navigation Testing API: hydrate from the static RSC payload
// fetch kicked off by an injected <script> tag, instead of the inline
// Flight data (which is not present in the static shell).
initialServerResponse = Promise.resolve(
createFromFetch<InitialRSCPayload>(instantTestStaticFetch, {
callServer,
findSourceMapURL,
debugChannel,
// The static fetch response is a partial stream (static-only Flight
// data with no dynamic content). Allow it to close without error so
// React treats dynamic holes as still-suspended rather than
// triggering error recovery.
unstable_allowPartialStream: true,
})
).then(async (initialRSCPayload) => {
return createInitialRSCPayloadFromFallbackPrerender(
await instantTestStaticFetch,
initialRSCPayload
)
})
} else if (
// @ts-expect-error
window.__NEXT_CLIENT_RESUME
let initialServerResponse: Promise<InitialRSCPayload>
if (clientResumeFetch) {
) {
const clientResumeFetch: Promise<Response> =
// @ts-expect-error
window.__NEXT_CLIENT_RESUME
initialServerResponse = Promise.resolve(
createFromFetch<InitialRSCPayload>(clientResumeFetch, {
callServer,
......
......@@ -13,22 +13,6 @@ const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
// Instant Navigation Mode: When the server returned a partial static shell
// (indicated by the __next_instant_test global), skip app hydration and only
// render the dev overlay so the developer can toggle the mode off. Hydration
// would fail because the static shell response doesn't include the full
// Flight data stream.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator
)
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks, assetPrefix)
......
......@@ -9,28 +9,6 @@ window.next.turbopack = true
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
// Instant Navigation Mode: The server returned a partial static shell.
// Skip hydration — the response doesn't include the full Flight data
// stream. In dev mode, still render the dev overlay so the developer can
// toggle the mode off.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { getOwnerStack } =
require('../next-devtools/userspace/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error')
const { renderAppDevOverlay } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator
)
}
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks, assetPrefix)
......
......@@ -8,15 +8,6 @@ const instrumentationHooks =
require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
// Instant Navigation Mode: The server returned a partial static shell.
// Skip hydration — the response doesn't include the full Flight data
// stream. The cookie listener in app-bootstrap handles the reload.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
// Include app-router and layout-router in the main chunk
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
......
......@@ -1649,6 +1649,7 @@ async function fetchMissingDynamicData(
seed.head,
result.debugInfo
)
return {
exitStatus: didReceiveUnknownParallelRoute
? NavigationTaskExitStatus.SoftRetry
......
......@@ -25,7 +25,7 @@ export function refreshReducer(
// preserve prefetched data when refreshing after an MPA navigation. This is
// only used for testing and is not exposed in production builds by default.
const bypassCacheInvalidation =
process.env.__NEXT_EXPOSE_TESTING_API && action.devBypassCacheInvalidation
process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation
if (!bypassCacheInvalidation) {
const currentNextUrl = state.nextUrl
const currentRouterState = state.tree
......
......@@ -35,7 +35,7 @@ export interface RefreshAction {
* Testing API to preserve prefetched data when refreshing after an MPA
* navigation. Not exposed in production builds by default.
*/
devBypassCacheInvalidation?: boolean
bypassCacheInvalidation?: boolean
}
export interface HmrRefreshAction {
......
/**
* Navigation lock for the Instant Navigation Testing API.
*
* This module is not meant to be used directly. It's exposed via a cookie-based
* protocol intended to be driven by an e2e testing framework like Playwright:
* Manages the in-memory lock (a promise) that gates dynamic data writes
* during instant navigation captures, and owns all cookie state
* transitions (pending → captured-MPA, pending → captured-SPA).
*
* async function instant(page, fn) {
* const context = page.context()
* const domain = new URL(page.url()).hostname
* await context.addCookies([{
* name: 'next-instant-navigation-testing',
* value: '1',
* domain,
* path: '/',
* }])
* try {
* return await fn()
* } finally {
* await context.clearCookies({
* name: 'next-instant-navigation-testing',
* })
* }
* }
* The cookie value is a JSON array:
* [0] — pending (waiting to capture)
* [1, null] — captured MPA page load
* [1, { from, to }] — captured SPA navigation (from/to route trees)
*
* // Usage in a test:
* await instant(page, async () => {
* await page.click('a[href="/product"]')
* await expect(page.locator('[data-testid="loading"]')).toBeVisible()
* })
*
* Next.js never writes to the cookie — it only reads and listens for changes
* via the CookieStore API's `change` event.
*
* When the lock is acquired:
* - Routes without a prefetch cache hit will wait for prefetch to complete
* before navigating.
* - Routes with a prefetch cache hit will wait before writing dynamic data
* into the UI.
*
* For MPA navigations (page reload, full page load):
* - The cookie tells the server to render only the static shell.
* - When the lock is released (cookie deleted), the page reloads to fetch
* dynamic data (handled in app-bootstrap.ts).
*
* This allows tests to assert on the prefetched UI state before dynamic
* content streams in. Network requests are not blocked — they proceed in
* parallel while the lock is held.
*
* All functions in this module are wrapped in checks for the testing API,
* which is not exposed in production builds by default. This ensures the code
* is dead code eliminated unless explicitly enabled.
* External actors (Playwright, devtools) set [0] to start a lock scope
* and delete the cookie to end one. Next.js writes captured values.
* The CookieStore handler distinguishes them by value: pending = external,
* captured = self-write (ignored).
*/
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
type InstantNavCookieState = 'pending' | 'mpa' | 'spa'
function parseCookieValue(raw: string): InstantNavCookieState {
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) {
return parsed[1] === null ? 'mpa' : 'spa'
}
} catch {}
return 'pending'
}
function writeCookieValue(value: unknown[]): void {
if (typeof cookieStore === 'undefined') {
return
}
// Read the existing cookie to preserve its attributes (domain, path),
// then write back with the new value. This updates the same cookie
// entry that the external actor created, regardless of how it was
// scoped.
cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {
if (existing) {
const options: any = {
name: NEXT_INSTANT_TEST_COOKIE,
value: JSON.stringify(value),
path: existing.path ?? '/',
}
if (existing.domain) {
options.domain = existing.domain
}
cookieStore.set(options)
}
})
}
type NavigationLockState = {
promise: Promise<void>
......@@ -61,6 +63,9 @@ type NavigationLockState = {
let lockState: NavigationLockState | null = null
function acquireLock(): void {
if (lockState !== null) {
return
}
let resolve: () => void
const promise = new Promise<void>((r) => {
resolve = r
......@@ -68,42 +73,65 @@ function acquireLock(): void {
lockState = { promise, resolve: resolve! }
}
function releaseLock(): void {
if (lockState !== null) {
lockState.resolve()
lockState = null
}
}
/**
* Starts listening for changes to the instant navigation test cookie via the
* CookieStore API. When the cookie is added (by the test framework), the
* in-memory lock is acquired. When the cookie is deleted, the lock is released.
* Sets up the cookie-based lock. Handles the initial page load state and
* registers a CookieStore listener for runtime changes.
*
* This should be called once during page initialization.
* Called once during page initialization from app-globals.ts.
*/
export function startListeningForInstantNavigationCookie(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// If the server served a static shell, this is an MPA page load
// while the lock is held. Transition to captured-MPA and acquire.
if (self.__next_instant_test) {
if (typeof cookieStore !== 'undefined') {
// If the cookie was already cleared during the MPA page
// transition, reload to get the full dynamic page.
cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {
if (!cookie) {
window.location.reload()
}
})
}
writeCookieValue([1, null])
acquireLock()
}
if (typeof cookieStore === 'undefined') {
return
}
cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
// Check if our cookie was added
for (const cookie of event.changed) {
if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
if (lockState !== null) {
console.error(
'Navigation lock already acquired. Concurrent locks ' +
'are not allowed. Did you forget to release the ' +
'previous lock?'
)
const state = parseCookieValue(cookie.value ?? '')
if (state !== 'pending') {
// Captured value — our own transition. Ignore.
return
}
// Pending value — external actor starting a new lock scope.
if (lockState !== null) {
releaseLock()
}
acquireLock()
return
}
}
// Check if our cookie was deleted
for (const cookie of event.deleted) {
if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
if (lockState !== null) {
lockState.resolve()
lockState = null
}
releaseLock()
refreshOnInstantNavigationUnlock()
return
}
}
......@@ -112,13 +140,40 @@ export function startListeningForInstantNavigationCookie(): void {
}
/**
* Returns true if the navigation lock is currently active. Checks the cookie
* rather than in-memory lockState because the cookie survives across MPA
* navigations (page reloads). Returns false when the testing API is disabled.
* Transitions the cookie from pending to captured-SPA. Called when a
* client-side navigation is captured by the lock.
*
* @param fromTree - The flight router state of the from-route
* @param toTree - The flight router state of the to-route (null if not yet known)
*/
export function transitionToCapturedSPA(
fromTree: FlightRouterState,
toTree: FlightRouterState | null
): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }])
}
}
/**
* Updates the captured-SPA cookie with the resolved route trees.
* Called after the prefetch resolves and the target route tree is known.
*/
export function updateCapturedSPAToTree(
fromTree: FlightRouterState,
toTree: FlightRouterState
): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }])
}
}
/**
* Returns true if the navigation lock is currently active.
*/
export function isNavigationLocked(): boolean {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
return document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')
return lockState !== null
}
return false
}
......
......@@ -56,6 +56,57 @@ export function navigate(
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): AppRouterState | Promise<AppRouterState> {
// Instant Navigation Testing API: when the lock is active, ensure a
// prefetch task has been initiated before proceeding with the navigation.
// This guarantees that segment data requests are at least pending, even
// for routes that already have a cached route tree. Without this, the
// static shell might be incomplete because some segments were never
// requested.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
if (isNavigationLocked()) {
return ensurePrefetchThenNavigate(
state,
url,
currentUrl,
currentRenderedSearch,
currentCacheNode,
currentFlightRouterState,
nextUrl,
freshnessPolicy,
shouldScroll,
navigateType
)
}
}
return navigateImpl(
state,
url,
currentUrl,
currentRenderedSearch,
currentCacheNode,
currentFlightRouterState,
nextUrl,
freshnessPolicy,
shouldScroll,
navigateType
)
}
function navigateImpl(
state: AppRouterState,
url: URL,
currentUrl: URL,
currentRenderedSearch: string,
currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState,
nextUrl: string | null,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): AppRouterState | Promise<AppRouterState> {
const now = Date.now()
const href = url.href
......@@ -306,27 +357,6 @@ async function navigateToUnknownRoute(
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): Promise<AppRouterState> {
// If the Instant Navigation Testing API lock is active, try to prefetch the
// route first. If the prefetch succeeds, navigate using the prefetched route
// tree. If it fails, fall through to the normal path.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const prefetchResult = await tryNavigateUsingTestingAPIPrefetch(
state,
url,
currentUrl,
currentRenderedSearch,
nextUrl,
currentCacheNode,
currentFlightRouterState,
freshnessPolicy,
shouldScroll,
navigateType
)
if (prefetchResult !== null) {
return prefetchResult
}
}
// Runs when a navigation happens but there's no cached prefetch we can use.
// Don't bother to wait for a prefetch response; go straight to a full
// navigation that contains both static and dynamic data in a single stream.
......@@ -841,44 +871,40 @@ function convertServerPatchToFullTreeImpl(
}
/**
* Helper for the Instant Navigation Testing API. If the navigation lock is
* active, schedules a prefetch task, waits for it to complete, and navigates
* using the prefetched route tree.
*
* Returns the new router state if navigation succeeded via prefetch, or null
* if the lock isn't active or the prefetch failed (caller should fall through
* to the normal unknown route path).
* Instant Navigation Testing API: ensures a prefetch task has been initiated
* and completed before proceeding with the navigation. This guarantees that
* segment data requests are at least pending, even for routes whose route
* tree is already cached.
*
* Not exposed in production builds by default.
* After the prefetch completes, delegates to the normal navigation flow.
*/
async function tryNavigateUsingTestingAPIPrefetch(
async function ensurePrefetchThenNavigate(
state: AppRouterState,
url: URL,
currentUrl: URL,
currentRenderedSearch: string,
nextUrl: string | null,
currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState,
nextUrl: string | null,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): Promise<AppRouterState | null> {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Lazy require to ensure dead code elimination
const { isNavigationLocked } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
if (!isNavigationLocked()) {
return null
}
): Promise<AppRouterState> {
const link = getLinkForCurrentNavigation()
const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR
// Use the link's fetch strategy so the test behavior matches what would
// happen if the route had been prefetched before navigation
const link = getLinkForCurrentNavigation()
const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR
// Transition the cookie to captured-SPA immediately, before waiting
// for the prefetch. This ensures the devtools panel can update its UI
// right away, even if the prefetch takes time (e.g. dev compilation).
// The "to" tree starts as null and is filled in after the prefetch
// resolves and the navigation produces a new router state.
const { transitionToCapturedSPA, updateCapturedSPAToTree } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
transitionToCapturedSPA(currentFlightRouterState, null)
const cacheKey = createCacheKey(url.href, nextUrl)
const { promise, resolve } = Promise.withResolvers<void>()
const cacheKey = createCacheKey(url.href, nextUrl)
await new Promise<void>((resolve) => {
schedulePrefetchTask(
cacheKey,
currentFlightRouterState,
......@@ -887,37 +913,26 @@ async function tryNavigateUsingTestingAPIPrefetch(
null, // onInvalidate
resolve // _onComplete callback
)
})
await promise
// Prefetch is complete. Proceed with the normal navigation flow, which
// will now find the route in the cache.
const result = await navigateImpl(
state,
url,
currentUrl,
currentRenderedSearch,
currentCacheNode,
currentFlightRouterState,
nextUrl,
freshnessPolicy,
shouldScroll,
navigateType
)
// Re-read from cache (should now be populated)
const now = Date.now()
const route = readRouteCacheEntry(now, cacheKey)
if (route !== null && route.status === EntryStatus.Fulfilled) {
return navigateUsingPrefetchedRouteTree(
now,
state,
url,
currentUrl,
currentRenderedSearch,
nextUrl,
currentCacheNode,
currentFlightRouterState,
freshnessPolicy,
shouldScroll,
navigateType,
route
)
}
// Update the cookie with the resolved "to" tree so the devtools
// panel can display both routes immediately.
updateCapturedSPAToTree(currentFlightRouterState, result.tree)
// Prefetch failed. Wait for the lock to be released before falling
// through to the normal navigation path. This prevents runtime data
// from leaking into the shell while the lock is held — the navigation
// blocks until the instant scope ends, then proceeds normally.
const { waitForNavigationLockIfActive } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
await waitForNavigationLockIfActive()
return null
}
return null
return result
}
......@@ -2,10 +2,11 @@ import type { Dispatch } from 'react'
import React, { use, useMemo, useOptimistic } from 'react'
import { isThenable } from '../../shared/lib/is-thenable'
import type { AppRouterActionQueue } from './app-router-instance'
import type {
AppRouterState,
ReducerActions,
ReducerState,
import {
ACTION_REFRESH,
type AppRouterState,
type ReducerActions,
type ReducerState,
} from './router-reducer/router-reducer-types'
// The app router state lives outside of React, so we can import the dispatch
......@@ -13,6 +14,22 @@ import type {
// or context.
let dispatch: Dispatch<ReducerActions> | null = null
/**
* Called when the instant navigation test lock is released. If the router
* is initialized, dispatches a soft refresh to fetch dynamic data. If not
* (e.g. the lock was released before hydration finished), falls back to a
* hard reload.
*/
export function refreshOnInstantNavigationUnlock() {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (dispatch !== null) {
dispatch({ type: ACTION_REFRESH, bypassCacheInvalidation: true })
} else {
window.location.reload()
}
}
}
export function dispatchAppRouterAction(action: ReducerActions) {
if (dispatch === null) {
throw new Error(
......
......@@ -7,6 +7,11 @@ import { reportGlobalError } from './report-global-error'
const recoverableErrors = new WeakSet<Error>()
const isInstantTest =
process.env.__NEXT_EXPOSE_TESTING_API &&
typeof self !== 'undefined' &&
!!self.__next_instant_test
export function isRecoverableError(error: Error): boolean {
return recoverableErrors.has(error)
}
......@@ -19,6 +24,21 @@ export const onRecoverableError: HydrationOptions['onRecoverableError'] = (
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(cause)) return
// Instant Navigation Testing API: suppress "server could not finish this
// Suspense boundary" errors (React error #419) during instant test mode.
// The static shell intentionally has incomplete Suspense boundaries — React
// correctly falls back to client rendering, which is expected.
if (isInstantTest) {
if (isError(cause)) {
if (process.env.NODE_ENV === 'production') {
if (cause.message.includes('#419')) return
} else {
if (cause.message.includes('could not finish this Suspense boundary'))
return
}
}
}
if (process.env.NODE_ENV !== 'production') {
const { decorateDevError } =
require('../../next-devtools/userspace/app/errors/stitched-error') as typeof import('../../next-devtools/userspace/app/errors/stitched-error')
......
......@@ -25,6 +25,7 @@ import {
ACTION_INSTANT_NAVS_TOGGLE,
} from './dev-overlay/shared'
import type { FlightRouterState } from '../shared/lib/app-router-types'
import {
createContext,
startTransition,
......@@ -73,7 +74,10 @@ export interface Dispatcher {
renderingIndicatorShow(): void
segmentExplorerNodeAdd(nodeState: SegmentNodeState): void
segmentExplorerNodeRemove(nodeState: SegmentNodeState): void
segmentExplorerUpdateRouteState(page: string): void
segmentExplorerUpdateRouteState(
page: string,
tree: FlightRouterState | null
): void
instantNavsToggle(): void
}
......@@ -222,8 +226,8 @@ export const dispatcher: Dispatcher = {
}
),
segmentExplorerUpdateRouteState: createQueuable(
(dispatch: Dispatch, page: string) => {
dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page })
(dispatch: Dispatch, page: string, tree: FlightRouterState | null) => {
dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page, tree })
}
),
instantNavsToggle: createQueuable((dispatch: Dispatch) => {
......
/**
* Cookie reading and subscription for the instant navigation devtools panel.
*
* The cookie value is a JSON array:
* [0] — pending (waiting to capture)
* [1, null] — captured MPA page load
* [1, { from, to }] — captured SPA navigation (from/to route trees)
*
* The "to" tree may be null initially and updated after the prefetch resolves.
*/
import { useMemo } from 'react'
import { useSyncExternalStore } from 'react'
import type {
FlightRouterState,
Segment,
} from '../../../../shared/lib/app-router-types'
const COOKIE_NAME = 'next-instant-navigation-testing'
export type InstantNavCookieData =
| { state: 'pending' }
| { state: 'mpa' }
| {
state: 'spa'
fromTree: FlightRouterState
toTree: FlightRouterState | null
}
function parseCookieValue(raw: string): InstantNavCookieData {
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) {
if (parsed[1] === null) {
return { state: 'mpa' }
}
// SPA capture: parsed[1] is { from, to }
if (typeof parsed[1] === 'object' && parsed[1] !== null) {
const fromTree: FlightRouterState = parsed[1].from ?? ['', {}]
const toTree: FlightRouterState | null = parsed[1].to ?? null
return { state: 'spa', fromTree, toTree }
}
return { state: 'spa', fromTree: ['', {}], toTree: null }
}
} catch {}
return { state: 'pending' }
}
export function readInstantNavCookieState():
| InstantNavCookieData['state']
| null {
if (typeof document === 'undefined') return null
const match = document.cookie.match(/next-instant-navigation-testing=([^;]*)/)
if (!match) return null
return parseCookieValue(match[1]).state
}
/**
* Formats a FlightRouterState tree into a route pattern string for display.
* Dynamic segments are shown with bracket syntax (e.g. [slug], [...params],
* [[...optional]]) rather than their filled-in values. Search params are
* omitted because they don't affect navigation.
*/
export function formatRoutePattern(tree: FlightRouterState): string {
const segments: string[] = []
let current: FlightRouterState | undefined = tree
while (current) {
const segment: Segment = current[0]
const children: Record<string, FlightRouterState> | undefined = current[1]
if (typeof segment === 'string') {
// Skip root segment (''), page sentinels, default sentinels,
// and route groups (parenthesized segments like "(marketing)")
if (
segment !== '' &&
!segment.startsWith('__PAGE__') &&
segment !== '__DEFAULT__' &&
!(segment.startsWith('(') && segment.endsWith(')'))
) {
segments.push(segment)
}
} else if (Array.isArray(segment)) {
// Dynamic segment tuple: [paramName, paramCacheKey, dynamicParamType, staticSiblings]
const paramName = segment[0]
const dynamicParamType = segment[2]
if (dynamicParamType === 'c' || dynamicParamType.startsWith('ci')) {
// Catch-all: [...param]
segments.push(`[...${paramName}]`)
} else if (dynamicParamType === 'oc') {
// Optional catch-all: [[...param]]
segments.push(`[[...${paramName}]]`)
} else {
// Dynamic: [param]
segments.push(`[${paramName}]`)
}
}
// Follow the children parallel route
current = children?.children
}
return '/' + segments.join('/')
}
// The raw cookie string is used as the useSyncExternalStore snapshot.
// Strings are compared by value, so no referential stability concerns.
// Parsing happens during render via useMemo.
// Cache the latest raw cookie value observed from CookieStore events.
// document.cookie may not reflect async cookieStore.set() writes
// immediately, so the snapshot reads this cache first.
let cachedRawValue: string | undefined = undefined
function readRawCookieValue(): string {
if (typeof document === 'undefined') return ''
const match = document.cookie.match(/next-instant-navigation-testing=([^;]*)/)
return match ? match[1] : ''
}
function getSnapshot(): string {
if (cachedRawValue !== undefined) {
return cachedRawValue
}
return readRawCookieValue()
}
function subscribe(callback: () => void): () => void {
if (typeof cookieStore === 'undefined') {
return () => {}
}
function handler(event: CookieChangeEvent) {
for (const cookie of event.changed) {
if (cookie.name === COOKIE_NAME) {
cachedRawValue = cookie.value ?? ''
callback()
return
}
}
for (const cookie of event.deleted) {
if (cookie.name === COOKIE_NAME) {
cachedRawValue = ''
callback()
return
}
}
}
cookieStore.addEventListener('change', handler)
return () => {
cookieStore.removeEventListener('change', handler)
}
}
/**
* Subscribes to the instant navigation cookie value. The cookie is the
* sole source of truth — this hook reads it via useSyncExternalStore.
*
* The raw cookie string is the snapshot (stable by value comparison).
* Parsing into structured data happens during render via useMemo.
*
* Returns null when the cookie is absent.
*/
export function useInstantNavCookieState(): InstantNavCookieData | null {
const rawValue = useSyncExternalStore(subscribe, getSnapshot)
return useMemo(() => {
if (!rawValue) return null
return parseCookieValue(rawValue)
}, [rawValue])
}
......@@ -167,3 +167,29 @@
.instant-nav-footer-button:hover {
background: var(--color-gray-200);
}
/* Shimmer skeleton for pending "to" route */
@keyframes instant-nav-shimmer {
0% {
background-position: -400px 0;
}
100% {
background-position: 400px 0;
}
}
.instant-nav-skeleton {
display: inline-block;
width: 120px;
height: 1em;
vertical-align: middle;
border-radius: 4px;
background: linear-gradient(
90deg,
var(--color-gray-300) 25%,
var(--color-blue-300) 50%,
var(--color-gray-300) 75%
);
background-size: 800px 100%;
animation: instant-nav-shimmer 1.5s ease-in-out infinite;
}
import { useReducer } from 'react'
import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { VersionInfo } from '../../server/dev/parse-version-info'
import type { SupportedErrorEvent } from './container/runtime-error/render-error'
import type { DebugInfo } from '../shared/types'
......@@ -7,6 +8,7 @@ import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-ser
import { parseStack } from '../../server/lib/parse-stack'
import { isConsoleError } from '../shared/console-error'
import type { CacheIndicatorState } from './cache-indicator'
import { readInstantNavCookieState } from './components/instant-navs/instant-nav-cookie'
export type DevToolsConfig = {
theme?: 'light' | 'dark' | 'system'
......@@ -68,18 +70,10 @@ export interface OverlayState {
>
readonly scale: number
readonly page: string
readonly tree: FlightRouterState | null
readonly theme: 'light' | 'dark' | 'system'
readonly hideShortcut: string | null
readonly instantNavs: boolean
readonly instantNavsPanel:
| { readonly status: 'waiting' }
| { readonly status: 'client-nav-waiting' }
| { readonly status: 'initial-load'; readonly toUrl: string }
| {
readonly status: 'client-nav'
readonly fromUrl: string
readonly toUrl: string
}
}
type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent>
......@@ -112,7 +106,6 @@ export const ACTION_DEVTOOLS_SCALE = 'devtools-scale'
export const ACTION_DEVTOOLS_CONFIG = 'devtools-config'
export const ACTION_INSTANT_NAVS_TOGGLE = 'instant-navs-toggle'
export const ACTION_INSTANT_NAVS_SET_STATUS = 'instant-navs-set-status'
export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset'
export const STORAGE_KEY_PANEL_POSITION_PREFIX =
......@@ -222,6 +215,7 @@ interface DevToolsScaleAction {
interface DevToolUpdateRouteStateAction {
type: typeof ACTION_DEVTOOL_UPDATE_ROUTE_STATE
page: string
tree: FlightRouterState | null
}
interface DevToolsConfigAction {
......@@ -233,24 +227,6 @@ interface CacheOnlyToggleAction {
type: typeof ACTION_INSTANT_NAVS_TOGGLE
}
type InstantNavSetStatusAction =
| { type: typeof ACTION_INSTANT_NAVS_SET_STATUS; status: 'waiting' }
| {
type: typeof ACTION_INSTANT_NAVS_SET_STATUS
status: 'client-nav-waiting'
}
| {
type: typeof ACTION_INSTANT_NAVS_SET_STATUS
status: 'initial-load'
toUrl: string
}
| {
type: typeof ACTION_INSTANT_NAVS_SET_STATUS
status: 'client-nav'
fromUrl: string
toUrl: string
}
interface InstantNavResetAction {
type: typeof ACTION_INSTANT_NAVS_RESET
}
......@@ -281,7 +257,6 @@ export type DispatcherEvent =
| DevIndicatorSetAction
| DevToolsConfigAction
| CacheOnlyToggleAction
| InstantNavSetStatusAction
| InstantNavResetAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
......@@ -307,8 +282,7 @@ const devToolsInitialPositionFromNextConfig = (process.env
const hasInstantNavsCookie =
!!process.env.__NEXT_INSTANT_NAV_TOGGLE &&
typeof document !== 'undefined' &&
document.cookie.includes('next-instant-navigation-testing=')
readInstantNavCookieState() !== null
export const INITIAL_OVERLAY_STATE: Omit<
OverlayState,
......@@ -342,18 +316,10 @@ export const INITIAL_OVERLAY_STATE: Omit<
devToolsPanelSize: {},
scale: NEXT_DEV_TOOLS_SCALE.Medium,
page: '',
tree: null,
theme: 'system',
hideShortcut: null,
instantNavs: hasInstantNavsCookie,
instantNavsPanel: hasInstantNavsCookie
? {
status: 'initial-load',
toUrl:
typeof window !== 'undefined'
? window.location.pathname + window.location.search
: '',
}
: { status: 'waiting' },
}
function getInitialState(
......@@ -539,7 +505,7 @@ export function useErrorOverlayReducer(
return { ...state, scale: action.scale }
}
case ACTION_DEVTOOL_UPDATE_ROUTE_STATE: {
return { ...state, page: action.page }
return { ...state, page: action.page, tree: action.tree }
}
case ACTION_DEVTOOLS_CONFIG: {
const {
......@@ -570,29 +536,8 @@ export function useErrorOverlayReducer(
case ACTION_INSTANT_NAVS_TOGGLE: {
return { ...state, instantNavs: !state.instantNavs }
}
case ACTION_INSTANT_NAVS_SET_STATUS: {
return {
...state,
instantNavsPanel:
action.status === 'waiting'
? { status: 'waiting' }
: action.status === 'client-nav-waiting'
? { status: 'client-nav-waiting' }
: action.status === 'initial-load'
? { status: 'initial-load', toUrl: action.toUrl }
: {
status: 'client-nav',
fromUrl: action.fromUrl,
toUrl: action.toUrl,
},
}
}
case ACTION_INSTANT_NAVS_RESET: {
return {
...state,
instantNavs: false,
instantNavsPanel: { status: 'waiting' },
}
return { ...state, instantNavs: false }
}
default: {
return state
......
......@@ -9,7 +9,6 @@ import {
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_CACHE_INDICATOR,
ACTION_INSTANT_NAVS_TOGGLE,
ACTION_INSTANT_NAVS_SET_STATUS,
ACTION_INSTANT_NAVS_RESET,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
......@@ -87,7 +86,6 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_RENDERING_INDICATOR_SHOW:
case ACTION_CACHE_INDICATOR:
case ACTION_INSTANT_NAVS_TOGGLE:
case ACTION_INSTANT_NAVS_SET_STATUS:
case ACTION_INSTANT_NAVS_RESET:
case ACTION_STATIC_INDICATOR:
case ACTION_UNHANDLED_ERROR:
......
......@@ -11,6 +11,7 @@ import {
} from 'react'
import { useLayoutEffect } from 'react'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import { GlobalLayoutRouterContext } from '../../../shared/lib/app-router-context.shared-runtime'
import { notFound } from '../../../client/components/not-found'
export type SegmentBoundaryType =
......@@ -73,12 +74,13 @@ function LoadingSegmentNode(): React.ReactNode {
}
export function SegmentViewStateNode({ page }: { page: string }) {
const { tree } = useContext(GlobalLayoutRouterContext)
useLayoutEffect(() => {
dispatcher.segmentExplorerUpdateRouteState(page)
dispatcher.segmentExplorerUpdateRouteState(page, tree)
return () => {
dispatcher.segmentExplorerUpdateRouteState('')
dispatcher.segmentExplorerUpdateRouteState('', null)
}
}, [page])
}, [page, tree])
return null
}
......
......@@ -19,6 +19,7 @@ import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_INSTANT_PREFETCH_HEADER,
} from '../../client/components/app-router-headers'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
......@@ -523,11 +524,32 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream<
* element inside <head>. Used during instant navigation testing to set
* self.__next_instant_test before any async bootstrap scripts execute.
*/
export function createInstantTestScriptInsertionTransformStream(): TransformStream<
Uint8Array,
Uint8Array
> {
const INSTANT_TEST_SCRIPT = '<script>self.__next_instant_test=1</script>'
export function createInstantTestScriptInsertionTransformStream(
requestId: string | null
): TransformStream<Uint8Array, Uint8Array> {
// Kick off a fetch for the static RSC payload. This is the hydration
// source for the locked static shell — same as the __NEXT_CLIENT_RESUME
// fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER
// so the server returns static-only data.
//
// The fetch promise is stored as self.__next_instant_test, which doubles
// as the feature flag (truthy = instant test mode). The client processes
// this as a fallback prerender payload for hydration.
const segmentPath = '/_full'
const cacheBustingHeader = computeCacheBustingSearchParam(
'1',
segmentPath,
undefined,
undefined
)
const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`
// In dev mode, inject self.__next_r (request ID) so that HMR WebSocket
// and debug channel initialization don't crash. The static shell
// bypasses renderToFizzStream which normally injects this via
// bootstrapScriptContent.
const requestIdScript =
requestId !== null ? `self.__next_r=${JSON.stringify(requestId)};` : ''
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}','${NEXT_INSTANT_PREFETCH_HEADER}':'1'}})</script>`
let didAlreadyInsert = false
return new TransformStream({
......@@ -560,7 +582,7 @@ export function createInstantTestScriptInsertionTransformStream(): TransformStre
const insertionPoint = headCloseAngle + 1
// e.g.
// chunk = <!DOCTYPE html><html><head><meta charset="utf-8">...
// insertion = <script>self.__next_instant_test=1</script>
// insertion = <script>self.__next_instant_test=fetch(...)</script>
// output = <!DOCTYPE html><html><head> [ <script>...</script> ] <meta charset="utf-8">...
const insertedHeadContent = new Uint8Array(
chunk.length + encodedInsertion.length
......@@ -575,6 +597,10 @@ export function createInstantTestScriptInsertionTransformStream(): TransformStre
controller.enqueue(insertedHeadContent)
didAlreadyInsert = true
},
flush(controller) {
// Append closing tags so the browser can parse the full document.
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
},
})
}
......
This diff is collapsed.
......@@ -145,7 +145,7 @@ describe('instant-nav-panel', () => {
// Cookie should now be set
await retry(async () => {
const cookie = await browser.eval(() => document.cookie)
expect(cookie).toContain('next-instant-navigation-testing=1')
expect(cookie).toContain('next-instant-navigation-testing=')
})
// Panel should show client-nav-waiting state
......@@ -192,12 +192,41 @@ describe('instant-nav-panel', () => {
document.querySelector<HTMLAnchorElement>('#link-to-target')!.click()
})
// The data fetching skeleton should be visible (dynamic content is locked)
// The data fetching skeleton should be visible (dynamic content is locked).
// Use a longer timeout because dev mode needs to compile the target page.
await retry(
async () => {
const skeleton = await browser.hasElementByCss(
'[data-testid="dynamic-skeleton"]'
)
expect(skeleton).toBe(true)
},
30000,
500
)
// Clean up
await clearInstantModeCookie(browser)
})
it('should auto-open panel on page load when cookie is already set', async () => {
const browser = await next.browser('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Open the panel and click Start to set the cookie
await openInstantNavPanel(browser)
await retry(async () => {
const skeleton = await browser.hasElementByCss(
'[data-testid="dynamic-skeleton"]'
)
expect(skeleton).toBe(true)
expect(await hasPanelOpen(browser)).toBe(true)
})
await clickStartClientNav(browser)
// Reload — the cookie persists, so the panel should auto-open
await browser.refresh()
await browser.waitForElementByCss('[data-testid="home-title"]')
await retry(async () => {
expect(await hasPanelOpen(browser)).toBe(true)
})
// Clean up
......
......@@ -42,11 +42,24 @@ describe('instant-navigation-testing-api', () => {
* Next.js test infra wraps Playwright with its own BrowserInterface, but
* the Instant Navigation Testing API is designed to work with native Playwright.
*/
async function openPage(url: string): Promise<Playwright.Page> {
async function openPage(
url: string,
options?: { cookies?: Array<{ name: string; value: string }> }
): Promise<Playwright.Page> {
let page: Playwright.Page
await next.browser(url, {
beforePageLoad(p) {
page = p
if (options?.cookies) {
const { hostname } = new URL(next.url)
p.context().addCookies(
options.cookies.map((c) => ({
...c,
domain: hostname,
path: '/',
}))
)
}
},
})
return page!
......@@ -134,23 +147,21 @@ describe('instant-navigation-testing-api', () => {
})
})
it('logs an error when attempting to nest instant scopes', async () => {
it('throws when attempting to nest instant scopes', async () => {
const page = await openPage('/')
// Listen for the specific error message
const consolePromise = page.waitForEvent('console', {
predicate: (msg) =>
msg.type() === 'error' && msg.text().includes('already acquired'),
timeout: 5000,
})
await instant(page, async () => {
// Attempt to acquire the lock again by nesting instant() calls.
// The inner call sets the cookie again, and the handler detects
// that the lock is already held, logging an error.
await instant(page, async () => {})
const msg = await consolePromise
expect(msg.text()).toContain('already acquired')
// The inner call detects the cookie is already set and throws
// before touching the browser state.
let caughtError: Error | undefined
try {
await instant(page, async () => {})
} catch (e) {
caughtError = e as Error
}
expect(caughtError).toBeDefined()
expect(caughtError!.message).toContain('already active')
})
})
......@@ -293,11 +304,8 @@ describe('instant-navigation-testing-api', () => {
// NOT be present.
describe('runtime params are excluded from instant shell', () => {
it('does not include cookie values in instant shell during client navigation', async () => {
const page = await openPage('/')
// Set a test cookie
await page.evaluate(() => {
document.cookie = 'testCookie=hello; path=/'
const page = await openPage('/', {
cookies: [{ name: 'testCookie', value: 'hello' }],
})
await instant(page, async () => {
......@@ -377,11 +385,8 @@ describe('instant-navigation-testing-api', () => {
})
it('does not include cookie values in instant shell during page load', async () => {
const page = await openPage('/')
// Set a test cookie
await page.evaluate(() => {
document.cookie = 'testCookie=hello; path=/'
const page = await openPage('/', {
cookies: [{ name: 'testCookie', value: 'hello' }],
})
await instant(page, async () => {
......
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