Backtestsvuerun-20261009-161443#15091
hydrateOnVisible: Cannot read properties of null (reading 'nodeType') when the SSR node is detached before the IntersectionObserver callback fires
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches use the same core fix in `__asyncHydrate`'s `performHydrate`. They capture `wasConnected` up front, then bail if `!el.parentNode || (wasConnected && !el.isConnected)`. This addresses the root cause the issue identifies: a lazy strategy firing after the SSR node has been detached. It also keeps hydration working for apps that hydrate into a container never attached to the document. On correctness of the primary fix, the two are equivalent. Patch A adds the defense-in-depth hardening the issue explicitly suggests. `getContainerType` now tolerates a `null` container, and the non-null assertion is dropped at the async-component call site. The change is minimal, type-correct and low-risk. It guards the other `parentNode(node)` call path, so the TypeError cannot resurface via a different route. A also documents the new guard with a comment explaining the intent. On tests, B checks two cases with a detached root element and a detached ancestor. It asserts no throw and that the inner component never renders, which is a meaningful check that would fail before the fix. A's tests are broader: - a detached element root - a detached fragment root, where `el` is the fragment anchor comment - a detached ancestor, where the node keeps its parent but is disconnected - a custom user-provided strategy, showing the guard is strategy-agnostic - a positive control confirming a still-connected node does hydrate and gets its click listener The positive control matters because it guards against a fix that simply never hydrates. B has no such check. A's assertions are also behavioral: the listener is not attached to the detached node. With identical core logic, A wins on test thoroughness, including the regression guard against over-skipping, and on the issue-requested hardening. Neither adds risky scope.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
5m 29s
Wall-clock time in the container
Full test suite
No new failures
1,736 passed · 1 skipped · 1,737 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
134vs 56 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.33
Link to minimal reproduction
https://stackblitz.com/edit/vitejs-vite-ktsycrrc?file=repro.mjs
Steps to reproduce
- SSR-render an async component that uses hydrate: hydrateOnVisible().
- On the client, hydration is deferred and the strategy registers an IntersectionObserver on the component's SSR node.
- The node gets detached from the document before the observer's callback executes (in production this is a route change / re-render while the intersection callback is already queued).
- The observer callback runs and invokes hydrate() against the now-detached node.
What is expected?
A node that is no longer connected to the document should simply not be hydrated (there's nothing to hydrate), no exception thrown.
What is actually happening?
hydrate() reaches hydrateNode, which computes the container type from the node's parent:
// packages/runtime-core/src/hydration.ts — inside hydrateNode, async-component branch
nextNode = vnode.type.hydrate(
node, vnode, parentComponent, parentSuspense,
getContainerType(parentNode(node)), // parentNode(node) === null for a detached node
slotScopeIds, optimized, rendererInternals, hydrateNode,
)
// packages/runtime-core/src/hydration.ts
const getContainerType = (container) => {
if (container.nodeType !== 1) return undefined // <-- container is null -> throws
...
}
For a detached node parentNode(node) is null, so getContainerType(null) throws TypeError: Cannot read properties of null (reading 'nodeType').
The async-component hydration wrapper only guards against the patched case, never against disconnection:
// packages/runtime-core/src/apiAsyncComponent.ts — __asyncHydrate
const performHydrate = () => {
if (patched) { /* warn + */ return } // only guards `patched`
hydrate() // no isConnected check
}
Because the strategy runs inside load().then(...), the throw surfaces as an unhandledrejection, so app-level try/catch around the component can't catch it.
System Info
vue: 3.5.33
@vue/server-renderer: 3.5.33
Environment where it triggers: Android WebView (Chrome), production SSR + client hydration
Any additional comments?
We see this almost exclusively on Android Chrome WebView (~43k occurrences / ~12.8k users over a rollout window) on a page that lazy-hydrates several below-the-fold sections via hydrateOnVisible. The IntersectionObserver callback is dispatched asynchronously; when the user navigates/re-renders in the WebView, the observed node is detached between the intersection being recorded and the callback running, exactly the sequence above. Desktop rarely hits the race.
Skip hydration when the anchor node is no longer connected. the semantically correct place is the async performHydrate (or each built-in strategy's trigger), e.g. bail when no observed/anchor element isConnected:
const performHydrate = () => {
if (patched) { return }
if (el && !el.isConnected) return // detached before hydration → nothing to hydrate
hydrate()
}
As defense-in-depth, getContainerType could also tolerate a null container (if (!container || container.nodeType !== 1) return undefined), since it's called with parentNode(node) at several sites.
We're currently shipping a userland wrapper around hydrateOnVisible that applies exactly the isConnected guard, which fully stops the crash.
The two patches
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..d38cd71b9 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1315,6 +1316,125 @@ describe('SSR hydration', () => { ) }) + describe('lazy hydration of a node detached before the strategy fires', () => {+ let observerCallbacks: IntersectionObserverCallback[]+ const g = globalThis as any+ const OriginalIO = g.IntersectionObserver++ beforeEach(() => {+ observerCallbacks = []+ g.IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallbacks.push(cb)+ }+ observe() {}+ disconnect() {}+ }+ })++ afterEach(() => {+ g.IntersectionObserver = OriginalIO+ })++ const fireIntersection = () => {+ for (const cb of observerCallbacks) {+ cb([{ isIntersecting: true } as any], {} as any)+ }+ }++ async function setup(comp: any, hydrate: any) {+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(comp),+ hydrate,+ })+ const App = { render: () => h('div', [h(AsyncComp)]) }+ const html = await renderToString(h(App))+ const container = document.createElement('div')+ container.innerHTML = html+ document.body.appendChild(container)+ createSSRApp(App).mount(container)+ // wait for the async loader to resolve and the strategy to register+ await new Promise(r => setTimeout(r))+ return container+ }++ test('hydrateOnVisible: skips hydration of a detached element root', async () => {+ const onClick = vi.fn()+ const Comp = { render: () => h('button', { onClick }, 'click') }+ const container = await setup(Comp, hydrateOnVisible())+ expect(observerCallbacks.length).toBe(1)++ const button = container.querySelector('button')!+ // node detached (e.g. route change) before the observer callback runs+ container.firstChild!.removeChild(button)+ expect(() => fireIntersection()).not.toThrow()++ // nothing was hydrated: no listener attached to the detached node+ button.dispatchEvent(new Event('click'))+ expect(onClick).not.toHaveBeenCalled()+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ document.body.removeChild(container)+ })++ test('hydrateOnVisible: skips hydration of a detached fragment root', async () => {+ const onClick = vi.fn()+ const Comp = {+ render: () => [h('span', { onClick }, 'a'), h('span', 'b')],+ }+ const container = await setup(Comp, hydrateOnVisible())+ expect(observerCallbacks.length).toBe(1)++ const wrapper = container.firstChild!+ const span = container.querySelector('span')!+ const nodes = Array.from(wrapper.childNodes)+ nodes.forEach(n => wrapper.removeChild(n))+ expect(() => fireIntersection()).not.toThrow()+ span.dispatchEvent(new Event('click'))+ expect(onClick).not.toHaveBeenCalled()+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ document.body.removeChild(container)+ })++ test('hydrateOnVisible: skips hydration when an ancestor is detached from the document', async () => {+ const onClick = vi.fn()+ const Comp = { render: () => h('button', { onClick }, 'click') }+ const container = await setup(Comp, hydrateOnVisible())++ // the whole subtree is removed; the node keeps its parent but is no+ // longer in the document+ document.body.removeChild(container)+ expect(() => fireIntersection()).not.toThrow()+ container.querySelector('button')!.dispatchEvent(new Event('click'))+ expect(onClick).not.toHaveBeenCalled()+ })++ test('custom strategy: skips hydration once the node is detached', async () => {+ const onClick = vi.fn()+ const Comp = { render: () => h('button', { onClick }, 'click') }+ let trigger!: () => void+ const container = await setup(Comp, (hydrate: () => void) => {+ trigger = hydrate+ })++ const button = container.querySelector('button')!+ container.firstChild!.removeChild(button)+ expect(() => trigger()).not.toThrow()+ button.dispatchEvent(new Event('click'))+ expect(onClick).not.toHaveBeenCalled()+ document.body.removeChild(container)+ })++ test('hydrateOnVisible: still hydrates a connected node', async () => {+ const onClick = vi.fn()+ const Comp = { render: () => h('button', { onClick }, 'click') }+ const container = await setup(Comp, hydrateOnVisible())+ fireIntersection()+ container.querySelector('button')!.dispatchEvent(new Event('click'))+ expect(onClick).toHaveBeenCalledTimes(1)+ document.body.removeChild(container)+ })+ })+ test('hydrate safely when property used by async setup changed before render', async () => { const toggle = ref(true) packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..032ab4482 100644@@ -124,6 +124,7 @@ export function defineAsyncComponent< __asyncHydrate(el, instance, hydrate) { let patched = false+ const wasConnected = el.isConnected ;(instance.bu || (instance.bu = [])).push(() => (patched = true)) const performHydrate = () => { // skip hydration if the component has been patched@@ -136,6 +137,12 @@ export function defineAsyncComponent< } return }+ // skip hydration if the SSR node has been detached before lazy+ // hydration performed (e.g. the strategy's trigger fired after a+ // route change / re-render removed it) - there is nothing left to+ // hydrate. Apps hydrating into a container that was never attached to+ // the document are still hydrated as long as the node keeps its parent.+ if (!el.parentNode || (wasConnected && !el.isConnected)) return hydrate() } const doHydrate = hydrateStrategypackages/runtime-core/src/hydration.tsindex 405a5db93..a23c52486 100644@@ -73,9 +73,10 @@ const isMathMLContainer = (container: Element) => container.namespaceURI!.includes('MathML') const getContainerType = (- container: Element | ShadowRoot,+ container: Element | ShadowRoot | null, ): 'svg' | 'mathml' | undefined => {- if (container.nodeType !== DOMNodeTypes.ELEMENT) return undefined+ if (!container || container.nodeType !== DOMNodeTypes.ELEMENT)+ return undefined if (isSVGContainer(container as Element)) return 'svg' if (isMathMLContainer(container as Element)) return 'mathml' return undefined@@ -347,7 +348,7 @@ export function createHydrationFunctions( vnode, parentComponent, parentSuspense,- getContainerType(parentNode(node)!),+ getContainerType(parentNode(node)), slotScopeIds, optimized, rendererInternals,
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..89fa5e829 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1191,6 +1192,59 @@ describe('SSR hydration', () => { expect(spy).toHaveBeenCalled() }) + // #15091+ async function assertSkipLazyHydration(detached: 'root' | 'ancestor') {+ let observer!: IntersectionObserver+ let observerCallback!: IntersectionObserverCallback+ const originalIntersectionObserver = globalThis.IntersectionObserver+ globalThis.IntersectionObserver = class {+ constructor(callback: IntersectionObserverCallback) {+ observer = this as any+ observerCallback = callback+ }+ disconnect() {}+ observe() {}+ } as any++ try {+ const Comp = vi.fn(() => h('p', 'hello'))+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Comp),+ hydrate: hydrateOnVisible(),+ })+ const App = () => h(AsyncComp)+ const container = document.createElement('div')++ container.innerHTML = await renderToString(h(App))+ document.body.appendChild(container)+ Comp.mockClear()+ createSSRApp(App).mount(container)++ const el = container.firstElementChild!+ if (detached === 'root') {+ el.remove()+ } else {+ container.remove()+ }+ expect(el.isConnected).toBe(false)++ expect(() =>+ observerCallback(+ [{ isIntersecting: true, target: el } as IntersectionObserverEntry],+ observer,+ ),+ ).not.toThrow()+ expect(Comp).not.toHaveBeenCalled()+ } finally {+ globalThis.IntersectionObserver = originalIntersectionObserver+ }+ }++ test.each(['root', 'ancestor'] as const)(+ 'skip lazy hydration when the SSR %s is detached',+ assertSkipLazyHydration,+ )+ test('update async wrapper before resolve', async () => { const Comp = { render() {packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..95de65b8e 100644@@ -123,6 +123,7 @@ export function defineAsyncComponent< __asyncLoader: load, __asyncHydrate(el, instance, hydrate) {+ const wasConnected = el.isConnected let patched = false ;(instance.bu || (instance.bu = [])).push(() => (patched = true)) const performHydrate = () => {@@ -136,6 +137,7 @@ export function defineAsyncComponent< } return }+ if (!el.parentNode || (wasConnected && !el.isConnected)) return hydrate() } const doHydrate = hydrateStrategy