// HydrationDiagnosticsPanel.jsx
// Usage:
// 1. In your SSR app's HTML template (e.g., _document.js in Next.js or index.html), add BEFORE any React scripts:
// <script>window.__INITIAL_HTML = document.documentElement.outerHTML;</script>
// 2. Import and render <HydrationDiagnosticsPanel /> anywhere in your app (ideally at app root for global access).
// 3. Works best in __DEV__ mode. Install no external deps (self-contained diff).
// 4. Features:
// - Asset readiness: Resource timing table for JS/CSS (load/parse times).
// - Server-client diff: Line-by-line HTML diff (body only, git-style) pre/post-hydration.
// - Mismatch stacks: Captures hydration warnings/errors with browser stacks.
// 5. Toggle with top-right button. Auto-captures on mount.
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createPortal } from 'react-dom';
const isDev = process.env.NODE_ENV === 'development';
const HydrationDiagnosticsPanel = () => {
const [isOpen, setIsOpen] = useState(false);
const [initialHTML, setInitialHTML] = useState('');
const [currentHTML, setCurrentHTML] = useState('');
const [hydrationErrors, setHydrationErrors] = useState([]);
const [resources, setResources] = useState([]);
const originalConsoleWarnRef = useRef(console.warn);
const originalConsoleErrorRef = useRef(console.error);
const hydrationTimeoutRef = useRef();
// Capture post-hydration HTML (debounced to allow hydration + any immediate client updates)
const captureCurrentHTML = useCallback(() => {
if (document.body) {
setCurrentHTML(document.body.innerHTML);
}
}, []);
// Simple line-based HTML diff (git-style: + added, - removed, ! changed)
const computeDiff = (oldHtml, newHtml) => {
if (!oldHtml || !newHtml) return [];
const oldLines = oldHtml.split('\n');
const newLines = newHtml.split('\n');
const diff = [];
let i = 0, j = 0;
while (i < oldLines.length || j < newLines.length) {
if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
diff.push({ type: ' ', line: oldLines[i] });
i++; j++;
} else if (i < oldLines.length && oldLines[i] === newLines[j + 1] && newLines[j] === oldLines[i + 1]) {
// Swap
diff.push({ type: '-', line: oldLines[i] });
diff.push({ type: '+', line: newLines[j] });
i++; j++;
} else {
const oldLine = oldLines[i];
const newLine = newLines[j];
if (oldLine && newLine && oldLine.trim() === newLine.trim()) {
diff.push({ type: '!', line: newLine }); // Content same, whitespace diff
i++; j++;
} else {
if (i < oldLines.length) {
diff.push({ type: '-', line: oldLines[i] });
i++;
}
if (j < newLines.length) {
diff.push({ type: '+', line: newLines[j] });
j++;
}
}
}
}
return diff.slice(0, 100); // Limit to first 100 lines for perf
};
// Hydration warning interceptor
const installConsoleInterceptors = useCallback(() => {
if (!isDev) return;
const checkAndCapture = (args) => {
const msg = args[0];
if (msg && typeof msg === 'string' && (
msg.includes('Hydration') ||
msg.includes('Text content does not match server') ||
msg.includes('Expected server HTML')
)) {
const stack = new Error().stack || '';
setHydrationErrors(prev => [...prev, { msg, stack, timestamp: Date.now() }]);
}
};
originalConsoleWarnRef.current = console.warn;
originalConsoleErrorRef.current = console.error;
console.warn = (...args) => {
checkAndCapture(args);
originalConsoleWarnRef.current(...args);
};
console.error = (...args) => {
checkAndCapture(args);
originalConsoleErrorRef.current(...args);
};
}, []);
// Cleanup interceptors
const uninstallConsoleInterceptors = useCallback(() => {
if (originalConsoleWarnRef.current) console.warn = originalConsoleWarnRef.current;
if (originalConsoleErrorRef.current) console.error = originalConsoleErrorRef.current;
}, []);
useEffect(() => {
if (!isDev) return;
// Capture initial HTML from global
if (window.__INITIAL_HTML) {
setInitialHTML(window.__INITIAL_HTML);
}
// Install interceptors
installConsoleInterceptors();
// Capture resources (assets)
if (performance.getEntriesByType) {
const entries = performance.getEntriesByType('resource')
.filter(entry => entry.initiatorType === 'script' || entry.name.match(/\.(css|js)(\?|$)/))
.map(entry => ({
name: entry.name,
duration: entry.duration,
startTime: entry.startTime,
responseEnd: entry.responseEnd,
initiatorType: entry.initiatorType,
}));
setResources(entries);
}
// Capture post-hydration HTML (debounce)
hydrationTimeoutRef.current = setTimeout(captureCurrentHTML, 100);
const interval = setInterval(captureCurrentHTML, 1000); // Periodic for client mutations
return () => {
uninstallConsoleInterceptors();
clearTimeout(hydrationTimeoutRef.current);
clearInterval(interval);
};
}, [installConsoleInterceptors, captureCurrentHTML]);
const diff = React.useMemo(() => computeDiff(initialHTML ? document.body.innerHTML : '', currentHTML), [initialHTML, currentHTML]);
if (!isDev) return null;
const PanelContent = () => (
<div className="fixed top-4 right-4 z-[9999] w-96 h-[80vh] bg-white border-2 border-blue-500 shadow-2xl rounded-lg flex flex-col overflow-hidden">
<div className="bg-blue-500 text-white p-3 flex justify-between items-center">
<h2 className="font-bold text-lg">🧪 Hydration Diagnostics</h2>
<button onClick={() => setIsOpen(false)} className="text-xl">×</button>
</div>
<div className="flex-1 overflow-auto p-4 space-y-4 text-sm">
{/* Tab Buttons */}
<div className="flex border-b">
<button className="flex-1 py-1 bg-blue-100 border-b-2 border-blue-500 font-medium">Assets</button>
<button className="flex-1 py-1 hover:bg-gray-100">Diff</button>
<button className="flex-1 py-1 hover:bg-gray-100">Errors</button>
</div>
{/* Assets Tab */}
<div className="space-y-2">
<h3 className="font-semibold text-blue-600">📦 Asset Readiness ({resources.length})</h3>
<div className="max-h-32 overflow-auto">
<table className="w-full text-xs border-collapse">
<thead>
<tr className="bg-gray-100">
<th className="p-1 text-left">Asset</th>
<th className="p-1 text-right w-20">Duration</th>
<th className="p-1 text-right w-20">End (ms)</th>
</tr>
</thead>
<tbody>
{resources.map((r, i) => (
<tr key={i} className="border-t">
<td className="p-1 truncate max-w-32" title={r.name}>{r.name.split('/').pop()}</td>
<td className="p-1 text-right text-green-600">{r.duration.toFixed(0)}ms</td>
<td className="p-1 text-right">{r.responseEnd.toFixed(0)}ms</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Diff Tab */}
<div className="space-y-2">
<h3 className="font-semibold text-purple-600">🔄 Server-Client Diff ({diff.length} lines)</h3>
<pre className="bg-gray-50 p-2 max-h-32 overflow-auto text-xs font-mono border">
{diff.map((d, i) => (
<div key={i} className={`whitespace-pre-wrap ${d.type === '+' ? 'text-green-600' : d.type === '-' ? 'text-red-600' : d.type === '!' ? 'text-orange-600' : ''}`}>
{d.type} {d.line}
</div>
))}
</pre>
{!initialHTML && <p className="text-xs text-gray-500">No __INITIAL_HTML found. Add script to HTML template.</p>}
</div>
{/* Errors Tab */}
<div className="space-y-2">
<h3 className="font-semibold text-red-600">⚠️ Mismatch Stacks ({hydrationErrors.length})</h3>
<div className="max-h-32 overflow-auto space-y-2">
{hydrationErrors.map((e, i) => (
<details key={i} className="bg-red-50 p-2 rounded text-xs">
<summary className="cursor-pointer font-medium">{e.msg}</summary>
<pre className="mt-1 text-gray-700 whitespace-pre-wrap">{e.stack}</pre>
</details>
))}
{hydrationErrors.length === 0 && <p className="text-gray-500 text-xs italic">No hydration errors captured.</p>}
</div>
</div>
</div>
</div>
);
return (
<>
{!isOpen && (
<button
onClick={() => setIsOpen(true)}
className="fixed top-4 right-4 z-[9998] bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg text-sm font-medium"
title="Open Hydration Diagnostics"
>
🧪 Hydration
</button>
)}
{isOpen && createPortal(<PanelContent />, document.body)}
</>
);
};
export default HydrationDiagnosticsPanel;
Quick Setup Guide
Next.js Example (pages/_document.js or app/layout.js):
// In <Head> or <head>
<script
dangerouslySetInnerHTML={{
__html: `window.__INITIAL_HTML = document.documentElement.outerHTML;`,
}}
/>
Root Layout/App:
import HydrationDiagnosticsPanel from './HydrationDiagnosticsPanel';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<HydrationDiagnosticsPanel />
</body>
</html>
);
}
CRA/Vite/HTML:
Add the <script> directly in public/index.html before <script type="module" src="/src/index.js">.
Limitations & Enhancements
- Diff: Line-based (not perfect tree diff). For production, add
diff lib or react-diff-viewer.
- Timing: Captures post-mount. For precise "before hydration", wrap
hydrateRoot with performance.mark.
- Stacks: Browser stacks (React component stacks in dev console). Use
react-error-overlay for deeper.
- Perf: Dev-only, throttled.
- Extend: Add tree serializer via
ReactDOMServer.renderToStaticMarkup(React.createElement(App)) (requires app root access).
This panel auto-exposes mismatches/diffs/assets in a draggable-ish overlay. Test by forcing mismatches (e.g., Date.now() in SSR component).