Unverified Commit 3279f016 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] Fix dev mode hydration failure when page is served from HTTP cache (#93492)

Backports:

- #92892
- #93486
parent ffc4f296
...@@ -8,16 +8,118 @@ export interface DebugChannelReadableWriterPair { ...@@ -8,16 +8,118 @@ export interface DebugChannelReadableWriterPair {
const pairs = new Map<string, DebugChannelReadableWriterPair>() const pairs = new Map<string, DebugChannelReadableWriterPair>()
const DEBUG_CHANNEL_STORAGE_KEY_PREFIX = '__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 {
const key = DEBUG_CHANNEL_STORAGE_KEY_PREFIX + requestId
const value = JSON.stringify(
initialDocumentDebugChunks.map((chunk) => {
let binary = ''
for (let i = 0; i < chunk.byteLength; i++) {
binary += String.fromCharCode(chunk[i])
}
return btoa(binary)
})
)
try {
sessionStorage.setItem(key, value)
} catch {
// Likely a quota error. Drop entries from previous documents in this tab
// (we only need to restore the current one's entry on cache restore) and
// retry once. If it still fails, skip silently — the location.reload()
// fallback in createDebugChannel handles this case.
for (let i = sessionStorage.length - 1; i >= 0; i--) {
const k = sessionStorage.key(i)
if (k?.startsWith(DEBUG_CHANNEL_STORAGE_KEY_PREFIX) && k !== key) {
sessionStorage.removeItem(k)
}
}
try {
sessionStorage.setItem(key, value)
} catch {}
}
}
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_PREFIX + requestId
)
if (!serializedData) {
return undefined
}
const chunks = (JSON.parse(serializedData) as string[]).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( export function getOrCreateDebugChannelReadableWriterPair(
requestId: string requestId: string
): DebugChannelReadableWriterPair { ): DebugChannelReadableWriterPair {
let pair = pairs.get(requestId) let pair = pairs.get(requestId)
if (!pair) { 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() } pair = { readable, writer: writable.getWriter() }
pairs.set(requestId, pair) 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 return pair
...@@ -49,6 +151,24 @@ export function createDebugChannel( ...@@ -49,6 +151,24 @@ 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) {
return { readable }
}
// Debug channel can't be restored — debug deps would block hydration.
// Force a fresh page load from the server. Return a never-closing stream
// so the Flight client stays parked until the reload tears the document
// down, instead of synchronously erroring with "Connection closed.".
location.reload()
return { readable: new ReadableStream() }
}
const { readable } = getOrCreateDebugChannelReadableWriterPair(requestId) const { readable } = getOrCreateDebugChannelReadableWriterPair(requestId)
return { readable } 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="/target-page">MPA Link</a>
</p>
</div>
)
}
export default function Page() {
return <h2>Target Page</h2>
}
import { nextTestSetup } from 'e2e-utils'
import { assertNoConsoleErrors, retry } from 'next-test-utils'
describe('bfcache-regression', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
it('should preserve interactivity after navigating back from another page via MPA navigation', async () => {
// In webpack dev, compiling a new route on demand while another page is
// open triggers an HMR cycle that has no Fast Refresh boundary, surfacing
// a "performing full reload" warning on the open page. Warm up the target
// page in parallel with the browser load so it's already compiled by the
// time we click the link.
const [browser] = await Promise.all([
next.browser('/', { pushErrorAsConsoleLog: true }),
!isTurbopack ? next.render('/target-page').catch(() => {}) : null,
])
// 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 another page by clicking the link (full page
// navigation, not a client-side navigation).
await browser.elementByCss('a[href="/target-page"]').click()
expect(await (await browser.elementByCss('h2')).text()).toBe('Target Page')
// 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')
})
await assertNoConsoleErrors(browser)
})
})
/**
* @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