No articles found
Try different keywords or browse our categories
Fix: Text content does not match server-rendered HTML error in Next.js - Quick Solutions
Quick guide to fix 'Text content does not match server-rendered HTML' errors in Next.js. Essential fixes with minimal code examples.
The ‘Text content does not match server-rendered HTML’ error occurs when client-side rendered text differs from server-rendered text during hydration. This hydration mismatch causes React to warn about content inconsistencies.
Common Causes and Fixes
1. Dynamic Content Differences
// ❌ Error: Server and client render different content
const Component = () => {
return <div>{new Date().toLocaleTimeString()}</div>; // Server: different time, Client: different time
};
// ✅ Fixed: Consistent content
import { useState, useEffect } from 'react';
const Component = () => {
const [time, setTime] = useState('Loading...');
useEffect(() => {
setTime(new Date().toLocaleTimeString());
}, []);
return <div>{time}</div>;
};
2. Conditional Rendering
// ❌ Error: Different content on server vs client
const Component = () => {
return <div>{typeof window !== 'undefined' ? 'Client' : 'Server'}</div>; // Mismatch
};
// ✅ Fixed: Consistent initial render
import { useState, useEffect } from 'react';
const Component = () => {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return <div>{isClient ? 'Client' : 'Server'}</div>;
};
3. Random Values
// ❌ Error: Random values differ
const Component = () => {
return <div>{Math.random()}</div>; // Different values on server and client
};
// ✅ Fixed: Consistent values
import { useState, useEffect } from 'react';
const Component = () => {
const [randomValue, setRandomValue] = useState('Loading...');
useEffect(() => {
setRandomValue(Math.random());
}, []);
return <div>{randomValue}</div>;
};
4. User Agent Detection
// ❌ Error: Different content based on user agent
const Component = () => {
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
return <div>{isMobile ? 'Mobile' : 'Desktop'}</div>; // Server: Desktop, Client: Mobile
};
// ✅ Fixed: Consistent initial render
import { useState, useEffect } from 'react';
const Component = () => {
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
setIsMobile(window.innerWidth < 768);
}, []);
return <div>{isMobile ? 'Mobile' : 'Desktop'}</div>;
};
5. Timestamps
// ❌ Error: Timestamps differ
const Component = () => {
return <div>Time: {Date.now()}</div>; // Different values
};
// ✅ Fixed: Consistent timestamps
import { useState, useEffect } from 'react';
const Component = () => {
const [timestamp, setTimestamp] = useState(0);
useEffect(() => {
setTimestamp(Date.now());
}, []);
return <div>Time: {timestamp}</div>;
};
6. Using Dynamic Imports
// ❌ Error: Browser-specific content
const Component = () => {
return <div>Width: {window.innerWidth}</div>; // Server: error, Client: works
};
// ✅ Fixed: Dynamic import with SSR disabled
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(
() => import('./BrowserComponent'),
{ ssr: false }
);
const BrowserComponent = () => {
return <div>Width: {window.innerWidth}</div>;
};
export default DynamicComponent;
7. Local Storage Access
// ❌ Error: Local storage access during render
const Component = () => {
const savedValue = localStorage.getItem('value') || 'default';
return <div>{savedValue}</div>; // Server: default, Client: saved value
};
// ✅ Fixed: Client-side only access
import { useState, useEffect } from 'react';
const Component = () => {
const [value, setValue] = useState('Loading...');
useEffect(() => {
const savedValue = localStorage.getItem('value') || 'default';
setValue(savedValue);
}, []);
return <div>{value}</div>;
};
8. Navigator Properties
// ❌ Error: Navigator properties
const Component = () => {
return <div>Browser: {navigator.userAgent}</div>; // Server: error, Client: works
};
// ✅ Fixed: Client-side only
import { useState, useEffect } from 'react';
const Component = () => {
const [userAgent, setUserAgent] = useState('Detecting...');
useEffect(() => {
setUserAgent(navigator.userAgent);
}, []);
return <div>Browser: {userAgent}</div>;
};
9. Window Properties
// ❌ Error: Window properties during render
const Component = () => {
return <div>Width: {window.innerWidth}</div>; // Server: error, Client: works
};
// ✅ Fixed: After mount
import { useState, useEffect } from 'react';
const Component = () => {
const [width, setWidth] = useState(0);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return <div>Width: {width}</div>;
};
10. Using Placeholders
// ❌ Error: No placeholder
const Component = () => {
const [data, setData] = useState(null);
useEffect(() => {
setData(fetchData());
}, []);
return <div>{data?.name}</div>; // Server: null, Client: actual data
};
// ✅ Fixed: With placeholder
import { useState, useEffect } from 'react';
const Component = () => {
const [data, setData] = useState({ name: 'Loading...' });
useEffect(() => {
fetchData().then(setData);
}, []);
return <div>{data.name}</div>;
};
Quick Fixes Summary
- Use useState + useEffect for dynamic values
- Always provide consistent initial values
- Use dynamic imports for browser-only content
- Check typeof window !== ‘undefined’ before accessing browser APIs
- Provide placeholders for async data
- Match server and client rendering structure
Remember: Server and client must render identical content initially. Use useEffect for client-side updates.
Related Articles
Fix: Hydration failed because the initial UI does not match error in Next.js - Complete Hydration Guide
Complete guide to fix 'Hydration failed because the initial UI does not match' error in Next.js applications. Learn how to handle client-server rendering mismatches and implement proper hydration strategies.
Fix: document is not defined in Next.js Error - Complete Client-Side Guide
Complete guide to fix 'document is not defined' error in Next.js applications. Learn how to handle browser APIs safely in server-side rendering environments.
Fix: cookies() can only be used in Server Components error Next.js
Quick fix for 'cookies() can only be used in Server Components' error in Next.js. Learn how to properly use cookies in Server Components.