Lit SSR client usage
How to re-apply that reactivity client-side depends on whether you are rendering standalone Lit templates or utilizing Lit components.
Standalone Lit TemplatesPermalink to “Standalone Lit Templates”
"Hydration" for Lit templates is the process of having Lit re-associate the expressions of Lit templates with the nodes they should update in the DOM as well as adding event listeners. In order to hydrate Lit templates, the
hydrate() method is provided in the
@lit-labs/ssr-client package. Before you update a server-rendered container using
render(), you must first call
hydrate() on that container using the same template and data that was used to render on the server:
Lit componentsPermalink to “Lit components”
To re-apply reactivity to Lit components, custom element definitions need to be loaded for them to upgrade, enabling their lifecycle callbacks, and the templates in the components' shadow roots needs to be hydrated.
Upgrading can be achieved simply by loading the component module that registers the custom element. This can be done by loading a bundle of all the component definitions for a page, or may be done based on more sophisticated heuristics where only a subset of definitions are loaded as needed. To ensure templates in
LitElement shadow roots are hydrated, load the
@lit-labs/ssr-client/lit-element-hydrate-support.js module which installs support for
LitElement to automatically hydrate itself when it detects it was server-rendered with declarative shadow DOM. This module must be loaded before the
lit module is loaded (including any component modules that import
lit) to ensure hydration support is properly installed.
When Lit components are server rendered, their shadow root contents are emitted inside a
template-shadowroot polyfill is described below.
Loading Permalink to “Loading @lit-labs/ssr-client/lit-element-hydrate-support.js”
This needs to be loaded before any component modules and the
If you are bundling your code, make sure the
@lit-labs/ssr-client/lit-element-hydrate-support.js is imported first:
Using the Permalink to “Using the template-shadowroot polyfill”
The HTML snippet below includes an optional strategy to hide the body until the polyfill is loaded to prevent layout shifts.
Combined examplePermalink to “Combined example”
This example shows a strategy that combines both the
@lit-labs/ssr-client/lit-element-hydrate-support.js and the
template-shadowroot polyfill loading and serves a page with a SSRed component to hydrate client-side.