September 5, 2024 1 min read
Hydration Mismatch Bug in Next.js with Dynamic Imports
Bug Fix
Depth: ●●○○○
Debugging a frustrating hydration error caused by client-only libraries loaded via dynamic imports.
The Problem
Console error: 'Text content does not match server-rendered HTML'. Appeared randomly on page load. Component worked fine in development but failed in production.
Investigation
The chart library (Recharts) was being imported normally but accessed browser APIs during render. Server rendered null, client rendered the chart, causing mismatch.
Solution
Used dynamic import with ssr: false. Also added a loading skeleton to prevent layout shift. Key lesson: any library that touches window/document needs ssr: false.