How It Works Features Pricing Blog
Log In Start Free Trial
Next.js · TypeScript/React

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

Warning: Text content did not match. Server: "April 10, 2026" Client: "April 10, 2026 10:32:15 AM" at span at div at Timestamp (webpack-internal:///./src/components/Timestamp.tsx:6:10) at div at main at Layout (webpack-internal:///./src/components/Layout.tsx:12:5) at App (webpack-internal:///./src/pages/_app.tsx:8:3) Error: Hydration failed because the initial UI does not match what was rendered on the server. at throwOnHydrationMismatch (node_modules/react-dom/cjs/react-dom.development.js:12350:9) at tryToClaimNextHydratableInstance (node_modules/react-dom/cjs/react-dom.development.js:12365:7) at updateHostComponent (node_modules/react-dom/cjs/react-dom.development.js:19211:23) at beginWork (node_modules/react-dom/cjs/react-dom.development.js:21616:14) at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:26557:12)

Here's what each line means:

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.

Before (broken)
export default function Timestamp() {
  const now = new Date().toLocaleString();
  return <span>{now}</span>;
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run the test suite locally to confirm no hydration warnings appear.
  2. Open a pull request with the useEffect-based rendering fix.
  3. Wait for CI checks including the Next.js build to pass.
  4. Have a teammate review and approve the PR.
  5. 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.