🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Components & Islands••By Komal Nakrani

Astro Web Components: Custom Elements Without a Framework

Use Astro web components: define custom elements in a script tag, pass data with attributes, use Shadow DOM and declarative shadow roots, and add Lit or libraries.

#Astro#Web Components#Custom Elements#Shadow DOM#Islands

Astro web components are standard custom elements that you define in a <script> tag inside an .astro component, then use like any HTML tag. Astro renders the surrounding HTML at build time, bundles the script once per page, and the browser upgrades the element when the script runs. You get interactivity with no UI framework, no client:* directive and no framework runtime, which makes web components one of the lightest ways to add behavior to an Astro site.

This guide shows the pattern Astro recommends, how to pass data in, when to use Shadow DOM, and how to work with Lit or third-party component libraries.

Key Takeaways

  • Define a custom element with customElements.define() in a component’s <script>; Astro bundles and deduplicates it.
  • Pass server data to the element with data-* attributes, read through this.dataset.
  • Render the real content as HTML in the Astro template so it works before JavaScript loads.
  • client:* directives do not apply to custom elements. The script loads with the page; use IntersectionObserver for lazy behavior.
  • Use declarative Shadow DOM (<template shadowrootmode="open">) when you need style encapsulation without a flash of unstyled content.

Why web components fit Astro

Astro ships zero JavaScript by default. When a piece of UI needs behavior, you have two main choices: a framework island (React, Svelte, Vue) with a client:* directive, or a <script> that enhances HTML you already rendered. The island or script guide compares the two in depth.

Web components are the structured version of the script approach. Instead of querying the document for elements and attaching listeners, you define a class that the browser runs for every instance of a tag, at any time it appears. Each instance manages its own state, cleanup is built in through disconnectedCallback(), and the code is plain browser APIs with no dependencies.

They work well for disclosure widgets, tabs, carousels, copy buttons, theme toggles, counters and anything else where the HTML is mostly static and the behavior is small.

Your first Astro web component

Here is a “copy to clipboard” button. The HTML is rendered by Astro, and the custom element adds the behavior:

---
// src/components/CopyButton.astro
interface Props { text: string; label?: string }
const { text, label = 'Copy' } = Astro.props;
---
<copy-button data-text={text}>
  <button type="button">{label}</button>
</copy-button>

<script>
  class CopyButton extends HTMLElement {
    connectedCallback() {
      const button = this.querySelector('button');
      const text = this.dataset.text ?? '';
      button?.addEventListener('click', async () => {
        await navigator.clipboard.writeText(text);
        button.textContent = 'Copied';
        setTimeout(() => (button.textContent = 'Copy'), 2000);
      });
    }
  }

  customElements.define('copy-button', CopyButton);
</script>

Use it as many times as you like:

---
// src/pages/install.astro
import CopyButton from '../components/CopyButton.astro';
---
<p>Install the CLI:</p>
<code>npm create astro@latest</code>
<CopyButton text="npm create astro@latest" />
<CopyButton text="npx astro add mdx" label="Copy MDX command" />

Even with several instances, Astro bundles the <script> once, processes it with TypeScript, and loads it as a module. The browser calls connectedCallback() for each <copy-button> element, so each instance wires up its own button.

Custom element names must contain a hyphen. That is how the browser (and Astro’s compiler) knows the tag is a custom element rather than a component import.

Passing data from Astro to the element

Astro components run on the server, and the script runs in the browser, so you cannot pass JavaScript variables directly between them. Use attributes:

---
// src/components/Countdown.astro
interface Props { until: Date }
const { until } = Astro.props;
---
<count-down data-until={until.toISOString()}>
  <span>Launch on {until.toLocaleDateString('en-US', { dateStyle: 'long' })}</span>
</count-down>

