Unverified Commit 56adc02e authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Use cookie as sole protocol for instant navigation testing (#89871)

The Instant Navigation Testing API already uses a cookie to persist lock
state across MPA navigations (page reloads, plain anchor links), since
window globals don't survive navigation. Rather than maintaining two
parallel mechanisms — a window global for SPA and a cookie for MPA —
this makes the cookie the single source of truth for all cases.

Playwright sets/clears the cookie directly via the browser context, and
the client reacts to changes through the CookieStore API's change event.
This removes the window.__EXPERIMENTAL_NEXT_TESTING__ global and the
page.evaluate() calls that went with it.
parent cd27e549
...@@ -1470,6 +1470,15 @@ export async function handler( ...@@ -1470,6 +1470,15 @@ export async function handler(
body.push( body.push(
new ReadableStream({ new ReadableStream({
start(controller) { start(controller) {
if (isInstantNavigationTest) {
// Inject a global so the client can detect that this response
// is a partial static shell, independent of document.cookie
// (which may be empty on the new page in some browsers).
const encoder = new TextEncoder()
controller.enqueue(
encoder.encode('<script>self.__next_instant_test=1</script>')
)
}
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML) controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
controller.close() controller.close()
}, },
......
...@@ -76,29 +76,32 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) { ...@@ -76,29 +76,32 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
} }
} }
// Instant Navigation Testing API: If the page was loaded with the instant // Instant Navigation Testing API: If the server returned a partial static
// test cookie set (from an MPA navigation while locked), skip hydration // shell (indicated by the __next_instant_test global injected into the
// and set up a minimal testing API. Hydration would fail because the // HTML), skip hydration. The response doesn't include the full Flight data
// static shell response doesn't include the full Flight data stream. // stream. When the test framework deletes the cookie, the CookieStore
// When unlock() is called, we clear the cookie and reload the page. // change event triggers a page reload.
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing' if (self.__next_instant_test) {
if (document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')) { const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing'
// Set up minimal testing API for the static shell if (
window.__EXPERIMENTAL_NEXT_TESTING__ = { typeof cookieStore !== 'undefined' &&
navigation: { document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')
lock: () => { ) {
console.error( // Cookie is still set. Wait for the test framework to delete it,
'Navigation lock already acquired. Concurrent locks are not allowed. ' + // then reload to get the full response.
'Did you forget to release the previous lock?' cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
) for (const cookie of event.deleted) {
}, if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
unlock: () => { window.location.reload()
// Clear the cookie and reload to get the full page with dynamic data return
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=;path=/;max-age=0` }
window.location.reload() }
}, })
}, } else {
// Cookie is already gone (or not accessible). Refresh immediately
// to get the full response.
window.location.reload()
} }
return return
} }
......
...@@ -6,16 +6,11 @@ if (process.env.__NEXT_DEV_SERVER) { ...@@ -6,16 +6,11 @@ if (process.env.__NEXT_DEV_SERVER) {
require('../next-devtools/userspace/app/app-dev-overlay-setup') as typeof import('../next-devtools/userspace/app/app-dev-overlay-setup') require('../next-devtools/userspace/app/app-dev-overlay-setup') as typeof import('../next-devtools/userspace/app/app-dev-overlay-setup')
} }
// Expose a testing API that allows e2e tests to assert on the prefetched UI // Start listening for the instant navigation test cookie. The test framework
// state before dynamic data streams in. Browser-only. // (e.g. Playwright) sets/clears this cookie to control the navigation lock.
// Browser-only.
if (process.env.__NEXT_EXPOSE_TESTING_API && typeof window !== 'undefined') { if (process.env.__NEXT_EXPOSE_TESTING_API && typeof window !== 'undefined') {
const { acquireNavigationLock, releaseNavigationLock } = const { startListeningForInstantNavigationCookie } =
require('./components/segment-cache/navigation-testing-lock') as typeof import('./components/segment-cache/navigation-testing-lock') require('./components/segment-cache/navigation-testing-lock') as typeof import('./components/segment-cache/navigation-testing-lock')
startListeningForInstantNavigationCookie()
window.__EXPERIMENTAL_NEXT_TESTING__ = {
navigation: {
lock: acquireNavigationLock,
unlock: releaseNavigationLock,
},
}
} }
...@@ -65,16 +65,6 @@ declare global { ...@@ -65,16 +65,6 @@ declare global {
*/ */
__next_r?: string __next_r?: string
__next_f: NextFlight __next_f: NextFlight
/**
* Testing API that allows e2e tests to assert on the prefetched UI state
* before dynamic data streams in. Dev-only.
*/
__EXPERIMENTAL_NEXT_TESTING__?: {
navigation: {
lock: () => void
unlock: () => void
}
}
} }
} }
......
/** /**
* Navigation lock for the Instant Navigation Testing API. * Navigation lock for the Instant Navigation Testing API.
* *
* This module is not meant to be used directly. It's exposed on the window * This module is not meant to be used directly. It's exposed via a cookie-based
* object and intended to be called via a wrapper API integrated into an * protocol intended to be driven by an e2e testing framework like Playwright:
* e2e testing framework like Playwright:
* *
* async function instant(page, fn) { * async function instant(page, fn) {
* await page.evaluate(() => window.__EXPERIMENTAL_NEXT_TESTING__.navigation.lock()) * const context = page.context()
* const domain = new URL(page.url()).hostname
* await context.addCookies([{
* name: 'next-instant-navigation-testing',
* value: '1',
* domain,
* path: '/',
* }])
* try { * try {
* return await fn() * return await fn()
* } finally { * } finally {
* await page.evaluate(() => window.__EXPERIMENTAL_NEXT_TESTING__.navigation.unlock()) * await context.clearCookies({
* name: 'next-instant-navigation-testing',
* })
* } * }
* } * }
* *
...@@ -20,6 +28,9 @@ ...@@ -20,6 +28,9 @@
* await expect(page.locator('[data-testid="loading"]')).toBeVisible() * 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: * When the lock is acquired:
* - Routes without a prefetch cache hit will wait for prefetch to complete * - Routes without a prefetch cache hit will wait for prefetch to complete
* before navigating. * before navigating.
...@@ -27,12 +38,12 @@ ...@@ -27,12 +38,12 @@
* into the UI. * into the UI.
* *
* For MPA navigations (page reload, full page load): * For MPA navigations (page reload, full page load):
* - A cookie is set that tells the server to render only the static shell. * - The cookie tells the server to render only the static shell.
* - When the lock is released, the cookie is cleared and a refresh is * - When the lock is released (cookie deleted), the page reloads to fetch
* triggered to fetch dynamic data. * dynamic data (handled in app-bootstrap.ts).
* *
* This allows tests to assert on the prefetched UI state before dynamic * This allows tests to assert on the prefetched UI state before dynamic
* content streams in. Network requests are not blocked - they proceed in * content streams in. Network requests are not blocked — they proceed in
* parallel while the lock is held. * parallel while the lock is held.
* *
* All functions in this module are wrapped in checks for the testing API, * All functions in this module are wrapped in checks for the testing API,
...@@ -49,83 +60,65 @@ type NavigationLockState = { ...@@ -49,83 +60,65 @@ type NavigationLockState = {
let lockState: NavigationLockState | null = null let lockState: NavigationLockState | null = null
// Tracks whether the page was loaded while the instant test cookie was set. function acquireLock(): void {
// When true, releasing the lock will trigger a refresh to fetch dynamic data. let resolve: () => void
let mpaLockedStateNeedsRefresh = false const promise = new Promise<void>((r) => {
resolve = r
})
lockState = { promise, resolve: resolve! }
}
/** /**
* Acquires the navigation lock. While locked, navigations will wait for * Starts listening for changes to the instant navigation test cookie via the
* prefetch tasks to complete before proceeding. * 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.
* Also sets a cookie so that MPA navigations (page reload, full page load)
* will render only the static shell.
* *
* Logs an error if the lock is already acquired (concurrent locks are not * This should be called once during page initialization.
* allowed).
*
* Not exposed in production builds by default.
*/ */
export function acquireNavigationLock(): void { export function startListeningForInstantNavigationCookie(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) { if (typeof cookieStore === 'undefined') {
console.error(
'Navigation lock already acquired. Concurrent locks are not allowed. ' +
'Did you forget to release the previous lock?'
)
return return
} }
cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
let resolve: () => void // Check if our cookie was added
const promise = new Promise<void>((r) => { for (const cookie of event.changed) {
resolve = r 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?'
)
return
}
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
}
return
}
}
}) })
lockState = { promise, resolve: resolve! }
// Set cookie for MPA navigations
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=1;path=/`
}
}
/**
* Releases the navigation lock. Any navigations that were waiting for
* prefetch completion will now proceed with dynamic data fetching.
*
* If the page was loaded while locked (MPA navigation), this also triggers
* a refresh to fetch the dynamic data that was blocked during the initial
* page load.
*
* No-op if the lock is not currently acquired.
*
* Not exposed in production builds by default.
*/
export function releaseNavigationLock(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (lockState !== null) {
lockState.resolve()
lockState = null
}
// Clear the cookie
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=;path=/;max-age=0`
// If the page was loaded with the cookie set (MPA navigation), trigger a
// refresh to fetch the dynamic data that was blocked during SSR.
if (mpaLockedStateNeedsRefresh) {
mpaLockedStateNeedsRefresh = false
triggerRefresh()
}
} }
} }
/** /**
* Returns true if the navigation lock is currently acquired. * Returns true if the navigation lock is currently active. Checks the cookie
* * rather than in-memory lockState because the cookie survives across MPA
* Not exposed in production builds by default. Always returns false when the * navigations (page reloads). Returns false when the testing API is disabled.
* testing API is not available.
*/ */
export function isNavigationLocked(): boolean { export function isNavigationLocked(): boolean {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
return lockState !== null return document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')
} }
return false return false
} }
...@@ -133,8 +126,6 @@ export function isNavigationLocked(): boolean { ...@@ -133,8 +126,6 @@ export function isNavigationLocked(): boolean {
/** /**
* Waits for the navigation lock to be released, if it's currently held. * Waits for the navigation lock to be released, if it's currently held.
* No-op if the lock is not acquired. * No-op if the lock is not acquired.
*
* Not exposed in production builds by default.
*/ */
export async function waitForNavigationLockIfActive(): Promise<void> { export async function waitForNavigationLockIfActive(): Promise<void> {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
...@@ -143,46 +134,3 @@ export async function waitForNavigationLockIfActive(): Promise<void> { ...@@ -143,46 +134,3 @@ export async function waitForNavigationLockIfActive(): Promise<void> {
} }
} }
} }
/**
* Called during page initialization when the instant test cookie is detected.
* Sets up the lock state so that:
* 1. Client-side navigations during the instant scope also block dynamic data
* 2. When the lock is released, a refresh is triggered to fetch dynamic data
*
* Not exposed in production builds by default.
*/
export function initializeMpaLockedState(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Set the MPA flag so we know to trigger a refresh when the lock is released
mpaLockedStateNeedsRefresh = true
// Also acquire the in-memory lock so client-side navigations during the
// instant scope also block dynamic data
if (lockState === null) {
let resolve: () => void
const promise = new Promise<void>((r) => {
resolve = r
})
lockState = { promise, resolve: resolve! }
}
}
}
/**
* Triggers a router refresh to fetch dynamic data. Used after releasing the
* navigation lock following an MPA navigation.
*/
function triggerRefresh(): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { dispatchAppRouterAction } =
require('../use-action-queue') as typeof import('../use-action-queue')
const { ACTION_REFRESH } =
require('../router-reducer/router-reducer-types') as typeof import('../router-reducer/router-reducer-types')
dispatchAppRouterAction({
type: ACTION_REFRESH,
devBypassCacheInvalidation: true,
})
}
}
...@@ -383,8 +383,8 @@ export interface ExperimentalConfig { ...@@ -383,8 +383,8 @@ export interface ExperimentalConfig {
externalMiddlewareRewritesResolve?: boolean externalMiddlewareRewritesResolve?: boolean
externalProxyRewritesResolve?: boolean externalProxyRewritesResolve?: boolean
/** /**
* Exposes the experimental testing API (`__EXPERIMENTAL_NEXT_TESTING__`) in * Exposes the Instant Navigation Testing API in production builds. This
* production builds. This API is always available in development mode. * API is always available in development mode.
* *
* The testing API allows e2e tests to control navigation timing, enabling * The testing API allows e2e tests to control navigation timing, enabling
* deterministic assertions on prefetched/cached UI before dynamic data * deterministic assertions on prefetched/cached UI before dynamic data
......
...@@ -82,6 +82,8 @@ interface Window { ...@@ -82,6 +82,8 @@ interface Window {
| 'top-right' | 'top-right'
| 'bottom-left' | 'bottom-left'
| 'bottom-right' | 'bottom-right'
/** @internal - Set by the server when serving a static shell for instant navigation tests */
__next_instant_test?: 1
} }
interface NextFetchRequestConfig { interface NextFetchRequestConfig {
......
...@@ -51,34 +51,37 @@ describe('instant-navigation-testing-api', () => { ...@@ -51,34 +51,37 @@ describe('instant-navigation-testing-api', () => {
return page! return page!
} }
const INSTANT_COOKIE = 'next-instant-navigation-testing'
/** /**
* Runs a function with instant navigation enabled. Within this scope, * Runs a function with instant navigation enabled. Within this scope,
* navigations render the prefetched UI immediately and wait for the * navigations render the prefetched UI immediately and wait for the
* callback to complete before streaming in dynamic data. * callback to complete before streaming in dynamic data.
* *
* This is the inline implementation of what will eventually be extracted * Uses the cookie-based protocol: setting the cookie acquires the
* to a Playwright helper package. * navigation lock (via CookieStore change event), and clearing it
* releases the lock.
*/ */
async function instant<T>( async function instant<T>(
page: Playwright.Page, page: Playwright.Page,
fn: () => Promise<T> fn: () => Promise<T>
): Promise<T> { ): Promise<T> {
await page.evaluate(() => // Acquire the lock by setting the cookie from within the page context.
(window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.lock() // This triggers the CookieStore change event in navigation-testing-lock.ts,
) // which acquires the in-memory navigation lock.
await page.evaluate((name) => {
document.cookie = name + '=1; path=/'
}, INSTANT_COOKIE)
try { try {
return await fn() return await fn()
} finally { } finally {
// Wait for the page to be ready before unlocking. This is only necessary // Release the lock by clearing the cookie. For SPA navigations, this
// when fn() triggers a full page navigation (e.g. page.reload() or // triggers the CookieStore change event which resolves the in-memory
// clicking a plain anchor), since the new page needs time to initialize. // lock. For MPA navigations (reload, plain anchor), the listener in
await page.waitForFunction( // app-bootstrap.ts triggers a page reload to fetch dynamic data.
() => await page.evaluate((name) => {
typeof (window as any).__EXPERIMENTAL_NEXT_TESTING__ !== 'undefined' document.cookie = name + '=; path=/; max-age=0'
) }, INSTANT_COOKIE)
await page.evaluate(() =>
(window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.unlock()
)
} }
} }
...@@ -167,19 +170,23 @@ describe('instant-navigation-testing-api', () => { ...@@ -167,19 +170,23 @@ describe('instant-navigation-testing-api', () => {
it('logs an error when attempting to nest instant scopes', async () => { it('logs an error when attempting to nest instant scopes', async () => {
const page = await openPage('/') const page = await openPage('/')
const errors: string[] = [] // Listen for the specific error message
page.on('console', (msg) => { const consolePromise = page.waitForEvent('console', {
if (msg.type() === 'error') { predicate: (msg) =>
errors.push(msg.text()) msg.type() === 'error' && msg.text().includes('already acquired'),
} timeout: 5000,
}) })
await instant(page, async () => { await instant(page, async () => {
// Attempt to nest another instant scope - should log an error // Attempt to acquire the lock again by changing the cookie value.
await instant(page, async () => {}) // The CookieStore change event fires, and the handler detects that
// the lock is already held, logging an error.
await page.evaluate((name) => {
document.cookie = name + '=nested; path=/'
}, INSTANT_COOKIE)
const msg = await consolePromise
expect(msg.text()).toContain('already acquired')
}) })
expect(errors.some((e) => e.includes('already acquired'))).toBe(true)
}) })
it('renders static shell on page reload', async () => { it('renders static shell on page reload', 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