Hydration failed because the initial UI does not match what was rendered on the server - Next JS fi

––– views

2 min read

If the initial HTML rendered on the server doesn't match the JavaScript code that runs in the browser, it can lead to broken or inconsistent user interfaces and a poor user experience.

This error shows only when working locally, and it might cause issues in production.

You don’t get much information about it in the terminal so where should you start?

Check multiple pages

Start with the home page, and do a hard refresh. If the error is still present, close the page and go to another. Is the error present here? If so, it means it is happening in some shared component, possibly the layout file, the header, or the footer. If it is not present on other pages, then you know it has something to do with the home page.

Start commenting out code

Once you know that the error is happening in a certain part of the codebase it’s time to start commenting out parts of it.

💡
Usually, it’s conditional logic that fails, look for places where you render something conditionally.

Maybe you have a login state, and only render certain parts based on whether or not the user is logged in.

This error occurred because the server was unaware of the client's login state.

TS

{
isLoggedIn
? (<div>content</div>)
: (<></>)
}

My solution was this: .logged-in is a class that toggles the visibility of the target element.

TS

const [navClass, setNavClass] = useState("");
useEffect(() => {
if (isLoggedIn) {
setNavClass("logged-in");
}
}, [isLoggedIn]);
return (
<div className={navClass}></div>
)

Conclusion

These errors occur when you attempt to render something on the server that is only accessible to the client.

If you don't have a specific state, but still encounter an error, you can check if window is defined. This ensures that the rendering is happening in the browser, rather than on the server.

TS

const [shouldShow, setShouldShow] = useState(false)
useEffect(() => {
if (typeof window !== 'undefined') {
setShouldShow(true);
}
}, []);
return shouldShow
? (<div>Content</div>)
: (<></>)

🔥
Here’s a Stackoverflow question that helped me out

To comment please authenticate