HTMX Swaps Server-Rendered HTML Fragments Instead of Exchanging JSON
HTMX is a small JavaScript library that lets HTML attributes send requests in the background (AJAX) and put the response into the page. The server answers with ready-made HTML rather than JSON, so the interactivity lives in templates the backend already renders, and the frontend needs little or no hand-written JavaScript.
How a Request Flows
<button hx-get="/contacts" hx-target="#list" hx-swap="innerHTML">
Load contacts
</button>
<div id="list"></div>
- The click triggers a
GET /contactsin the background. - The server renders a fragment (
<ul><li>…</li></ul>) with its normal template engine. - HTMX swaps that fragment into
#list. No JSON parsing, no client-side templating.
| Attribute | Decides |
|---|---|
hx-get, hx-post, hx-put, hx-delete |
which request is sent |
hx-trigger |
which event sends it (click, change, keyup with a delay, page load) |
hx-target |
which element receives the response |
hx-swap |
how it is inserted (replace content, replace element, append…) |
Why It Fits Server-Rendered Apps
With Django or Rails, the backend already owns the templates and the state. HTMX adds partial page updates to that model instead of duplicating it in a JavaScript framework, and it stays readable: what a button does is written on the button.
When It Doesn't Fit
Highly interactive interfaces that keep a lot of state in the browser (editors, offline apps) are better served by a client-side framework.
References
- Programming Languages MOC - hub for language and frontend notes.
- htmx documentation - attributes, triggers and swaps.
- HTMX - The Practical Guide (Udemy) - the course I took notes from.
Review cards
Flashcard Why does HTMX send HTML fragments instead of JSON?
Sending HTML fragments allows the server to use its existing template engine and the frontend to avoid JSON parsing and client-side templating.
Quiz Which of these is NOT a valid hx-swap value?
- innerHTML
- outerHTML
- beforebegin
- append
There is no append: use beforeend to add the response at the end of the target.