Client Side Hydration

Hydration refers to the client-side process during which Vue takes over the static HTML sent by the server and turns it into dynamic DOM that can react to client-side data changes.

In entry-client.js, we are simply mounting the app with this line:

app.mount('#app')

Since the server has already rendered the markup, we obviously do not want to throw that away and re-create all the DOM elements. Instead, we want to "hydrate" the static markup and make it interactive.

Vue provides a createSSRApp method for use in client-side code (in this case, in our entry-client.js) to tell Vue to hydrate the existing static HTML instead of re-creating all the DOM elements.

Hydration Caveats

Vue will assert the client-side generated virtual DOM tree matches the DOM structure rendered from the server. If there is a mismatch, it will bail hydration, discard existing DOM and render from scratch. There will be a warning in the browser console but your site will still work.

The first key way to ensure that SSR is working to ensuring your application state is the same on client and server. Take special care not to depend on APIs specific to the browser (like window width, device capability or localStorage) or server (such as Node built-ins), and take care where the same code will give different results when run in different places (such as when using timezones, timestamps, normalizing URLs or generating random numbers). See Writing Universal Code for more details.

A second key thing to be aware of when using SSR + client hydration is that invalid HTML may be altered by the browser. For example, when you write this in a Vue template:

<table>
  <tr>
    <td>hi</td>
  </tr>
</table>

The browser will automatically inject <tbody> inside <table>, however, the virtual DOM generated by Vue does not contain <tbody>, so it will cause a mismatch. To ensure correct matching, make sure to write valid HTML in your templates.

You might consider using a HTML validator like the W3C Markup Validation Service (opens new window) or HTML-validate (opens new window) to check your templates in development.

© 2013–present Yuxi Evan You
Licensed under the MIT License.
https://v3.vuejs.org/guide/ssr/hydration.html