Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 28 ยท HTMX and Alpine Together

Using HTMX and Alpine.js Together

Combine HTMX and Alpine.js safely: decide who owns which state, use Alpine inside swapped HTML, trigger requests with $dispatch and build server-filled modals.

You now know both libraries on their own. HTMX moves HTML between server and page. Alpine.js keeps small bits of state next to the markup. Used together, they let you build screens that feel like a single-page app while the server still renders every piece of HTML.

The combination only feels smooth when you keep the two jobs apart. This lesson gives you a simple rule for that, then shows the four patterns you will use again and again: Alpine inside swapped content, state that survives swaps, Alpine events that start HTMX requests, and a modal filled by the server. If you need a refresher, review Reactive State with x-data and Targets and Swap Strategies first.

Who owns what

Every piece of information on a page has exactly one owner. Decide the owner before you write the attribute.

Server state belongs to HTMX

Database facts Todos, products, search results.
Rules Permissions and validation live on the server.

The server sends fresh HTML whenever these change.

1 / 3

If you catch yourself copying a database value into Alpine state and editing it there, stop. Let the server own it: send the edit with HTMX, then swap in the new HTML. If you catch yourself sending a request just to remember that a menu is open, stop as well. That belongs to Alpine.

Alpine inside swapped fragments

Alpine watches the page with a MutationObserver. Whenever new elements appear, including elements inserted by HTMX, it looks for x-data and starts the component. You do not need to call anything. A fragment from the server can carry its own Alpine behavior, exactly like a normal page.

A swapped fragment brings its own Alpine state

Load two or three cards and use their buttons. Each card has its own qty, because each fragment carries its own x-data scope. The server never hears about the quantity or the open panel, which is correct: those are view state.

When you do need htmx:load

Alpine needs no help, but other JavaScript does. A date picker or a chart library has to be started on new elements. HTMX fires htmx:load for every element it adds, and htmx.onLoad is a shortcut for that event:

JavaScript
htmx.onLoad((content) => {
  content.querySelectorAll("[data-chart]").forEach((el) => drawChart(el));
});

The callback runs once for the initial page and again for each swapped fragment. Prefer Alpine's x-init for your own small behaviors, and keep htmx.onLoad for libraries that know nothing about Alpine.

State that survives a swap

A swap replaces the target's content, not the elements around it. If an x-data element sits outside the target, its state is untouched. If the x-data element is the target (or is inside it), the swap destroys it and the fresh fragment starts with fresh state.

Which swaps keep Alpine state?

Click the local button a few times, then press "Refresh list only". The click count stays, and the swap counter goes up, because the component lives outside the target. Now press "Replace whole component": both counters return to zero, because Alpine initialized a brand-new component.

Notice the @htmx:after-swap listener. HTMX fires every event twice, once as htmx:afterSwap and once in kebab-case, and the kebab-case name is what you write in an Alpine attribute (HTML attributes are case-insensitive).

To keep state across a full replacement, either move the x-data element above the swap target, or keep the value in an Alpine store that lives outside the DOM.

Alpine events that start HTMX requests

Sometimes the UI knows when a request should happen, but the element that should send it is somewhere else. Alpine's $dispatch creates a custom DOM event that bubbles up. HTMX can listen for it with hx-trigger, using from:body to hear events from anywhere.

$dispatch triggers an HTMX request

The buttons know nothing about HTTP. They only announce filter-changed and include the chosen tag in detail. The results panel declares when it wants to refresh (load and filter-changed from:body) and what to send (hx-vals with a js: expression that reads the event). Each side stays small, and you could add a second panel that listens to the same event without touching the buttons.

A modal with server content

Modals and dropdowns are the classic mix: Alpine decides whether they are visible, HTMX fills them. One button can do both jobs, because a single element may carry hx-get and @click.

Alpine modal, HTMX content

Press the button: the dialog opens at once (Alpine, no waiting), and the "Loading..." text turns into the profile a moment later (HTMX). Press Escape or click the dark area to close it. Because the dialog markup is part of the page, it stays accessible and cached. Only the changing part comes from the server.

If you reuse the same modal for many records, reset the body to a placeholder when it closes, so the next user does not see the previous record for a moment.

Ordering pitfalls

Most bugs in this combination come from one fact: the two libraries start up independently and both read the DOM.

  • Alpine-bound HTMX attributes. HTMX processes hx-* attributes when elements arrive. If Alpine creates the attribute later with :hx-get="url", HTMX may have already looked and found nothing. Prefer plain attributes, or call htmx.process($el) from x-init after Alpine sets the attribute.
  • Script order. Load HTMX first and Alpine with defer, as in every example here, so x-data does not run before the libraries exist.
  • Replacing the x-data element. As you saw, outerHTML swaps reset state. Put long-lived state higher in the tree.
  • Flash of hidden content. Elements with x-show are visible until Alpine starts. Add x-cloak and the rule [x-cloak] { display: none !important; } to hide them early.
  • Duplicate ids. A fragment that is swapped twice with beforeend repeats its ids. Use classes or generate unique ids on the server.

Never put raw user input into a fragment that contains Alpine expressions. An attribute such as x-data="{ name: '{{ name }}' }" runs as JavaScript, so a quote in the name is an injection. Escape it, or pass values through data- attributes and read them with $el.dataset. The next lesson covers this in depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A product list comes from a database, and the filter panel can be collapsed. Which library should own each piece?

    Database data is server state, so the server sends it as HTML. Whether a panel is collapsed is view state that only the browser needs.
  2. 2. An HTMX swap inserts HTML that contains an element with x-data. What do you have to do for it to work?

    Alpine observes the DOM for added nodes and starts any new x-data components automatically.
  3. 3. When is Alpine state lost during an HTMX swap?

    A swap that removes the x-data element destroys the component. A component outside the target keeps its state.
  4. 4. Which pair lets an Alpine button cause an HTMX element elsewhere on the page to send a request?

    $dispatch creates a bubbling custom event, and hx-trigger with from:body listens for it anywhere in the page.

Summary

  • Give each piece of state one owner: the server (HTMX) for data and rules, the browser (Alpine) for view state.
  • Alpine initializes x-data inside swapped fragments automatically; use htmx.onLoad only for other libraries.
  • State survives swaps when its x-data element is outside the target, and resets when the element is replaced.
  • $dispatch plus hx-trigger="name from:body" connects Alpine events to HTMX requests, and hx-vals="js:..." can read the event detail.
  • For modals, let Alpine open and close, and let HTMX fill the content.
  • Watch for ordering problems: Alpine-created hx-* attributes, script order, replaced components, flashes and duplicate ids.

Continue with Server-Side Setup: Fragments, Partials and Security.