Unverified Commit 67f4f5ed authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix dev mode hydration failure when page is served from HTTP cache (#92892)

PR #88182 introduced an experimental option to use `Cache-Control:
no-cache` instead of `no-store` in dev mode, and PR #91503 made it the
default. With `no-cache`, browsers may serve the page from HTTP cache on
back-forward navigation or tab duplication. The HTML, including the
inline RSC payload, is restored from cache and all scripts re-execute.

In dev mode, React's Flight client uses a debug channel (a
WebSocket-backed stream delivering component debug info) that adds
dependencies to model chunk initialization. On a fresh page load, the
WebSocket delivers this data and the dependencies resolve normally. On
HTTP cache restore, however, the bootstrap script re-executes and
creates a new debug channel stream, but the WebSocket doesn't re-send
debug data for the cached payload's request ID. The debug dependencies
are never fulfilled, blocking the entire model tree from initializing,
so `hydrateRoot` is never called and the page loses all interactivity.

This is dev-only — production builds have no debug channel, so there are
no stuck dependencies and no issue.

The fix buffers debug channel chunks in memory as they flow through the
`TransformStream` in `getOrCreateDebugChannelReadableWriterPair`. Once
all chunks have been received, the buffer is eagerly persisted to
`sessionStorage`. When the page detects it was served from HTTP cache
(via `PerformanceNavigationTiming.transferSize === 0`),
`createDebugChannel` restores the debug data from `sessionStorage` and
replays it as a synthetic `ReadableStream` instead of expecting it from
the WebSocket. If the restore fails (e.g., quota exceeded during the
earlier write, or the entry was overwritten by another page), the page
falls back to `location.reload()` to get a fresh page from the server.

A regression test is included that navigates to an external page and
verifies interactivity is preserved after clicking the browser back
button. Tab duplication (which triggers the same HTTP cache restore)
cannot be simulated in Playwright and was verified manually.

fixes #92238
fixes #91982
fixes #92687
parent 4dd1fcb1
......@@ -8,16 +8,114 @@ export interface DebugChannelReadableWriterPair {
const pairs = new Map<string, DebugChannelReadableWriterPair>()
const DEBUG_CHANNEL_STORAGE_KEY = '__next_debug_channel'
// Buffer for the initial document's debug channel data. Written to
// sessionStorage once complete so it can be restored when the browser serves
// the page from HTTP cache (back-forward navigation, tab duplication, etc.).
let initialDocumentDebugChunks: Uint8Array[] = []
function persistDebugChannelToSessionStorage(requestId: string): void {
try {
const chunks = initialDocumentDebugChunks.map((chunk) => {
let binary = ''
for (let i = 0; i < chunk.byteLength; i++) {
binary += String.fromCharCode(chunk[i])
}
return btoa(binary)
})
sessionStorage.setItem(
DEBUG_CHANNEL_STORAGE_KEY,
JSON.stringify({ requestId, chunks })
)
} catch {
// Quota exceeded or other error — skip silently. The location.reload()
// fallback in createDebugChannel handles this case.
}
}
function wasServedFromCache(): boolean {
try {
// There is exactly one PerformanceNavigationTiming entry per page load.
const entry = performance.getEntriesByType('navigation')[0]
return entry?.transferSize === 0
} catch {
return false
}
}
function restoreDebugChannelFromSessionStorage(
requestId: string
): ReadableStream<Uint8Array> | undefined {
try {
const serializedData = sessionStorage.getItem(DEBUG_CHANNEL_STORAGE_KEY)
if (!serializedData) {
return undefined
}
const parsedData = JSON.parse(serializedData) as {
requestId: string
chunks: string[]
}
if (parsedData.requestId !== requestId) {
return undefined
}
const chunks = parsedData.chunks.map((base64) => {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
})
return new ReadableStream<Uint8Array>({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(chunk)
}
controller.close()
},
})
} catch {
return undefined
}
}
export function getOrCreateDebugChannelReadableWriterPair(
requestId: string
): DebugChannelReadableWriterPair {
let pair = pairs.get(requestId)
if (!pair) {
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()
// Only buffer chunks for the initial document's debug channel, not for
// client-side navigation requests.
const shouldBuffer = requestId === self.__next_r
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
if (shouldBuffer) {
initialDocumentDebugChunks.push(chunk.slice())
}
controller.enqueue(chunk)
},
})
pair = { readable, writer: writable.getWriter() }
pairs.set(requestId, pair)
pair.writer.closed.finally(() => pairs.delete(requestId))
pair.writer.closed
.then(() => {
if (shouldBuffer) {
persistDebugChannelToSessionStorage(requestId)
}
})
.finally(() => pairs.delete(requestId))
}
return pair
......@@ -49,6 +147,21 @@ export function createDebugChannel(
}
}
// Only attempt to restore the sessionStorage debug channel entry for the
// initial document load (no request headers). Client-side navigations pass
// request headers and should always use the WebSocket-backed debug channel.
if (!requestHeaders && wasServedFromCache()) {
const readable = restoreDebugChannelFromSessionStorage(requestId)
if (!readable) {
// Debug channel can't be restored — debug deps would block hydration.
// Force a fresh page load from the server.
location.reload()
}
return { readable }
}
const { readable } = getOrCreateDebugChannelReadableWriterPair(requestId)
return { readable }
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useState } from 'react'
export default function Page() {
const [count, setCount] = useState(0)
return (
<div>
<p id="count">Count: {count}</p>
<button id="increment" onClick={() => setCount((c) => c + 1)}>
Increment
</button>
<p>
<a href="https://example.com">External Link</a>
</p>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('bfcache-regression', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should preserve interactivity after navigating back from an external page', async () => {
const browser = await next.browser('/')
// Verify initial state and that the counter is interactive.
await browser.elementById('increment').click()
await retry(async () => {
expect(await browser.elementById('count').text()).toBe('Count: 1')
})
// Navigate away to an external page by clicking the link (full page
// navigation, not a client-side navigation).
await browser.elementByCss('a[href="https://example.com"]').click()
await retry(async () => {
expect(await browser.url()).toContain('example.com')
})
// Navigate back (simulates clicking the browser back button).
await browser.back()
// After navigating back, the page should be interactive.
await retry(async () => {
expect(await browser.elementById('count').text()).toBe('Count: 0')
})
await browser.elementById('increment').click()
await retry(async () => {
expect(await browser.elementById('count').text()).toBe('Count: 1')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
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