Backtestsvuerun-20261002-115633#15091

Issue #15091 Merged fix PR #15092 Run 2 Oct 2026 · run-20261002-115633 vuejs/core

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

Better

Our patch was judged better than the merged fix.

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

Both patches make the same runtime change in `__asyncHydrate`. They capture `wasConnected = el.isConnected` up front, and `performHydrate` bails out when `!el.parentNode || (wasConnected && !el.isConnected)`. This fixes the root cause the issue identifies: `hydrate()` running on a detached node. It also keeps hydration working for containers that were never attached to the document. Correctness is therefore identical.

The patches differ in tests and craft.

Patch A's tests cover detaching the root element and detaching an ancestor. They call the mocked observer callback directly. This works only because the same async component was resolved during `renderToString`, so the strategy registers synchronously. That is a somewhat implicit dependency. Patch A also has no positive test showing that a connected node still hydrates, and no test for a container outside the document. Without those, a regression from an over-broad guard would go unnoticed.

Patch B's tests are much more thorough:
- a detached single root;
- a detached fragment root, which exercises the anchor/comment path;
- a detached ancestor where the node keeps its parent;
- a positive case where a connected node hydrates and its event handlers work;
- a custom strategy in an off-document container, both the skip case and the hydrate case, which verifies the `wasConnected` nuance;
- no strategy, where the node is detached before the loader resolves.

These tests would fail before the fix and also guard against false negatives. Patch B also adds comments explaining the non-obvious `wasConnected` logic, while Patch A's one-line guard is unexplained.

Neither patch adds scope beyond the issue. With identical fixes, Patch B wins clearly on test quality and clarity.

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

12m 12s

Wall-clock time in the container

Full test suite

No new failures

3,625 passed · 6 skipped · 3,631 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

