Client Side Hydrationedit
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.
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.
In development mode, 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. In production mode, this assertion is disabled for maximum performance.
One thing to be aware of when using SSR + client hydration is some special HTML structures that 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
<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.
Handling Hydration Errors
If you do receive hydration errors (as seen in console: “Vuejs Error - The client-side rendered virtual DOM tree is not matching server-rendered content”), you can try following these steps:
- Show DevTools in Chrome (F12)
- Load the page that causes “the client-side rendered virtual DOM tree…” warning.
- Scroll to the warning in DevTools console.
- Click at the source location hyperlink of the warning in vue.runtime.esm.js.
- Set a breakpoint there (left-clicking at line number in the source code browser).
- Make the same warning appear again. Usually by reloading the page. If there are many warnings, you can check the message by moving a mouse over
- When you have found your message and stopped on a breakpoint, look at the call stack. Click one frame down to call to “patch” to open its source. Hover mouse over hydrate function call 4 lines above the execution line in patch. Hyperlink to the source of hydrate would open.
- In the hydrate function, move about 15 lines from the start and set a breakpoint where false is returned after
false. Set the breakpoint there and remove all other breakpoints.
- Make the same warning happen again. Now, when breakpoint is hit, execution should stop in the hydrate function. Switch to DevTools console and evaluate
elmseems to be a server-rendered DOM element while
vnodeis a virtual DOM node.
Elmis printed as HTML so you can figure out where the error happened.