Lit SSR server usage
In order to render custom elements in Node, they must first be defined and registered with the global
customElements API, which is a browser-only feature. As such, when Lit runs in Node, it automatically uses a set of minimal DOM APIs necessary to render Lit on the server, and defines the
customElements global. (For a list of emulated APIs, see DOM emulation.)
Lit SSR provides two different ways of rendering custom elements server-side: rendering in the global scope or via VM modules. VM modules utilizes Node's
vm.Module API, which enables running code within V8 Virtual Machine contexts. The two methods differ primarily in how global state, such as the custom elements registry, are shared.
When rendering in the global scope, a single shared
customElements registry will be defined and shared across all render requests, along with any other global state that your component code might set.
Rendering with VM modules allows each render request to have its own context with a separate global from the main Node process. The
customElements registry will only be installed within that context, and other global state will also be isolated to that context. VM modules are an experimental Node feature.
Global ScopePermalink to “Global Scope”
render() method takes a renderable value, usually a Lit template result, and returns an iterable of strings that can be streamed or concatenated to a string for a response.
VM ModulePermalink to “VM Module”
Lit also provide a way to load application code into, and render from, a separate VM context with its own global object.
Note: Using this feature requires Node 14+ and passing the
--experimental-vm-modules flag to Node because of its use of experimental VM modules for creating a module-compatible VM context.