Backtestsvuerun-20261001-022054#15091

Issue #15091 Merged fix PR #15092 Run 30 Sep 2026 · run-20261001-022054 vuejs/core

hydrateOnVisible: Cannot read properties of null (reading 'nodeType') when the SSR node is detached before the IntersectionObserver callback fires

Worse

The merged fix was judged better than our patch.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches add a guard in `performHydrate` inside `__asyncHydrate`, which is where the issue says the fix belongs. Both stop the reported `getContainerType(null)` crash when the SSR root node itself is removed.

The difference is coverage. Patch B only checks `!el.parentNode`. The issue's expected behavior is that a node no longer connected to the document should not be hydrated. In the common real-world case (route change or re-render), an ancestor is removed rather than the component's own root. Then `el.parentNode` is still non-null, so B goes ahead and hydrates a detached subtree. It doesn't crash, but it does pointless work against stale DOM, which is the scenario the issue asks to skip.

Patch A checks `isConnected`, which also catches ancestor detachment. It records `wasConnected` at setup so that hydration into a container that was never attached (common in tests and some setups) is not wrongly skipped. That is a careful edge-case consideration.

Tests: Patch A uses the real `hydrateOnVisible` strategy and a mocked IntersectionObserver, parameterized over root detachment and ancestor detachment. This directly exercises the behavior gap between the two patches. Patch B's two tests cover only root detachment, using a custom strategy and `hydrateOnVisible`; they are reasonable but miss the ancestor case.

Patch B's extra `getContainerType` null-tolerance is harmless defense-in-depth that the issue suggested, but it earns no credit on its own. Overall, A covers the issue's semantics more completely, with tests to match.

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

3m 18s14 turns

Wall-clock time in the container

Full test suite

No new failures

3,620 passed · 6 skipped · 3,626 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

106vs 56 merged

Changed lines, ours vs merged

Vue version

3.5.33

Link to minimal reproduction

https://stackblitz.com/edit/vitejs-vite-ktsycrrc?file=repro.mjs

Steps to reproduce

  1. SSR-render an async component that uses hydrate: hydrateOnVisible().
  2. On the client, hydration is deferred and the strategy registers an IntersectionObserver on the component's SSR node.
  3. 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).
  4. 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

Our patch+103 −3
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..fd96457a5 100644@@ -19,6 +19,7 @@ import {   defineAsyncComponent,   defineComponent,   h,+  hydrateOnVisible,   nextTick,   onMounted,   onServerPrefetch,@@ -1315,6 +1316,100 @@ describe('SSR hydration', () => {     )   }) +  // lazy hydration of a detached node+  test('lazy hydration of async component should be skipped if its node is detached', async () => {+    const spy = vi.fn()+    const Comp = () => h('button', { onClick: spy }, 'click')++    let triggerHydrate: (() => void) | undefined+    const AsyncComp = defineAsyncComponent({+      loader: () => Promise.resolve(Comp),+      hydrate: hydrate => {+        triggerHydrate = hydrate+      },+    })+    const App = () => h(AsyncComp)++    const html = await renderToString(h(App))+    expect(html).toBe('<button>click</button>')++    const container = document.createElement('div')+    container.innerHTML = html+    createSSRApp(App).mount(container)++    // resolve loader+    await new Promise(r => setTimeout(r))+    expect(triggerHydrate).toBeDefined()++    // detach the SSR node before the strategy triggers hydration+    const btn = container.firstChild as HTMLButtonElement+    btn.remove()+    expect(btn.parentNode).toBe(null)++    expect(() => triggerHydrate!()).not.toThrow()+    await nextTick()++    // not hydrated+    btn.dispatchEvent(new Event('click'))+    expect(spy).not.toHaveBeenCalled()+  })++  // lazy hydration of a detached node+  test('hydrateOnVisible should not throw if the node is detached before it becomes visible', async () => {+    const originalIO = (globalThis as any).IntersectionObserver+    let ioCallback: ((entries: any[]) => void) | undefined+    const observed: Element[] = []+    ;(globalThis as any).IntersectionObserver = class {+      constructor(cb: (entries: any[]) => void) {+        ioCallback = cb+      }+      observe(el: Element) {+        observed.push(el)+      }+      unobserve() {}+      disconnect() {}+    }++    try {+      const spy = vi.fn()+      const Comp = () => h('button', { onClick: spy }, 'click')+      const AsyncComp = defineAsyncComponent({+        loader: () => Promise.resolve(Comp),+        hydrate: hydrateOnVisible(),+      })+      const App = () => h(AsyncComp)++      const html = await renderToString(h(App))+      expect(html).toBe('<button>click</button>')++      const container = document.createElement('div')+      container.innerHTML = html+      createSSRApp(App).mount(container)++      // resolve loader+      await new Promise(r => setTimeout(r))++      const btn = container.firstChild as HTMLButtonElement+      expect(ioCallback).toBeDefined()+      expect(observed).toContain(btn)++      // detach the SSR node before it becomes visible+      btn.remove()+      expect(btn.parentNode).toBe(null)++      expect(() =>+        ioCallback!([{ isIntersecting: true, target: btn }]),+      ).not.toThrow()+      await nextTick()++      // not hydrated+      btn.dispatchEvent(new Event('click'))+      expect(spy).not.toHaveBeenCalled()+    } finally {+      ;(globalThis as any).IntersectionObserver = originalIO+    }+  })+   test('hydrate safely when property used by async setup changed before render', async () => {     const toggle = ref(true) packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..2e957c2cd 100644@@ -136,6 +136,10 @@ export function defineAsyncComponent<           }           return         }+        // skip hydration if the node has been detached before lazy hydration+        // performed, e.g. the intersection callback of `hydrateOnVisible`+        // fires after the node is removed - there is nothing to hydrate.+        if (!el.parentNode) 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, 
Merged fix · PR #15092+56 −0
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 

