Fix Hydration Errors in Next.js
Source: Dev.to
Common Causes of Hydration Errors
Browser/Environment Issues
- Browser extensions injecting attributes (password managers, ad blockers, accessibility tools)
- Browser auto‑fill adding attributes to form elements
- Third‑party scripts modifying the DOM before React hydrates
- Different timezones causing date/time mismatches between server and client
Code Issues
- Using browser‑only APIs during SSR (
window,localStorage,document) - Random values or
Math.random()in render (server generates different value than client) - Date objects using
new Date()without consistent formatting - Using
useEffectoruseStatethat modifies content on initial render - Inconsistent whitespace in template literals (extra spaces, newlines)
- Conditional rendering based on client‑only values (
window.innerWidth, user‑agent detection)
Data Issues
- Server and client fetching different data or at different times
- Missing
keyprops in lists causing reordering issues - Using non‑serializable data in server components (functions, symbols)
- Inconsistent data formatting between server and client (dates, numbers, locales)
CSS/Styling Issues
- CSS‑in‑JS libraries that generate different class names on server vs client
- CSS modules with inconsistent hash generation
- Media queries that apply different styles on server vs client
Component Issues
-
Nesting block elements inside inline elements
<span> <div>inside</div> </span> -
Invalid HTML structure (SSR might render differently than the browser parses)
-
Third‑party components that aren’t SSR‑compatible
-
Portals rendering in different locations
Best Practice
Always check if code relies on client‑only APIs and wrap them in useEffect or use the 'use client' directive appropriately.