Debian Codegraph @

www/src/content/extensions/12-hx-alpine-compat.md

raw symbols SCIP
1 ---
2 title: "hx-alpine-compat"
3 description: "Run htmx alongside Alpine.js without conflicts"
4 category: "Compatibility"
5 icon: "icon-[simple-icons--alpinedotjs]"
6 keywords: ["alpine", "alpinejs", "compatibility", "integration", "history"]
7 ---
8
9 The `alpine-compat` extension provides a compatibility layer between htmx and [Alpine.js](https://alpinejs.dev/), ensuring Alpine components are correctly initialized and preserved across htmx-driven DOM updates.
10
11 ## Installing
12
13 ```html
14 <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/htmx.min.js"></script>
15 <script src="https://cdn.jsdelivr.net/npm/htmx.org@__VERSION__/dist/ext/hx-alpine-compat.js"></script>
16 <script defer src="/path/to/alpine.js"></script>
17 ```
18
19 Alpine must load **after** the extension script. The `defer` attribute ensures this.
20
21 ## What it does
22
23 ### Alpine initialization on swap
24
25 htmx's settle phase introduces a brief pause after swapping content to allow CSS transitions to run. Alpine's mutation observer fires during this window and sees the intermediate DOM state, causing components to initialize against incomplete or transitioning content. The extension defers Alpine's mutation observer before the swap and flushes it only after the settle phase completes, so Alpine always initializes against the final stable DOM.
26
27 ### Morph-aware state preservation
28
29 When using `innerMorph` or `outerMorph` swap styles, htmx reconciles the existing DOM with new content rather than replacing it. The extension hooks into `htmx:before:morph:node` to carry Alpine's reactive data stack from the old node to the new one before morphing, preventing Alpine state from being lost during reconciliation. This replaces the need for Alpine's native morph extension.
30
31 ### Alpine ID binding compatibility
32
33 Alpine can bind reactive values to an element's `id` attribute via `:id` or `x-bind:id`. This causes the morph algorithm to see mismatched IDs and treat matching elements as different nodes. The extension overrides the soft-match check to ignore ID mismatches when both nodes have Alpine-reactive ID bindings, keeping the morph stable.
34
35 ## Combining with `history-cache`
36
37 When used alongside the [`history-cache`](/docs/extensions/history-cache) extension, `alpine-compat` also handles saving and restoring Alpine component state across history navigation.
38
39 ### How it works
40
41 Before a page is saved to the history cache, the extension serializes each Alpine component's reactive data to a `data-alpine-state` attribute, then tears down the Alpine tree so the snapshot is clean HTML. On restore, it re-applies the saved values back into the live Alpine data stack after Alpine has re-initialized the restored content.