Docs
Protocol Verified

[FIX-010] Hydration Mismatch #418

Fixing React hydration errors caused by HTML comment nodes.

PRID: 1121
VERIFIED
1 min read

[FIX-010] Hydration Mismatch #418 (Comment Nodes)

📝 Problem Background

During the SSG integration, the application crashed immediately on boot with Minified React error #418. This indicates a hydration mismatch where the server-rendered HTML does not match what the client expected.

🧪 Effort Metrics

  • Attempt Count: 2
  • Time Spent: 45 min
  • Complexity: ⭐⭐⭐ (Tricky)

🔍 Root Cause Analysis

The "Comment" Trap:

  1. The SSG build process inserts a comment node <!--ssr-outlet--> into the <div id="root"> when no content is pre-rendered for client-only routes.
  2. The client entry script checked rootElement.hasChildNodes() to decide whether to hydrate or render.
  3. hasChildNodes() returns true for Comment Nodes.
  4. React tried to hydrate a Comment Node, expecting an App, resulting in a mismatch.

🛠️ Fix Strategy

Strict Element Detection: Refactor the hydration check to specifically look for ELEMENT_NODE (Type 1), ignoring comments and text nodes.

typescript
const hasStaticContent = Array.from(rootElement.childNodes).some( (node) => node.nodeType === Node.ELEMENT_NODE ); if (hasStaticContent) { hydrateRoot(rootElement, <App />); } else { createRoot(rootElement).render(<App />); }

Status: Resolved. Hybrid injection strategy is stable.

Authority Distribution

Share this technical artifact