What the agent reported

The crash is fixed: a lazily hydrated async component whose server-rendered node is removed before its hydration strategy fires now skips hydration instead of throwing. The new regression tests failed before the change and pass after it, and the existing hydration, async-component and server-renderer tests still pass.

What was wrong: the wrapper in packages/runtime-core/src/apiAsyncComponent.ts that runs a deferred hydration (performHydrate) only checked whether the component had been updated in the meantime. It never checked whether the node was still in the DOM. For a removed node, hydrateNode called getContainerType(parentNode(node)!) with null, and getContainerType read .nodeType from it, which threw.

What I changed:

  1. packages/runtime-core/src/apiAsyncComponent.ts: performHydrate now returns early with if (!el.parentNode) return before calling hydrate(). Every strategy goes through this function, including hydrateOnVisible, hydrateOnIdle, hydrateOnMediaQuery and custom ones.
  2. packages/runtime-core/src/hydration.ts: getContainerType now accepts null and returns undefined for it. I also removed the ! assertion at the async-component call site.

Why parentNode rather than the suggested isConnected: I tried !el.isConnected and it broke 3 existing tests ("async component", "Suspense + async component", "nested async wrapper"). Those tests hydrate into a container that was never added to the document, and apps can legitimately do the same. The parentNode check targets exactly the null parent that causes the crash.

Tests (added in packages/runtime-core/__tests__/hydration.spec.ts):

  • "lazy hydration of async component should be skipped if its node is detached": a custom strategy captures hydrate. The test removes the server-rendered button, calls hydrate, and asserts that nothing throws and that clicking the button does not fire its handler.
  • "hydrateOnVisible should not throw if the node is detached before it becomes visible": this reproduces your scenario. The test environment has no IntersectionObserver, so the test installs a minimal stand-in and restores the original afterwards. It removes the node, then fires the intersection callback, and makes the same two assertions.

Results:

  • Before the fix: both tests failed with TypeError: Cannot read properties of null (reading 'nodeType').
  • After the fix: the hydration, async-component and server-renderer tests all pass: 19 files, 444 tests.
  • Type check: tsc --noEmit passes.
  • Review: the reviewer found no blocking issues and nothing unrelated in the diff.

Requirements:

AskStatus
A removed node is not hydrated and nothing is thrownDone; both tests above
Guard in performHydrateDone, using parentNode instead of isConnected for the reason above
Guard in each built-in strategy (offered as an alternative)Not done: the performHydrate guard already covers every strategy, as the hydrateOnVisible test shows
getContainerType tolerates nullDone; no test covers it on its own, because the main guard returns before it can be reached in these scenarios
No unhandled rejection from the load().then(...) pathCovered, since the throw that caused it no longer happens

One behaviour note: one case is still not caught. If the node stays inside its parent but that whole subtree is removed from the document, it will still be hydrated. That doesn't crash, because the node still has a parent. Unlike the existing "component was updated" skip, the new skip logs no development warning.

All changes are uncommitted in the working tree.