Abort superseded Server Component HMR requests on the client

In `next dev`, rapid edits can start overlapping Server Component HMR
refreshes, but only the newest can commit. With this change, when a
newer HMR refresh supersedes an older one, we abort the older request on
the client so it stops transferring and decoding RSC data. This is the
client half of the feature; later changes also cancel the superseded
request's server-side work. Everything here is gated on the
`serverComponentsHmrCancellation` flag.

The router's `hmrRefresh` method now tracks the newest refresh
generation in an `AbortController` and aborts the previous one before
scheduling the new one, so the superseded request tears down as early as
possible, threading the abort signal through the HMR action,
`refreshDynamicData`, `navigateToKnownRoute`, `spawnDynamicRequests`,
and `fetchMissingDynamicData` down to the `fetch` call. An aborted
request becomes a new `NavigationTaskExitStatus.Canceled` rather than a
failure, so `finishNavigationTask` leaves its cache nodes for the newer
navigation to fulfill and does not retry or fall back to an MPA
navigation. `hmrRefreshReducer` also bails out when its generation was
already aborted before it ran, which happens when an HMR action waits
behind a Server Action in the router queue.

The subtle part is how an aborted request's partially received response
is handled. A superseded refresh can already have committed part of its
tree with a Suspense boundary still streaming. If we simply aborted the
fetch, React's Flight client would reject the still-pending rows, and a
committed boundary reading such a row would throw into an error
boundary. Instead, for a cancellable refresh we decode the response
through a wrapper stream that we close, rather than letting the aborted
fetch error it, so React marks the unresolved rows as halted: they
suspend during render instead of rejecting, and the superseded boundary
keeps showing its fallback until the newer response commits. Closing the
stream also avoids the unclosed-stream memory leak that browsers retain
as a GC root, the same leak #89610 fixed for prefetch streams by closing
them with `allowPartialStream` rather than leaving them open. The
wrapper is created synchronously so the decode still starts where
`createFromFetch` would, preserving the server-latency debug timing.

