Lit SSR server usage

This package is part of the Lit Labs family of experimental packages. See the Lit Labs page for guidance on using Labs software in production.

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.

GlobalVM Module
Pros:
  • Easy to use. Can import component modules directly and call render() with templates.
Cons:
  • Custom elements are registered in a shared registry across different render requests.
Pros:
  • Isolates contexts across different render requests.
Cons:
  • Less intuitive usage. Need to write and specify a module file with a function to call.
  • Slower due the module graph needing to be re-evaluated per request.

The 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.

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.