Lit
Lit elements, rendered on the server into a declarative shadow root with
@lit-labs/ssr and adopted in place in the browser with
@lit-labs/ssr-client. The droplet below is a Lit element served by the demo
server: its load sets the start, Lit renders it to HTML with its styles in
the shadow root, and the button works once the bundle hydrates it.
counter · Lit
Server HTML: the button works once Lit hydrates.
import { css, html } from "lit";import { DropletElement } from "@dropletsjs/renderer-lit/element";import type { DropletProps } from "./$types";
export const ssr = true;export const hydrate = true;
export default class Counter extends DropletElement<DropletProps> { static override properties = { added: { state: true }, hydrated: { state: true } };
// The shadow root keeps the page's stylesheets out, src/app.css included; // custom properties inherit into it, so the card uses its --demo-* colors. static override styles = css` section { max-width: 36rem; padding: 1rem 1.25rem; border: 1px solid var(--demo-line); border-radius: var(--demo-radius); background: var(--demo-surface); } p { margin: 0; } p + p { margin-top: 0.75rem; } .row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; } .tag { padding: 0.125rem 0.5rem; border: 1px solid var(--demo-line); border-radius: 999px; background: var(--demo-sunken); color: var(--demo-muted); font: 500 0.75rem/1.4 var(--demo-mono); } output { font-size: 1.25rem; font-weight: 600; } button { min-height: 2.25rem; padding: 0.375rem 0.875rem; border: 0; border-radius: var(--djs-radius-sm, 4px); background: var(--demo-accent); color: var(--demo-on-accent); font: inherit; font-size: 0.875rem; font-weight: 600; cursor: pointer; } button:focus-visible { outline: 2px solid var(--djs-focus, var(--demo-accent)); outline-offset: 2px; } .muted { color: var(--demo-muted); font-size: 0.875rem; } `;
declare added: number; declare hydrated: boolean;
constructor() { super(); // Set here, not as class fields: a field would hide the property Lit defines. this.added = 0; this.hydrated = false; }
// Runs in the browser only, once the server's shadow root is adopted. The // change waits for that update to finish: Lit warns of one made during it. override firstUpdated() { void this.updateComplete.then(() => (this.hydrated = true)); }
override render() { // What the server load returned. Always the value: the renderer waits for it. const { framework, start } = this.data; return html` <section data-hydrated=${String(this.hydrated)}> <p class="row"><span class="tag">counter · ${framework}</span></p> <p class="row"> <output aria-live="polite">${start + this.added}</output> <button type="button" @click=${() => (this.added += 1)}>Add one</button> </p> <p class="muted"> ${this.hydrated ? `Hydrated: ${framework} runs the button in this tab.` : `Server HTML: the button works once ${framework} hydrates.`} </p> </section> `; }}import type { LoadEvent } from "./$types";
/** * Runs on the server only. The count starts where the server says, and the * name of the framework comes with it. The same for everyone, so a browser * (or a cache in front) may keep it for five minutes. */export const load = ({ setHeaders }: LoadEvent) => { setHeaders({ "cache-control": "public, max-age=300" }); return { framework: "Lit", start: 3 };};Add it to a project
Section titled “Add it to a project”npx djs add counter --framework litIt installs what the project lacks and adds lit() to renderers invite.config.ts, asking first, then writes src/droplets/counter/+droplet.lit.ts.
Every step it takes is in Add a renderer. What it installs for Lit:
| Package | Installed as |
|---|---|
@dropletsjs/renderer-lit | a dev dependency, at exactly the version of @dropletsjs/droplets you have |
lit@^3.3.0 | a dependency |
By hand:
npm install litnpm install -D @dropletsjs/renderer-litthen import { lit } from "@dropletsjs/renderer-lit" and lit() in renderers.
The files
Section titled “The files”| File | What it is |
|---|---|
+droplet.lit.ts, +droplet.lit.js |
The component: the file default-exports a LitElement class. Its flags are named exports. |
+error.lit.ts, +error.lit.js |
The error page, optional, a LitElement class too. |
+droplet.ts, +droplet.server.ts |
The loads, as for every framework: Writing droplets. |
.lit.ts is Lit’s alone: any +droplet.lit.ts is a Lit droplet, and a plain
+droplet.ts next to it stays the universal load. The packages lit,
lit-html, lit-element, @lit/reactive-element, @lit-labs/ssr-client
and @dropletsjs/renderer-lit are Lit’s own: a droplet of another framework
that reaches them, through any chain of imports, fails the build.
import { css, html } from "lit";import { DropletElement } from "@dropletsjs/renderer-lit/element";import type { DropletProps } from "./$types";
export const hydrate = true;
export default class Hello extends DropletElement<DropletProps> { // Added to the ones DropletElement declares: Lit merges them. static override properties = { clicks: { state: true } }; static override styles = css`h1 { font-family: system-ui, sans-serif; }`; declare clicks: number;
constructor() { super(); this.clicks = 0; }
override render() { return html` <h1>${this.data.greeting}</h1> <button @click=${() => (this.clicks += 1)}>${this.clicks}</button> <slot></slot> `; }}import { css, html } from "lit";import { DropletErrorElement } from "@dropletsjs/renderer-lit/element";import type { DropletErrorProps } from "./$types";
export default class HelloError extends DropletErrorElement<DropletErrorProps> { static override styles = css`.oops { color: crimson; }`; override render() { return html`<p class="oops">${this.error.message}</p><slot></slot>`; }}What it supports
Section titled “What it supports”| Server rendering | yes, with @lit-labs/ssr: ssr = true, the default; ssr = false renders it in the browser only |
hydrate |
true (the default), "visible", "interactive", false |
| Prerendering | yes: prerender = true with entries |
| Forms | enhance() of @dropletsjs/renderer-lit/form, a Lit directive |
| Runtimes | Node, Bun, Deno and Cloudflare Workers render alike |
Importing another framework, even through a neutral file, stops
vite build, and the vite dev server reports it too:
droplets: a lit droplet imports vue code: src/droplets/counter/+droplet.lit.ts -> vue/dist/vue.runtime.esm-bundler.js. A droplet uses its own framework's modules and neutral code only.Flags are read from +droplet.lit.ts alone. A flag that is not a literal
(export const hydrate = isMobile) is ignored, with a warning under
vite dev and vite build; a flag exported from +droplet.ts or
+droplet.server.ts is ignored.
One mistake is caught when the droplet renders, not at build: a default
export that is no LitElement class answers 500, with
counter: the droplet component must default-export a LitElement class (…); the renderer defines it
in the server’s log.
Specifics
Section titled “Specifics”-
The element and its name. The renderer defines the class itself, as
<element>-<droplet id>(<element>-<droplet id>--errorfor the error page),<element>being the droplets server’s element name. The demo’s is<djs-demo-counter-lit>, inside<djs-demo>. Don’t callcustomElements.define(or use@customElement) in a droplet file;lit({ prefix })changes the prefix: a lowercase letter, then lowercase letters, digits and hyphens. -
Properties. The element gets
dataandform(orerror) as properties, never attributes, andactionUrl(name?), the URL of a form action, the same string on the server and in the browser.DropletElementandDropletErrorElementof@dropletsjs/renderer-lit/elementdeclare them; a plainLitElementdeclares them itself withattribute: false. Declare fields, never initialize them as class fields (data = …): a class field hides the property Lit defines. Give state its initial value in the constructor, as the demo does. -
Data is always a value. Lit has no suspense: when a droplet mounts in the browser, the renderer waits for
databefore it renders, and a rejection renders the error page instead. -
Declarative shadow DOM.
@lit-labs/ssrprints the element with a declarative shadow root (<template shadowrootmode="open">), itsstatic stylesinside, and thedefer-hydrationattribute. In the browser, the renderer’s client setup loadslit-element-hydrate-supportonce per page, before any droplet defines its class;hydratethen adopts the server’s nodes in place, without rendering them again.firstUpdatedruns then, which is where the demo setshydrated. -
Markup inserted with
innerHTML. The HTML parser attaches a declarative shadow root only while it parses a page: a fragment a host inserts withinnerHTML, like the ones the droplet element fetches itself after a form action or an edit in dev, keeps it as an inert<template>.hydrateattaches those first, innermost first, so such a fragment hydrates like one in the page. Until its script runs, it shows nothing of its shadow content. -
Styles live in the shadow root. Write them as
static styles. The droplet’sstyle.css, a CSS file a component imports, the sharedcss.pathstylesheet (Tailwind included) and the host’s styles reach the light DOM only: the element itself and the host’s children. They never reach inside the shadow root, so the droplet’s scoped prefix has nothing to scope there. Inherited properties (font,color) and CSS custom properties flow in: theme a Lit droplet with custom properties set insrc/app.cssor by the host. The demo’s counter draws its card with the--demo-*properties apps/demo’ssrc/app.csssets on<djs-demo>. -
Children: the host’s children are the element’s light-DOM child; a
<slot>in the template shows them. -
One registry per page.
customElementsholds one class per name, forever. Two droplets servers on one page keep apart by their element names, which are distinct already. An edited module undervite devdefines its new class under<tag>--v2,--v3, …; when the markup’s tag is held by another class, the droplet mounts afresh, with a warning in the console, rather than adopting nodes it did not render. -
Forms in the shadow root post natively, to
this.actionUrl("name"). To post them by fetch and update in place,enhance()isenhanceDropletFormas a Lit directive, released when the form leaves the page:import { enhance } from "@dropletsjs/renderer-lit/form";import type { DropletActions } from "./$types";html`<form method="post" action=${this.actionUrl()} ${enhance<DropletActions>()}>…</form>`; -
hydrate = "interactive"works through the shadow root: the events that start it (pointerdown,focusin,keydown,click) are composed, so they reach the droplet element from inside, and a click replayed after hydration reaches the element that was clicked, not the shadow host. -
Cloudflare Workers. Lit’s default builds expect a DOM and fail on Workers as they load. The renderer bundles Lit into the server build and swaps in Lit’s own server build (
lit-html/node/…,@lit/reactive-element/node/…), which runs on Lit’s DOM shim with no Node API. apps/demo, which serves the droplet on this page, builds for Workers too, and its tests render this counter underwrangler dev. -
Hot updates: Lit has no HMR of its own. Under
vite devwithdev.strategy: "hmr"(the default), an edit to a component remounts the droplet in place, under a new tag, without a page reload, and its state starts over. An edit to the load brings newdatato the live element. See Hot updates.
The renderer runs rendererConformance() like every other, with
css: false: a component’s styles live in its shadow root, so the client
build extracts none. The kit renders the server side in a worker thread,
where Lit’s DOM shim finds no happy-dom and defines its elements apart from
the browser bundles’; its DOM checks look into shadow roots and through
slots, and its HTML checks ignore Lit’s <!--lit-part--> comments. The
renderer’s own vitest suite covers the server side further, a Workers build
included, and Playwright checks in real Chromium what only a browser shows:
the parser attaching declarative shadow roots, styles inside the shadow
root, and the replayed click inside it.
The example
Section titled “The example”examples/frameworks/lit
has one droplet per mode (client, ssr-hydrate with an error page,
ssr-nohydrate) and a fourth, guestbook, with a form action posted from
inside a shadow root, natively and through enhance(). From a clone of the
repository:
pnpm install && pnpm buildpnpm --filter @dropletsjs/example-lit dev # http://localhost:5173: the devtools pagepnpm --filter @dropletsjs/example-lit build then start serves it on
http://localhost:8000; /droplets/ssr-hydrate?who=Ana is the fragment a
host pastes into its page.