A development test suite covers three cases: a superseded request is
aborted while the newest commits without a hard reload, a partially
committed render whose Suspense boundary is left streaming does not
surface an error when superseded, and disabling the flag preserves the
previous behavior where the superseded request runs to completion.
parent e5cc93e7
...@@ -380,6 +380,10 @@ function gesturePush(href: string, options?: NavigateOptions): void { ...@@ -380,6 +380,10 @@ function gesturePush(href: string, options?: NavigateOptions): void {
} }
} }
// Tracks the newest HMR refresh generation so that a newer refresh can abort
// the request of the one it supersedes. Development only.
let activeHmrRefreshController: AbortController | null = null
/** /**
* The app router that is exposed through `useRouter`. These are public API * The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly * methods. Internal Next.js code should call the lower level methods directly
...@@ -486,9 +490,19 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -486,9 +490,19 @@ export const publicAppRouterInstance: AppRouterInstance = {
// Reset the known routes table so that route predictions are cleared // Reset the known routes table so that route predictions are cleared
// when routes change during development. // when routes change during development.
resetKnownRoutes() resetKnownRoutes()
let signal: AbortSignal | undefined
if (process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION) {
// Abort the superseded generation before scheduling the new one, so its
// request is torn down as early as possible. Halting (not rejecting)
// makes the abort safe regardless of order.
activeHmrRefreshController?.abort()
activeHmrRefreshController = new AbortController()
signal = activeHmrRefreshController.signal
}
startTransition(() => { startTransition(() => {
dispatchAppRouterAction({ dispatchAppRouterAction({
type: ACTION_HMR_REFRESH, type: ACTION_HMR_REFRESH,
signal,
}) })
}) })
} }
......
...@@ -66,6 +66,7 @@ export interface FetchServerResponseOptions { ...@@ -66,6 +66,7 @@ export interface FetchServerResponseOptions {
readonly flightRouterState: FlightRouterState readonly flightRouterState: FlightRouterState
readonly nextUrl: string | null readonly nextUrl: string | null
readonly isHmrRefresh?: boolean readonly isHmrRefresh?: boolean
readonly signal?: AbortSignal
} }
export type StaticStageData< export type StaticStageData<
...@@ -198,7 +199,8 @@ export async function fetchServerResponse( ...@@ -198,7 +199,8 @@ export async function fetchServerResponse(
url, url,
headers, headers,
'auto', 'auto',
shouldImmediatelyDecode shouldImmediatelyDecode,
options.signal
) )
// If the fetch succeeds while we're in the offline state, notify the // If the fetch succeeds while we're in the offline state, notify the
...@@ -313,6 +315,13 @@ export async function fetchServerResponse( ...@@ -313,6 +315,13 @@ export async function fetchServerResponse(
revealAfter: flightResponse._revealAfter ?? null, revealAfter: flightResponse._revealAfter ?? null,
} }
} catch (err) { } catch (err) {
if (options.signal?.aborted) {
// A newer HMR refresh superseded this one and aborted its request.
// Rethrow so the caller treats it as canceled, rather than logging a
// failure or falling back to an MPA navigation.
throw err
}
// If the fetch rejected due to a network error, wait for connectivity // If the fetch rejected due to a network error, wait for connectivity
// to be restored and then retry. checkOfflineError returns true for // to be restored and then retry. checkOfflineError returns true for
// network errors (and starts the polling loop); returns false for // network errors (and starts the polling loop); returns false for
...@@ -549,6 +558,123 @@ export async function decodeStageUntilBoundary<T>( ...@@ -549,6 +558,123 @@ export async function decodeStageUntilBoundary<T>(
}) })
} }
// When an HMR refresh can be superseded, we decode its Flight response through
// a wrapper stream we can close on abort. Closing the stream (rather than
// letting the aborted fetch error it) makes React's Flight client mark
// unresolved rows as halted: they suspend during render instead of rejecting,
// so a superseded request never surfaces an error on an already-committed tree.
// Because the stream is closed, there's also no unclosed-stream GC-root leak
// (see #89610). The wrapper is created synchronously here so that the decode
// starts at the same point `createFromNextFetch` would, preserving the
// server-latency debug timing.
function createHaltingFlightResponse<T>(
fetchPromise: Promise<Response>,
headers: RequestHeaders,
signal: AbortSignal
): Promise<T> & { _debugInfo?: Array<any> } {
let closed = false
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null
const wrapper = new ReadableStream<Uint8Array>({
start(controller) {
const onAbort = () => {
closed = true
try {
controller.close()
} catch {
// The controller may already be closed; nothing to do.
}
if (reader !== null) {
reader.cancel().catch(() => {})
}
}
if (signal.aborted) {
onAbort()
} else {
signal.addEventListener('abort', onAbort, { once: true })
}
},
async pull(controller) {
if (closed) {
return
}
if (reader === null) {
let response: Response
try {
response = await fetchPromise
} catch (err) {
// We don't inspect `err`. If the request was superseded, `onAbort`
// already ran synchronously (abort listeners fire during
// `signal.abort()`, before this rejection microtask), so `closed` is
// true and the controller is already closed — erroring it would
// throw, and a superseded request's failure is moot regardless of its
// cause. Only a genuine, non-superseded failure reaches here with
// `closed` still false; that is the case we surface.
if (!closed) {
controller.error(err)
}
return
}
if (closed) {
// Aborted while awaiting the response. The `fetch` abort tears down
// an in-flight request, but if it had already completed we still hold
// an unread body; release it so it isn't left dangling.
response.body?.cancel().catch(() => {})
return
}
const body = response.body
if (body === null) {
controller.close()
return
}
reader = body.getReader()
}
try {
const { done, value } = await reader.read()
if (closed) {
return
}
if (done) {
controller.close()
} else {
controller.enqueue(value)
}
} catch (err) {
// Same as the fetch catch above: once superseded (`closed`) the
// controller is already closed and the outcome is moot, so we swallow
// the rejection unconditionally; only a real, non-superseded read
// failure (`closed` still false) is surfaced.
if (!closed) {
controller.error(err)
}
}
},
})
// React attaches `_debugInfo` to the returned promise at runtime.
return createFromNextReadableStream<T>(wrapper, headers, {
allowPartialStream: true,
}) as Promise<T> & { _debugInfo?: Array<any> }
}
// Selects the Flight decode strategy: a halting wrapper for cancellable HMR
// refreshes, otherwise the standard fetch-based decode. Gated to the dev server
// (where HMR runs) so the wrapper is eliminated from production and
// `--debug-prerender` bundles regardless of the flag.
function decodeFlightResponse<T>(
fetchPromise: Promise<Response>,
headers: RequestHeaders,
signal: AbortSignal | undefined
): Promise<T> & { _debugInfo?: Array<any> } {
if (
process.env.__NEXT_DEV_SERVER &&
process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&
signal
) {
return createHaltingFlightResponse<T>(fetchPromise, headers, signal)
}
return createFromNextFetch<T>(fetchPromise, headers)
}
export async function createFetch<T>( export async function createFetch<T>(
url: URL, url: URL,
headers: RequestHeaders, headers: RequestHeaders,
...@@ -606,7 +732,7 @@ export async function createFetch<T>( ...@@ -606,7 +732,7 @@ export async function createFetch<T>(
// been written into the cache by the time the navigation happens, the router // been written into the cache by the time the navigation happens, the router
// will go straight to a dynamic request. // will go straight to a dynamic request.
let flightResponsePromise = shouldImmediatelyDecode let flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers) ? decodeFlightResponse<T>(fetchPromise, headers, signal)
: null : null
let browserResponse = await fetchPromise let browserResponse = await fetchPromise
...@@ -667,7 +793,7 @@ export async function createFetch<T>( ...@@ -667,7 +793,7 @@ export async function createFetch<T>(
processed = fetch(fetchUrl, fetchOptions).then(processFetch) processed = fetch(fetchUrl, fetchOptions).then(processFetch)
fetchPromise = processed.then(({ response }) => response) fetchPromise = processed.then(({ response }) => response)
flightResponsePromise = shouldImmediatelyDecode flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers) ? decodeFlightResponse<T>(fetchPromise, headers, signal)
: null : null
browserResponse = await fetchPromise browserResponse = await fetchPromise
// We just performed a manual redirect, so this is now true. // We just performed a manual redirect, so this is now true.
......
...@@ -103,6 +103,11 @@ const enum NavigationTaskStatus { ...@@ -103,6 +103,11 @@ const enum NavigationTaskStatus {
* necessitating a retry. * necessitating a retry.
*/ */
const enum NavigationTaskExitStatus { const enum NavigationTaskExitStatus {
/**
* The request was superseded by a newer navigation and aborted. No retry is
* needed; the newer request owns the tree from here.
*/
Canceled = -1,
/** /**
* No additional navigation is required. * No additional navigation is required.
*/ */
...@@ -1411,7 +1416,8 @@ export function spawnDynamicRequests( ...@@ -1411,7 +1416,8 @@ export function spawnDynamicRequests(
// server-patch retry logic so it can inherit the intent if the original // server-patch retry logic so it can inherit the intent if the original
// transition hasn't committed yet. // transition hasn't committed yet.
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
navigationLock: NavigationLock navigationLock: NavigationLock,
signal: AbortSignal | undefined
): void { ): void {
const dynamicRequestTree = task.dynamicRequestTree const dynamicRequestTree = task.dynamicRequestTree
if (dynamicRequestTree === null) { if (dynamicRequestTree === null) {
...@@ -1436,7 +1442,8 @@ export function spawnDynamicRequests( ...@@ -1436,7 +1442,8 @@ export function spawnDynamicRequests(
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
routeCacheEntry, routeCacheEntry,
navigationLock navigationLock,
signal
) )
const separateRefreshUrls = accumulation.separateRefreshUrls const separateRefreshUrls = accumulation.separateRefreshUrls
...@@ -1489,7 +1496,8 @@ export function spawnDynamicRequests( ...@@ -1489,7 +1496,8 @@ export function spawnDynamicRequests(
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
routeCacheEntry, routeCacheEntry,
navigationLock navigationLock,
signal
) )
) )
} }
...@@ -1538,6 +1546,14 @@ async function finishNavigationTask( ...@@ -1538,6 +1546,14 @@ async function finishNavigationTask(
} }
switch (exitStatus) { switch (exitStatus) {
case NavigationTaskExitStatus.Canceled: {
// This navigation was superseded and its request aborted. Its cache nodes
// may already be reused by the newer navigation, so leave them untouched
// for the newer request to fulfill. If the tree was abandoned entirely,
// it can be garbage collected along with its unresolved promises. We do
// not retry or hard-navigate.
return
}
case NavigationTaskExitStatus.Done: { case NavigationTaskExitStatus.Done: {
// The task has completely finished. There's no missing data. Exit. // The task has completely finished. There's no missing data. Exit.
previousNavigationDidMismatch = false previousNavigationDidMismatch = false
...@@ -1758,7 +1774,8 @@ async function fetchMissingDynamicData( ...@@ -1758,7 +1774,8 @@ async function fetchMissingDynamicData(
nextUrl: string | null, nextUrl: string | null,
freshnessPolicy: FreshnessPolicy, freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null, routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock navigationLock: NavigationLock,
signal: AbortSignal | undefined
): Promise<{ ): Promise<{
exitStatus: NavigationTaskExitStatus exitStatus: NavigationTaskExitStatus
url: URL url: URL
...@@ -1769,6 +1786,7 @@ async function fetchMissingDynamicData( ...@@ -1769,6 +1786,7 @@ async function fetchMissingDynamicData(
flightRouterState: dynamicRequestTree, flightRouterState: dynamicRequestTree,
nextUrl, nextUrl,
isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh, isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh,
signal,
}) })
if (typeof result === 'string') { if (typeof result === 'string') {
// fetchServerResponse will return an href to indicate that the SPA // fetchServerResponse will return an href to indicate that the SPA
...@@ -1913,6 +1931,17 @@ async function fetchMissingDynamicData( ...@@ -1913,6 +1931,17 @@ async function fetchMissingDynamicData(
seed, seed,
} }
} catch { } catch {
if (signal?.aborted) {
// A newer HMR refresh superseded this one and aborted its request. Treat
// it as canceled rather than a failure, so we don't retry or
// hard-navigate.
return {
exitStatus: NavigationTaskExitStatus.Canceled,
url,
seed: null,
}
}
// This shouldn't happen because fetchServerResponse's entire body is // This shouldn't happen because fetchServerResponse's entire body is
// wrapped in a try/catch. If it does, though, it implies the server failed // wrapped in a try/catch. If it does, though, it implies the server failed
// to respond with any tree at all. So we must fall back to a hard retry. // to respond with any tree at all. So we must fall back to a hard retry.
......
import type { import type {
HmrRefreshAction,
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { refreshDynamicData } from './refresh-reducer' import { refreshDynamicData } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
export function hmrRefreshReducer(state: ReadonlyReducerState): ReducerState { export function hmrRefreshReducer(
return refreshDynamicData(state, FreshnessPolicy.HMRRefresh) state: ReadonlyReducerState,
action: HmrRefreshAction
): ReducerState {
// HMR actions may wait behind a Server Action in the router queue. If a newer
// generation superseded this one before it started, don't install a refresh
// tree whose request is already canceled.
if (action.signal?.aborted) {
return state
}
return refreshDynamicData(state, FreshnessPolicy.HMRRefresh, action.signal)
} }
...@@ -35,12 +35,14 @@ export function refreshReducer( ...@@ -35,12 +35,14 @@ export function refreshReducer(
const currentRouterState = state.tree const currentRouterState = state.tree
invalidateSegmentCacheEntries(currentNextUrl, currentRouterState) invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)
} }
return refreshDynamicData(state, FreshnessPolicy.RefreshAll) // A full refresh has no HMR generation to cancel.
return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)
} }
export function refreshDynamicData( export function refreshDynamicData(
state: ReadonlyReducerState, state: ReadonlyReducerState,
freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh,
signal: AbortSignal | undefined
): ReducerState { ): ReducerState {
// During a refresh, invalidate the BFCache, which may contain dynamic data. // During a refresh, invalidate the BFCache, which may contain dynamic data.
invalidateBfCache() invalidateBfCache()
...@@ -103,6 +105,7 @@ export function refreshDynamicData( ...@@ -103,6 +105,7 @@ export function refreshDynamicData(
// cache entry to mark as having a dynamic rewrite on mismatch. If a // cache entry to mark as having a dynamic rewrite on mismatch. If a
// mismatch occurs, the retry handler will traverse the known route tree // mismatch occurs, the retry handler will traverse the known route tree
// to find and mark the entry. // to find and mark the entry.
null null,
signal
) )
} }
...@@ -94,7 +94,9 @@ export function restoreReducer( ...@@ -94,7 +94,9 @@ export function restoreReducer(
null, null,
// History traversal always uses 'replace'. // History traversal always uses 'replace'.
'replace', 'replace',
navigationLock navigationLock,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
) )
return completeTraverseNavigation( return completeTraverseNavigation(
state, state,
......
...@@ -518,7 +518,9 @@ export function serverActionReducer( ...@@ -518,7 +518,9 @@ export function serverActionReducer(
// have the route tree from the server response. If a mismatch occurs // have the route tree from the server response. If a mismatch occurs
// during dynamic data fetch, the retry handler will traverse the // during dynamic data fetch, the retry handler will traverse the
// known route tree to mark the entry as having a dynamic rewrite. // known route tree to mark the entry as having a dynamic rewrite.
null null,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
) )
} }
......
...@@ -69,6 +69,8 @@ export function serverPatchReducer( ...@@ -69,6 +69,8 @@ export function serverPatchReducer(
// Server patch (retry) navigations don't use route prediction. This is // Server patch (retry) navigations don't use route prediction. This is
// typically a retry after a previous mismatch, so the route was already // typically a retry after a previous mismatch, so the route was already
// marked as having a dynamic rewrite when the mismatch was detected. // marked as having a dynamic rewrite when the mismatch was detected.
null null,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
) )
} }
...@@ -38,6 +38,7 @@ export interface RefreshAction { ...@@ -38,6 +38,7 @@ export interface RefreshAction {
export interface HmrRefreshAction { export interface HmrRefreshAction {
type: typeof ACTION_HMR_REFRESH type: typeof ACTION_HMR_REFRESH
signal?: AbortSignal
} }
export type ServerActionDispatcher = ( export type ServerActionDispatcher = (
......
...@@ -41,7 +41,7 @@ function clientReducer( ...@@ -41,7 +41,7 @@ function clientReducer(
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const { hmrRefreshReducer } = const { hmrRefreshReducer } =
require('./reducers/hmr-refresh-reducer') as typeof import('./reducers/hmr-refresh-reducer') require('./reducers/hmr-refresh-reducer') as typeof import('./reducers/hmr-refresh-reducer')
return hmrRefreshReducer(state) return hmrRefreshReducer(state, action)
} else { } else {
throw new Error( throw new Error(
'hmrRefresh can only be used in development mode. Please use refresh instead.' 'hmrRefresh can only be used in development mode. Please use refresh instead.'
......
...@@ -239,7 +239,8 @@ export function navigateToKnownRoute( ...@@ -239,7 +239,8 @@ export function navigateToKnownRoute(
// In these cases, if a mismatch occurs, we still mark the route as having a // In these cases, if a mismatch occurs, we still mark the route as having a
// dynamic rewrite by traversing the known route tree (see // dynamic rewrite by traversing the known route tree (see
// dispatchRetryDueToTreeMismatch). // dispatchRetryDueToTreeMismatch).
routeCacheEntry: FulfilledRouteCacheEntry | null routeCacheEntry: FulfilledRouteCacheEntry | null,
signal: AbortSignal | undefined
): AppRouterState { ): AppRouterState {
// A version of navigate() that accepts the target route tree as an argument // A version of navigate() that accepts the target route tree as an argument
// rather than reading it from the prefetch cache. // rather than reading it from the prefetch cache.
...@@ -352,7 +353,8 @@ export function navigateToKnownRoute( ...@@ -352,7 +353,8 @@ export function navigateToKnownRoute(
accumulation, accumulation,
routeCacheEntry, routeCacheEntry,
navigateType, navigateType,
navigationLock navigationLock,
signal
) )
} }
return completeSoftNavigation( return completeSoftNavigation(
...@@ -415,7 +417,9 @@ function navigateUsingPrefetchedRouteTree( ...@@ -415,7 +417,9 @@ function navigateUsingPrefetchedRouteTree(
navigateType, navigateType,
navigationLock, navigationLock,
null, null,
route route,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
) )
} }
...@@ -631,7 +635,9 @@ async function navigateToUnknownRoute( ...@@ -631,7 +635,9 @@ async function navigateToUnknownRoute(
// came directly from the server. If a mismatch occurs during dynamic data // came directly from the server. If a mismatch occurs during dynamic data
// fetch, the retry handler will traverse the known route tree to mark the // fetch, the retry handler will traverse the known route tree to mark the
// entry as having a dynamic rewrite. // entry as having a dynamic rewrite.
null null,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
) )
} }
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
// Editing any of these constants triggers a Server Component HMR refresh.
// `boundaryKey` is the Suspense boundary's key: changing it remounts the
// boundary, so the remounted boundary has no prior content and commits its
// fallback while `DynamicContent` streams — a partially committed tree.
const boundaryKey = 'initial'
const dynamicMarker = 'initial'
const dynamicDelayMs = 0
async function DynamicContent() {
await connection()
await new Promise((resolve) => setTimeout(resolve, dynamicDelayMs))
return <p id="dynamic">{dynamicMarker}</p>
}
export default function Page() {
return (
<main>
<p id="shell">shell</p>
<Suspense key={boundaryKey} fallback={<p id="dynamic">loading</p>}>
<DynamicContent />
</Suspense>
</main>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type { Playwright } from 'next-webdriver'
describe('hmr-rsc-cancellation', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let pristinePage: string
let pristineConfig: string
beforeAll(async () => {
pristinePage = await next.readFile('app/page.tsx')
pristineConfig = await next.readFile('next.config.js')
})
afterEach(async () => {
await next.stop()
// Restore the fixture so each test starts from the same baseline.
await next.patchFile('app/page.tsx', pristinePage)
await next.patchFile('next.config.js', pristineConfig)
})
// Records each HMR RSC request's aborted/settled state, and a sentinel that
// is cleared if the page hard-reloads (so we can assert cancellation never
// triggers a reload).
async function instrumentBrowser(browser: Playwright) {
await browser.eval(() => {
const requests: Array<{ aborted: boolean; settled: boolean }> = []
;(window as any).__hmrRequests = requests
;(window as any).__reloadSentinel = true
const originalFetch = window.fetch
window.fetch = (input: any, init: any) => {
const headers = new Headers(init?.headers)
if (headers.get('next-hmr-refresh') === '1') {
const record = {
aborted: init?.signal?.aborted ?? false,
settled: false,
}
requests.push(record)
init?.signal?.addEventListener(
'abort',
() => {
record.aborted = true
},
{ once: true }
)
const result = originalFetch(input, init)
result.then(
() => {
record.settled = true
},
() => {
record.settled = true
}
)
return result
}
return originalFetch(input, init)
}
})
}
function readResult(browser: Playwright) {
return browser.eval(() => ({
requests: (window as any).__hmrRequests as Array<{
aborted: boolean
settled: boolean
}>,
reloaded: (window as any).__reloadSentinel !== true,
}))
}
function expectCleanCliOutput(output: string) {
expect(output).not.toContain('Failed to fetch RSC payload')
expect(output).not.toContain('Cannot write to a closing writable stream')
expect(output).not.toContain('unhandledRejection')
}
it('cancels a superseded Server Component HMR request', async () => {
await next.start()
const browser = await next.browser('/')
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('initial')
})
await instrumentBrowser(browser)
const cliStart = next.cliOutput.length
// Request A: a slow refresh whose dynamic content keeps streaming.
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'slow'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 5000')
)
await retry(async () => {
expect(
await browser.eval(() => (window as any).__hmrRequests.length)
).toBe(1)
})
// Request B supersedes A, aborting it.
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'latest'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 0')
)
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('latest')
})
await retry(async () => {
const { requests, reloaded } = await readResult(browser)
expect(reloaded).toBe(false)
// Two refreshes: the superseded one was aborted, the newest committed.
expect(requests).toMatchObject([
{ aborted: true, settled: true },
{ aborted: false, settled: true },
])
})
expectCleanCliOutput(next.cliOutput.slice(cliStart))
})
it('does not surface an error when a partially committed render is superseded', async () => {
await next.start()
const browser = await next.browser('/')
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('initial')
})
await instrumentBrowser(browser)
const cliStart = next.cliOutput.length
// Request A: remount the Suspense boundary (new key) with a slow dynamic.
// The remounted boundary has no prior content, so React commits it showing
// its fallback while the dynamic row streams — the tree is partially
// committed and on screen.
await next.patchFile('app/page.tsx', (src) =>
src
.replace(/const boundaryKey = '[^']*'/, "const boundaryKey = 'a'")
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'slow'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 5000')
)
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('loading')
})
// Request B supersedes A, keeping the same boundary key so B reuses the
// committed boundary that is showing A's fallback. A's aborted dynamic row
// must halt (suspend) rather than reject into that mounted boundary.
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'latest'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 0')
)
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('latest')
})
await retry(async () => {
const { requests, reloaded } = await readResult(browser)
expect(reloaded).toBe(false)
// Two refreshes: the superseded one was aborted, the newest committed.
expect(requests).toMatchObject([
{ aborted: true, settled: true },
{ aborted: false, settled: true },
])
})
expectCleanCliOutput(next.cliOutput.slice(cliStart))
})
it('preserves existing behavior when cancellation is disabled', async () => {
await next.patchFile('next.config.js', (src) =>
src.replace(
'serverComponentsHmrCancellation: true',
'serverComponentsHmrCancellation: false'
)
)
await next.start()
const browser = await next.browser('/')
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('initial')
})
await instrumentBrowser(browser)
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'slow'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 1000')
)
await retry(async () => {
expect(
await browser.eval(() => (window as any).__hmrRequests.length)
).toBe(1)
})
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'latest'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 0')
)
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('latest')
})
// With cancellation disabled, neither refresh is aborted; both run to
// completion like before.
await retry(async () => {
const { requests } = await readResult(browser)
expect(requests).toMatchObject([
{ aborted: false, settled: true },
{ aborted: false, settled: true },
])
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
serverComponentsHmrCancellation: true,
},
}
module.exports = nextConfig
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