HTMX + Alpine.js Patterns Cheat Sheet
Common patterns for pairing HTMX's server-driven HTML swaps with Alpine.js's lightweight client-side reactivity.
HTMX Basic Request + Swap
Fetch server-rendered HTML and swap it into the DOM without a page reload.
<div id="results"> <input type="text" name="q" hx-get="/search" hx-trigger="keyup changed delay:300ms" hx-target="#results" hx-swap="innerHTML" hx-indicator="#spinner"> <span id="spinner" class="htmx-indicator">Loading...</span></div>
Alpine.js Local UI State
Handle purely client-side toggles (menus, tabs) with x-data, no server round trip needed.
<div x-data="{ open: false }"> <button @click="open = !open" :aria-expanded="open">Menu</button> <ul x-show="open" x-transition x-cloak> <li>Profile</li> <li>Settings</li> </ul></div>
HTMX Triggers Alpine State
Use HTMX's hx-on to update an Alpine store after a server response lands.
<div x-data="{ count: 0 }"> <button hx-post="/like" hx-swap="none" hx-on::after-request="if(event.detail.successful) count++"> Like (<span x-text="count"></span>) </button></div><script>document.addEventListener('alpine:init', () => { Alpine.store('cart', { items: [] })})</script>
Out-of-Band Swap for Toasts
Update a notification region from any HTMX response, independent of the main target.
<!-- server response fragment --><div id="main-content">Item saved.</div><div id="toast" hx-swap-oob="true" x-data x-init="setTimeout(() => $el.remove(), 3000)"> Saved successfully!</div>
Key Attributes Cheat Table
The attributes you'll use in nearly every HTMX + Alpine page.
- hx-get / hx-post / hx-put / hx-delete- issues the corresponding HTTP verb and swaps the response
- hx-trigger- controls the DOM event that fires the request (e.g. `click`, `keyup changed delay:500ms`)
- hx-target / hx-swap- where and how (innerHTML, outerHTML, beforeend...) the response is placed
- x-data- declares an Alpine component's reactive scope
- x-show / x-if- conditional visibility (x-show toggles CSS, x-if removes from DOM)
- x-model- two-way binds form input to Alpine state
- hx-boost- progressively enhances normal <a>/<form> into AJAX navigation
Keep server state (data that must be consistent across users/sessions) in HTMX swaps and keep Alpine strictly for ephemeral, per-client UI state — mixing the two sources of truth for the same value is the #1 cause of bugs in this stack.
Explore Topics
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance