Fix Hydration Error: Text content does not match server-rendered HTML in Next.js
This error occurs when the HTML rendered on the server differs from what React generates on the client during hydration. Common causes include using Date.now(), browser-only APIs, or invalid HTML nesting. Fix it by ensuring deterministic rendering or using useEffect for client-only content and suppressHydrationWarning sparingly.
Reading the Stack Trace
Here's what each line means:
- Server: "April 10, 2026" Client: "April 10, 2026 10:32:15 AM": The server rendered a date string without time, but the client rendered it with time, causing a text mismatch.
- at Timestamp (webpack-internal:///./src/components/Timestamp.tsx:6:10): The Timestamp component at line 6 produces different output on server vs client due to time-dependent rendering.
- at throwOnHydrationMismatch: React detected the mismatch and threw an error instead of silently recovering, which is the default behavior in React 18.
Common Causes
1. Using Date.now() during render
Calling new Date() during render produces different output on the server and client because they execute at different times.
export default function Timestamp() {
const now = new Date().toLocaleString();
return <span>{now}</span>;
}
2. Invalid HTML nesting
Nesting block elements like div inside inline elements like p creates different DOM trees in the server HTML vs client parsing.
export default function Card({ children }) {
return (
<p>
<div className="card">{children}</div>
</p>
);
}
3. Checking window or localStorage during render
Reading browser-only values like localStorage during render yields different results on server (where they don't exist) vs client.
export default function ThemeToggle() {
const theme = typeof window !== 'undefined'
? localStorage.getItem('theme') || 'light'
: 'light';
return <button>{theme === 'dark' ? 'Light Mode' : 'Dark Mode'}</button>;
}
The Fix
Defer time-dependent rendering to useEffect, which only runs on the client after hydration completes. The server and initial client render both show the same loading state, preventing any mismatch.
export default function Timestamp() {
const now = new Date().toLocaleString();
return <span>{now}</span>;
}
import { useEffect, useState } from 'react';
export default function Timestamp() {
const [now, setNow] = useState<string | null>(null);
useEffect(() => {
setNow(new Date().toLocaleString());
}, []);
if (!now) return <span>Loading...</span>;
return <span>{now}</span>;
}
Testing the Fix
import { render, screen, act } from '@testing-library/react';
import Timestamp from './Timestamp';
describe('Timestamp', () => {
it('shows loading state initially', () => {
render(<Timestamp />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
it('renders the current time after mount', async () => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2026-01-15T10:30:00'));
render(<Timestamp />);
await act(async () => {
jest.runAllTimers();
});
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
expect(screen.getByText(/2026/)).toBeInTheDocument();
jest.useRealTimers();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/hydration-mismatch-timestamp,git add src/components/Timestamp.tsx src/components/__tests__/Timestamp.test.tsx,git commit -m "fix: defer time-dependent rendering to useEffect to prevent hydration mismatch",git push origin fix/hydration-mismatch-timestamp
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm no hydration warnings appear.
- Open a pull request with the useEffect-based rendering fix.
- Wait for CI checks including the Next.js build to pass.
- Have a teammate review and approve the PR.
- Merge to main and verify no hydration errors appear in the browser console in staging.
Frequently Asked Questions
BugStack compares the server-rendered output with the client-side render, verifies they match, and runs the full test suite to confirm no hydration warnings remain.
All fixes are delivered as pull requests. Your CI pipeline catches hydration mismatches during the build step, and your team reviews before merging.
Yes, but only for intentional mismatches like timestamps. It silences the warning but does not fix the underlying issue. Use it sparingly and only on leaf text nodes.
The loading state renders on the server, so search engines see that text. If the dynamic content is important for SEO, pass it via server-side props instead.