Server-Side DOM Shim

1.1.0 · active · verified Sun Apr 19

server-dom-shim is a utility package designed to provide a minimal shim for standard DOM APIs within server-side rendering (SSR) environments. Its primary purpose is to prevent common errors like `HTMLElement is not defined` when rendering web components or other DOM-dependent JavaScript on the server, without incurring the overhead of a full browser emulation library like JSDOM. The package is currently at version 1.1.0 and has seen a consistent, albeit not rapid, release cadence with updates in late 2025 and mid-2024. A key differentiator is its use of Node.js conditional exports, which intelligently exports `@lit-labs/ssr-dom-shim` in Node.js environments while deferring to native DOM APIs in browser contexts. This approach allows developers to write universal codebases that seamlessly adapt to different execution environments, making it suitable for modern SSR frameworks and libraries that leverage web standards. It focuses on providing necessary global definitions rather than full interactive DOM capabilities.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and verify server-side DOM APIs like `HTMLElement` and `customElements` are available, preventing common SSR errors without full browser emulation.

import { HTMLElement, customElements, Event, CustomEvent, Element } from 'server-dom-shim';

// Verify that HTMLElement is defined in the server environment
console.log('HTMLElement is defined:', typeof HTMLElement !== 'undefined');

// Example: Define a simple custom element (though it won't render visually in Node.js)
class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    // In a real SSR scenario, this would be part of a component's lifecycle
    // and prevent errors when a framework tries to instantiate it.
    console.log('MyCustomElement instance created (server-side shim)');
  }

  connectedCallback() {
    console.log('MyCustomElement connectedCallback (server-side shim)');
  }
}

// Define the custom element if not already defined (important for re-runs in dev)
if (!customElements.get('my-custom-element')) {
  customElements.define('my-custom-element', MyCustomElement);
  console.log('Custom element "my-custom-element" defined (server-side shim)');
}

// Example: Create an event instance
const myEvent = new CustomEvent('my-custom-event', { detail: { data: 'hello' } });
console.log(`Created event: ${myEvent.type} with detail:`, myEvent.detail);

// This shim allows libraries that expect a DOM environment to run without errors during SSR.

view raw JSON →