<script>
  class CountDown extends HTMLElement {
    #timer?: number;

    connectedCallback() {
      const until = new Date(this.dataset.until!).getTime();
      const span = this.querySelector('span')!;
      const tick = () => {
        const ms = Math.max(0, until - Date.now());
        const days = Math.floor(ms / 86_400_000);
        const hours = Math.floor((ms % 86_400_000) / 3_600_000);
        span.textContent = `${days} days, ${hours} hours to go`;
      };
      tick();
      this.#timer = window.setInterval(tick, 60_000);
    }

    disconnectedCallback() {
      clearInterval(this.#timer);
    }
  }

  customElements.define('count-down', CountDown);
</script>

For more complex data, serialize JSON into an attribute with data-config={JSON.stringify(config)} and parse it in connectedCallback(). Keep it small; large data belongs in the HTML itself.

Notice the progressive enhancement: the server renders a useful sentence (“Launch on November 20, 2026”), and the script upgrades it to a live countdown. If JavaScript fails or loads late, the page still says something meaningful.

Loading behavior: no client directives

client:load, client:visible and the other directives only apply to framework components. A custom element is plain HTML, and its <script> is bundled with the page, so it loads like any other Astro script: as a deferred module.

If a component should only do work when it scrolls into view, do it in the element:

// inside a custom element class
connectedCallback() {
  const io = new IntersectionObserver((entries) => {
    if (entries.some((e) => e.isIntersecting)) {
      io.disconnect();
      this.start();
    }
  });
  io.observe(this);
}

For heavy dependencies, import them dynamically inside that callback (const { Chart } = await import('chart.js')) so the library downloads only when needed. Vite splits dynamic imports into separate chunks automatically.

Shadow DOM: when you need encapsulation

The examples so far use the light DOM: children are regular HTML, styled by your site’s CSS and Astro’s scoped styles. That is usually what you want on a content site.

Shadow DOM isolates an element’s markup and styles from the rest of the page. It is useful for embeddable widgets that must not inherit or leak styles. The catch is that a shadow root attached in JavaScript renders nothing until the script runs, which can cause a flash or a layout shift.

Declarative Shadow DOM solves that by putting the shadow root in the HTML, so Astro renders it at build time:

---
// src/components/Badge.astro
interface Props { tone?: 'info' | 'success' }
const { tone = 'info' } = Astro.props;
---
<status-badge data-tone={tone}>
  <template shadowrootmode="open">
    <style>
      :host { display: inline-block; }
      span { padding: 0.125rem 0.5rem; border-radius: 999px; font: 600 0.75rem/1.5 system-ui; }
      :host([data-tone='info']) span { background: #e0ecff; color: #1d3f8a; }
      :host([data-tone='success']) span { background: #dcf5e3; color: #17603a; }
    </style>
    <span><slot></slot></span>
  </template>
  New
</status-badge>

The browser attaches the shadow root while parsing the HTML, with no JavaScript at all. Add a script only if the element needs behavior. Astro’s scoped <style> tags do not reach inside a shadow root, so styles for shadow content must live inside the template, as above.

Using Lit

Lit is a small library for building web components with reactive properties and templates. Astro no longer ships an official Lit integration, so Lit components are not server-rendered by Astro. You can still use them as client-side custom elements:

npm install lit
// src/scripts/like-button.ts
import { LitElement, html, css } from 'lit';

class LikeButton extends LitElement {
  static properties = { count: { type: Number } };
  static styles = css`button { font: inherit; }`;
  declare count: number;

  constructor() {
    super();
    this.count = 0;
  }

  render() {
    return html`<button @click=${() => this.count++}>Likes: ${this.count}</button>`;
  }
}

customElements.define('like-button', LikeButton);
---
// src/pages/post.astro
---
<like-button count="3"></like-button>
<script>
  import '../scripts/like-button.ts';
</script>

Because there is no server rendering, the element is empty until the script runs. Give it a placeholder size in CSS (for example like-button { display: inline-block; min-width: 6rem; min-height: 2.5rem; }) to avoid layout shift. If a component must render on the server, an Astro component with a small enhancing script is usually the better choice.

Third-party web component libraries

Libraries built as web components work in Astro the same way: install the package, import it in a <script>, and use the tags in your templates.

---
// src/components/Gallery.astro
---
<image-slider>
  <!-- slides rendered by Astro -->
</image-slider>
<script>
  import 'some-web-component-library/image-slider.js';
</script>

Check each library’s docs for its CSS file and any assets it needs from public/. Because these libraries define elements globally, import each one once, ideally from the component that uses it, so Astro only bundles it on pages that need it.

TypeScript tips

  • this.dataset values are always string | undefined. Parse numbers and dates explicitly.
  • querySelector<HTMLButtonElement>('button') gives you a typed element.
  • If you want typed document.querySelector('copy-button'), declare the element in a global interface:
// src/env.d.ts
declare global {
  interface HTMLElementTagNameMap {
    'copy-button': HTMLElement & { dataset: { text?: string } };
  }
}
export {};

When to choose a web component

Use a web component when Use a framework island when
The HTML is static and the behavior is small The UI re-renders often from state
You want no framework runtime You already use React, Svelte or Vue on the site
The widget repeats many times on a page You need complex state shared across components
You want it to work in any framework later You rely on a component library for that framework

Most marketing and content sites need only a handful of small behaviors, and web components cover them with very little code. The client directive guide covers the island side, and the copy code button tutorial is a full worked example.

Every Komal theme ships static Astro components with small scripts rather than framework islands, so the patterns above fit straight into a theme. See MDN’s custom elements guide and Astro’s client-side scripts guide for the full API.

FAQ

Can I use web components in Astro?

Yes. Define a custom element with customElements.define() inside a <script> tag in an .astro component, then use the tag in your templates. Astro renders the HTML, bundles the script once per page, and the browser upgrades every instance when the script runs.

Do client directives work with web components in Astro?

No. Directives such as client:load and client:visible only apply to framework components like React or Svelte. A custom element’s script loads with the page; to delay work until it is visible, use an IntersectionObserver inside the element.

How do I pass props to a web component in Astro?

Pass values as attributes, usually data-* attributes, from the Astro template, then read them in the element with this.dataset or getAttribute(). For structured data, serialize it with JSON.stringify() into an attribute and parse it in connectedCallback().

Does Astro server-render web components?

Astro renders whatever HTML you write inside and around the custom element tag, including declarative shadow DOM templates. It does not run the element’s JavaScript class on the server, so content generated only by the class appears after the script loads.

Is there an Astro integration for Lit?

Not an official one anymore. You can still use Lit components as client-side custom elements by importing them in a <script> tag. They render in the browser, so reserve space for them with CSS to prevent layout shift.