Fix SSR Hydration Mismatches in Next.js, Nuxt & Vue
Why rendering window, localStorage, or new Date() during SSR causes hydration mismatches, and how deferring to mount fixes it.
By the end of this tutorial you will know:
- What hydration is and why React/Vue compare server HTML to the first client render
- Which browser-only values (
Date.now(),localStorage,window) trigger mismatches - How to defer client-only UI until after mount cleanly
Prerequisites: Basic familiarity with React or Vue components.
1. The big idea
With Server-Side Rendering (SSR), the server renders your component to HTML first, sends it to the browser, and then React/Vue hydrates that HTML on the client by running the component again and attaching event listeners.
If the first client render produces different text or tags than the server did, the framework throws a Hydration Mismatch error.
2. Reproducing the mismatch
"use client";
export function BrokenClock() {
// Server renders at 12:00:00.001, client hydrates at 12:00:00.450!
return <p>Current time: {new Date().toLocaleTimeString()}</p>;
}Any value that differs between server and client on the initial render—new Date(), Math.random(), window.innerWidth, or localStorage.getItem(...)—breaks hydration.
3. The fix: defer client-only values until after mount
Render a stable placeholder (or null) on the server and initial client pass, then populate the browser-only value inside useEffect (or onMounted in Vue).
"use client";
import { useEffect, useState } from "react";
export function SafeClock() {
const [time, setTime] = useState<string | null>(null);
useEffect(() => {
const update = () => setTime(new Date().toLocaleTimeString());
update();
const id = window.setInterval(update, 1000);
return () => window.clearInterval(id);
}, []);
return <p>Current time: {time ?? "—"}</p>;
}Reload the page with DevTools Console open. The hydration mismatch warning is gone, and the clock updates smoothly after mount.
4. Common pitfalls
| Cause | Symptom | Fix |
|---|---|---|
typeof window !== "undefined" in JSX | Server renders null, client renders <div> | Use useEffect state so first client render matches server |
new Date().toLocaleString() | Timezone/locale differs between server and user | Format inside useEffect after mount |
Invalid HTML nesting (<p> inside <p>) | Browser auto-closes tags, breaking DOM tree | Check browser DevTools for nested block elements |
5. What you learned
You now know why SSR hydration requires the server and initial client render to match, and how post-mount effects eliminate mismatches cleanly.