182vs 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+182 −0
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..e51fdf8df 100644@@ -19,6 +19,7 @@ import {   defineAsyncComponent,   defineComponent,   h,+  hydrateOnVisible,   nextTick,   onMounted,   onServerPrefetch,@@ -36,6 +37,7 @@ import { import * as runtimeDom from '@vue/runtime-dom' import type { HMRRuntime } from '../src/hmr' import type { InternalRenderFunction } from '../src/component'+import type { HydrationStrategy } from '../src/hydrationStrategies' import { type SSRContext, renderToString } from '@vue/server-renderer' import { type CompilerOptions, compile } from '@vue/compiler-dom' import { PatchFlags, normalizeStyle } from '@vue/shared'@@ -1482,6 +1484,177 @@ describe('SSR hydration', () => {     resolve({})   }) +  describe('lazy hydration of detached SSR node', () => {+    let observerCallbacks: IntersectionObserverCallback[]+    const OriginalIntersectionObserver = (window as any).IntersectionObserver++    beforeEach(() => {+      observerCallbacks = []+      ;(window as any).IntersectionObserver = class {+        constructor(cb: IntersectionObserverCallback) {+          observerCallbacks.push(cb)+        }+        observe() {}+        disconnect() {}+      }+    })++    afterEach(() => {+      ;(window as any).IntersectionObserver = OriginalIntersectionObserver+    })++    const fireIntersection = () => {+      for (const cb of observerCallbacks) {+        cb([{ isIntersecting: true } as IntersectionObserverEntry], null!)+      }+    }++    async function setup(+      render: () => any,+      hydrate: HydrationStrategy,+      attachToDocument = true,+    ) {+      const mounted = vi.fn()+      const Inner = { render, mounted }+      const html = await renderToString(+        h({ render: () => h('main', [h(Inner)]) }),+      )+      const container = document.createElement('div')+      container.innerHTML = html+      if (attachToDocument) document.body.appendChild(container)+      createSSRApp({+        render: () =>+          h('main', [+            h(+              defineAsyncComponent({+                loader: () => Promise.resolve(Inner),+                hydrate,+              }),+            ),+          ]),+      }).mount(container)+      // wait for the loader to resolve and the strategy to be registered+      await new Promise(r => setTimeout(r))+      return { container, mounted }+    }++    test('hydrateOnVisible: skip hydration when node is detached before observer callback', async () => {+      const { container, mounted } = await setup(+        () => h('button', 'hi'),+        hydrateOnVisible(),+      )+      expect(observerCallbacks.length).toBe(1)+      container.querySelector('button')!.remove()++      expect(() => fireIntersection()).not.toThrow()+      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+      container.remove()+    })++    test('hydrateOnVisible: skip hydration when fragment root is detached before observer callback', async () => {+      const { container, mounted } = await setup(+        () => [h('button', 'a'), h('button', 'b')],+        hydrateOnVisible(),+      )+      expect(observerCallbacks.length).toBe(1)+      container.querySelector('main')!.innerHTML = ''++      expect(() => fireIntersection()).not.toThrow()+      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+      container.remove()+    })++    test('hydrateOnVisible: skip hydration when an ancestor is detached from the document', async () => {+      const { container, mounted } = await setup(+        () => h('button', 'hi'),+        hydrateOnVisible(),+      )+      // the node keeps its parent but is no longer in the document+      container.querySelector('main')!.remove()++      expect(() => fireIntersection()).not.toThrow()+      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+      container.remove()+    })++    test('hydrateOnVisible: hydrates when node is still connected', async () => {+      const spy = vi.fn()+      const { container, mounted } = await setup(+        () => h('button', { onClick: spy }, 'hi'),+        hydrateOnVisible(),+      )+      fireIntersection()+      await nextTick()+      expect(mounted).toHaveBeenCalledTimes(1)+      triggerEvent('click', container.querySelector('button')!)+      expect(spy).toHaveBeenCalled()+      container.remove()+    })++    test('custom strategy: skip hydration when node is detached in a container outside the document', async () => {+      let doHydrate!: () => void+      const { container, mounted } = await setup(+        () => h('button', 'hi'),+        hydrate => {+          doHydrate = hydrate+        },+        false,+      )+      container.querySelector('button')!.remove()++      expect(() => doHydrate()).not.toThrow()+      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+    })++    test('custom strategy: hydrates in a container outside the document', async () => {+      let doHydrate!: () => void+      const spy = vi.fn()+      const { container, mounted } = await setup(+        () => h('button', { onClick: spy }, 'hi'),+        hydrate => {+          doHydrate = hydrate+        },+        false,+      )+      doHydrate()+      await nextTick()+      expect(mounted).toHaveBeenCalledTimes(1)+      triggerEvent('click', container.querySelector('button')!)+      expect(spy).toHaveBeenCalled()+    })++    test('no strategy: skip hydration when node is detached before loader resolves', async () => {+      const mounted = vi.fn()+      const Inner = { render: () => h('button', 'hi'), mounted }+      const html = await renderToString(+        h({ render: () => h('main', [h(Inner)]) }),+      )++      let resolve: any+      const container = document.createElement('div')+      container.innerHTML = html+      document.body.appendChild(container)+      createSSRApp({+        render: () =>+          h('main', [+            h(defineAsyncComponent(() => new Promise(r => (resolve = r)))),+          ]),+      }).mount(container)++      container.querySelector('button')!.remove()+      resolve(Inner)+      await new Promise(r => setTimeout(r))++      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+      container.remove()+    })+  })+   //#12362   test('nested async wrapper', async () => {     const Toggle = defineAsyncComponent(packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..5f28bb0a0 100644@@ -125,6 +125,10 @@ export function defineAsyncComponent<     __asyncHydrate(el, instance, hydrate) {       let patched = false       ;(instance.bu || (instance.bu = [])).push(() => (patched = true))+      // the SSR node may be hydrated inside a container that is not attached to+      // the document, so only treat losing the connection as a detachment if+      // it was connected to begin with.+      const wasConnected = el.isConnected       const performHydrate = () => {         // skip hydration if the component has been patched         if (patched) {@@ -136,6 +140,11 @@ export function defineAsyncComponent<           }           return         }+        // skip hydration if the SSR node has been detached before lazy+        // hydration performed - there is nothing left to hydrate.+        if (!el.parentNode || (wasConnected && !el.isConnected)) {+          return+        }         hydrate()       }       const doHydrate = hydrateStrategy 
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