Sentry Answers>Next.js>

Fixing Hydration Errors in server-rendered Components

Fixing Hydration Errors in server-rendered Components

Scott Cooper

The Problem

How do I fix the “Hydration failed because the initial UI does not match what was rendered on the server” error with Next.js and React 18?

What are Hydration Errors?

Hydration errors are emitted by react-dom when the server-rendered HTML does not match the HTML that is rendered on the client. This could be the text content of an element, the attributes of an element, or the structure of the DOM. Hydration is the process of React converting pre-rendered HTML into an interactive application by attaching event handlers.

The common causes of hydration errors are well defined by the Next.js docs:

Next.js Hydration Errors

How to fix Hydration Errors?

The first step is to identify the component that is causing the error. This can be challenging if there are many components on the page or if there is no visual change when the page loads. Reproducing the error locally with a react development build can identify the text that was mismatched between the server and client and nextjs displays an error with some of the elements that were mismatched.

Session Replay can be used to help identify the component that is causing the hydration error. See this changelog for how to get started.

Once the component is identified, the next step is to determine why the server and client rendered different HTML.

1. Fix invalid nesting of HTML elements

If you have rendered a div inside a <p> or nested two <p> elements together, react will rerender the entire page and emit a hydration error. This can happen accidentally if you’re using MDX and have an extra line between two paragraphs. Fixing these can be tricky since you’ll need to find the components that are sending invalid HTML and either swap out the elements used or fix the invalid nesting. The diff Sentry is able to provide can help identify the components that are using invalid HTML. See this changelog for how to get started.

Your browser console window can also give you descriptive errors, pointing you to the issue causing the hydration failure. For example:

Click to Copy
Warning: Expected server HTML to contain a matching <h1> in <p>. h1 p main div

You might have a component that includes a <div> tag that is nested inside a <p> tag in another component.

2. Using useEffect to display something different on the client

If you are using typeof window !== 'undefined' in your component to change what the component is rendering based on whether it is server-side or client-side, you may need to use useEffect to change the component after it has been hydrated. Its possible the user will momentairly see the server-rendered HTML before it is changed by the client.

Click to Copy
import { useState, useEffect } from 'react' export default function App() { const [isClient, setIsClient] = useState(false) useEffect(() => { setIsClient(true) }, []) return <div>{isClient ? 'isClient true' : 'isClient false'}</div> }

3. Using suppressHydrationWarning

suppressHydrationWarning is part of the react-dom package and can be used to suppress hydration errors. Dates often cause hydration errors because the server and client exist in different timezones or the relative time has changed since the server rendered the page.

To silence hydration warnings on an element, add suppressHydrationWarning={true}:

Click to Copy
<time datetime="2024-01-01" suppressHydrationWarning>{new Date().toLocaleDateString()}</time>

4. Disable SSR On Specific Components

Next.js allows you to disable SSR on particular components.

You can define a component with SSR disabled as follows:

Click to Copy
const MyComponent = dynamic(() => import('../components/MyComponent'), { ssr: false })

If a component is not pre-rendered on the server, it will not cause a hydration mismatch error.

Filter these errors out

If these errors are caused by 3rd party scripts or browser extensions, you can filter them out by enabling your Sentry project’s Inbound Filters. Learn more about Inbound Filters

Additional Reading

  • Sentry BlogCommon Errors in Next.js and How to Resolve Them
  • Community SeriesDebug Next.js with Sentry
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.