How To Hydrate A Server-Side Rendered Web Component
An in-depth guide to lazy loading Web Components
In part 1 of this series I explain you how to server-side render a Web Component.
Hydration
Declarative Shadow DOM enables us to attach a Shadow root to a Custom Element and fully render it without any JavaScript. This is a huge step for web components since they can now be rendered on the server. But there is a slight problem though.
Our component doesn’t do anything, it’s not interactive.
Even worse, it’s not even a Custom Element!
If you check the server-side rendered components from my previous article in the browser’s dev tools you will notice they all have a Shadow root attached to it. But when you check the CustomElementsRegistry
to find the constructor
of the element:
const el = await customElements.get('my-element');
console.log(el) // undefined 😱
you will notice that it hasn’t even been registered as a Custom Element.
This is an important fact to realise about Declarative Shadow DOM: it only attaches a Shadow root to an element.
In other words, it only takes care of rendering the HTML of the component and nothing else. The benefit of this approach is that it…