Articles

Declarative Shadow DOM: Server-Rendered Web Components

Declarative Shadow DOM lets HTML create a shadow root with a template element, so web components can render on the server and display before JavaScript.

Takina Takina · · 5 min read
HTML markup displayed in a code editor

Declarative Shadow DOM is a way to create a shadow root directly in HTML, using a <template> element with a shadowrootmode attribute, instead of calling attachShadow() from JavaScript. The browser’s HTML parser builds the shadow tree as the page loads, which means a web component’s encapsulated markup and styles can be server-rendered and painted before any script runs.

It closes one of the longest-standing gaps in the web components story: until it arrived, shadow DOM only existed after JavaScript executed, which made components awkward to use with server-side rendering.

The problem it solves

Shadow DOM gives an element a private, encapsulated subtree. Styles inside it do not leak out, and page styles do not leak in. Historically the only way to create one was imperative:

class UserCard extends HTMLElement {
  constructor() {
    super();
    const root = this.attachShadow({ mode: "open" });
    root.innerHTML = `<style>p { color: teal; }</style><p><slot></slot></p>`;
  }
}
customElements.define("user-card", UserCard);

That works in the browser, but it means the server cannot send the final rendered component. The user sees unstyled light-DOM content, or nothing, until the script downloads, parses, and runs. That gap hurts perceived performance and the Core Web Vitals that measure it, and it leaves crawlers and no-JavaScript environments with an incomplete page.

The syntax

Declarative Shadow DOM moves the shadow root into markup. You place a <template> with shadowrootmode as the first child of the host element:

<user-card>
  <template shadowrootmode="open">
    <style>
      p { color: teal; font-weight: 600; }
    </style>
    <p><slot></slot></p>
  </template>
  Ada Lovelace
</user-card>

When the parser reaches that template, it does not create a normal inert template element. Instead it attaches a shadow root to the parent <user-card>, moves the template’s contents into it, and discards the template itself. The text “Ada Lovelace” stays in the light DOM and is projected through the <slot>. The result is identical to what the JavaScript version produces, except it exists the moment the HTML is parsed.

shadowrootmode accepts open or closed, matching the mode option of attachShadow(). A few companion attributes mirror the other options:

  • shadowrootdelegatesfocus — equivalent to delegatesFocus: true, so clicking non-focusable parts of the component focuses its first focusable element.
  • shadowrootclonable — allows the shadow root to be copied when the host is cloned with cloneNode().
  • shadowrootserializable — marks the root as one that serialisation methods may include in their output.

Hydrating a declarative shadow root

A declarative shadow root renders without JavaScript, but most components still need behaviour: event listeners, state, and updates. When the custom element definition eventually loads, the component should adopt the shadow root the parser already built rather than creating a new one.

class UserCard extends HTMLElement {
  constructor() {
    super();
    const internals = this.attachInternals();
    this.root = internals.shadowRoot ?? this.attachShadow({ mode: "open" });
    if (!internals.shadowRoot) {
      this.root.innerHTML = `<style>p { color: teal; }</style><p><slot></slot></p>`;
    }
  }
}

ElementInternals.shadowRoot exposes the existing root, including a closed one, to the element’s own code. If it is present, the component skips rendering and just wires up behaviour. If it is absent, the element was created on the client and renders itself the usual way. This is the same render-on-the-server, attach-on-the-client pattern described in what is hydration, applied at the level of a single element.

Calling attachShadow() on a host that already has a declarative shadow root does not throw, but it empties that root and returns it, discarding the server-rendered content. That is why checking first matters.

Parsing rules and gotchas

innerHTML ignores it. For security and compatibility reasons, setting innerHTML with a shadowrootmode template produces an ordinary inert template, not a shadow root. To parse declarative shadow roots from a string on the client, use setHTMLUnsafe() on an element or Document.parseHTMLUnsafe(). As the names suggest, these do not sanitise their input, so only pass them trusted markup.

One shadow root per host. If a host has multiple shadowrootmode templates, only the first one creates a shadow root. The rest stay as regular template elements.

Serialising back out. The outerHTML and innerHTML getters do not include shadow content. getHTML({ serializableShadowRoots: true }) does, for roots marked serialisable, which is useful for snapshot testing or for building a component’s server output in a JavaScript runtime.

Styles repeat per instance. Each declarative shadow root needs its own <style> block, because a shadow root cannot see the document’s stylesheets. Render fifty cards and you send that CSS fifty times. Compression absorbs much of the duplication on the wire, but the browser still parses each block. A common compromise is to keep server-rendered styles minimal and attach a shared constructed stylesheet through adoptedStyleSheets once the component upgrades.

Declarative vs imperative shadow DOM

Imperative (attachShadow)Declarative (shadowrootmode)
Created byJavaScript at runtimeHTML parser during load
Works without JavaScriptNoYes
Server-side renderingNot possible directlySupported
Content visible on first paintNoYes
StylesCan share via adoptedStyleSheetsInline <style> per instance
Created via innerHTMLYesNo; needs setHTMLUnsafe()

Where it fits

Declarative Shadow DOM matters most for frameworks and design systems that ship web components and want them to render on the server. A server renderer can walk the component tree, emit each component’s shadow template, and stream finished HTML. That makes components compatible with static generation and with partial-hydration approaches such as Astro’s islands architecture, where most of the page never needs client-side JavaScript at all.

For components that are purely presentational, such as a styled badge or a layout wrapper, declarative shadow DOM can remove the need for a custom element definition entirely. The encapsulation is real even if no script ever defines the tag.

The takeaway

Declarative Shadow DOM lets you write <template shadowrootmode="open"> inside an element to give it a shadow root at parse time. The payoff is encapsulated components that render on the server, paint immediately, and work without JavaScript. When the component’s script loads, read the existing root through ElementInternals instead of creating a new one, remember that innerHTML will not parse these templates, and watch for duplicated styles across many instances.

Takina Takina · · 5 min read

Module Federation Explained: Sharing Code at Runtime

Module Federation lets separately built and deployed JavaScript apps load each other's modules at runtime. How hosts, remotes, and shared dependencies work.

#JavaScript #Frontend #Web Development