#Vue

#Nuxt

Understanding SSR Hydration Errors (with Nuxt.js)

2 years ago

68

If you're new to Server Side Rendering (SSR), the Hydration Errors can be difficult to understand at first. Here are some Tips.

What are Hydration Errors?

Hydration Errors happen, when the HTML-DOM rendered by the Server, doesn't match with the HTML-DOM created by the Client. There are two main Causes where this might happen:

  • different Data on Server and Client Side
  • invalid HTML


Different Data

It might not be always that obvious, but a simple Example to get the Idea is, when you try to include the current Timestamp in Milliseconds at Render-Time:


<template>
    <div>
        {{timems}}
    </div>
</template>
<script setup>
    const timems=ref(new Date().getMilliseconds())
</script>

Of course the Server renders the DOM first, and then on the Client. So the timems differs on the Client. The Solution is simple:

Use State Management and set the Variable only once during Server rendering or use <ClientOnly> Directive to only render the Variable on the Client.

Similar things might also happen when you use other host-dependant Variable and Functions like:

  • window
  • document
  • navigator
  • process
  • Random
  • location


Invalid HTML

This can be a bit tricky sometimes. As a Developer, you're normally used to write HTML in a way that it just runs in the Browser (or at least all Browsers you need to support). But Browsers also understand invalid HTML, which leads to developers getting used to writing invalid HTML.

So here are some examples of code that you might not be used to write correct:


<!-- Nested anchor tags -->
<a>foo<a>bar</a></a>

<!-- <div> in <p> -->
<p><div>foo</div></p>

<!-- <p> in <ul> -->
<ul><p>foo</p></ul>

<!-- v-if on root level -->
<template>
   <div v-if="true">foo</div>
</template>

<!-- v-html on p -->
<p v-html="text"></p>

<!-- <table> without <tbody> -->
<table>
   <tr>
      <td>foo</td>
   </tr>
</table>

Also look for cases where you have a trailing Whitespace or Newline-Character in a text, as some Clients might omit them, while others won't.