HTML over the wire: what HTMX actually does
The htmx 4 mechanism built up from links and forms: a real HTTP exchange with a Go server, swap and error defaults, and the cases where it is the wrong tool.
- topic
- go and htmx
- date
- read
- 17 min
htmx is a JavaScript library that issues an HTTP request when an event fires on an element and puts the HTML that comes back somewhere in the page. This article takes that sentence apart: which attribute controls each part, what goes over the wire, what the server does differently, how error responses behave, and which kinds of interface the model handles badly.
The code is for htmx 4.0.2 and Go 1.27.3, using net/http and html/template and no other dependency. The version needs a word. htmx 4.0 was published in August 2026 and is documented at four.htmx.org, but the npm latest tag still points at 2.0.11, and the htmx.org front page says that will change at some point in 2027. Where 2.x behaves differently, the text says so. The server below serves the 4.0.2 file itself, fetched once:
curl -sSLo static/htmx.min.js https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.jsTwo controls, four restrictions
HTML has two elements that make the browser send a request and act on the response. They are its hypermedia controls:
<a href="/tasks?q=go">Tasks about Go</a>
<form method="post" action="/tasks">
<input name="title">
<button>Add</button>
</form>Clicking the link sends GET /tasks?q=go. Submitting the form sends POST /tasks with the field in the body. Four things are fixed: only these two elements issue requests, only a click or a submit triggers them, the method is GET or POST, and the response takes over the entire window.
htmx lifts each restriction with an attribute. hx-get, hx-post, hx-put, hx-patch and hx-delete go on any element and choose the method. hx-trigger names the event. hx-target picks the element that receives the response, and hx-swap says how it is inserted. Here is the body of a small task list that uses all of them, written as html/template source:
<body>
<h1>Tasks</h1>
<p id="flash" role="status"></p>
{{template "count" .}}
<input type="search" name="q" value="{{.Query}}" placeholder="Filter"
hx-get="/tasks"
hx-trigger="input changed delay:300ms"
hx-target="#tasks"
hx-swap="outerHTML"
hx-push-url="true">
{{template "list" .}}
{{template "form" .}}
</body>{{define "list"}}<ul id="tasks">
{{range .Tasks}}{{template "task" .}}
{{end}}</ul>{{end}}
{{define "task"}}<li id="task-{{.ID}}">
{{.Title}}
<button hx-delete="/tasks/{{.ID}}" hx-target="closest li" hx-swap="delete">Delete</button>
</li>{{end}}
{{define "form"}}<form id="new-task" method="post" action="/tasks"
hx-post="/tasks" hx-target="this" hx-swap="outerHTML">
<input name="title" value="{{.Title}}" placeholder="New task">
<button>Add</button>
{{- with .Error}}
<p role="alert">{{.}}</p>
{{- end}}
</form>{{end}}The filter is an <input> that issues a GET. It fires on input events, after a 300 ms pause and only if the value changed, and it sends its own name and value as the query string. The response replaces the list, and hx-push-url copies the request URL to the address bar.
Each Delete button issues a DELETE, a method no HTML form can send. Its target is the closest enclosing <li>, and the delete swap removes that element whatever the response body contains.
The form is still a working HTML form, with method and action. Once the script has loaded, hx-post takes over the submit, and the response replaces the form itself where a plain submit would replace the page.
Left out, each attribute has a default. The event is submit on a form, change on an input, select or textarea, and click on anything else. The target is the element that issued the request, and the response replaces its children.
On the server, the page needs three routes and a directory for the script (the pattern syntax is covered in The standard library router is enough):
mux := http.NewServeMux()
mux.Handle("GET /{$}", http.RedirectHandler("/tasks", http.StatusSeeOther))
mux.HandleFunc("GET /tasks", a.index)
mux.HandleFunc("POST /tasks", a.create)
mux.HandleFunc("DELETE /tasks/{id}", a.delete)
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))One interaction on the wire
Typing go into the filter produces one request. The exchange below was reproduced with curl, so you can run it yourself: the HX- values were read from a headless Chromium session driving this page with htmx 4.0.2, then passed to curl by hand. The grep removes curl’s connection messages.
curl -sv 'http://localhost:8895/tasks?q=go' \
-H 'Accept: text/html' \
-H 'HX-Request: true' \
-H 'HX-Request-Type: partial' \
-H 'HX-Source: input' \
-H 'HX-Target: ul#tasks' \
-H 'HX-Current-URL: http://localhost:8895/tasks' 2>&1 | grep -v '^[*{}]'> GET /tasks?q=go HTTP/1.1
> Host: localhost:8895
> User-Agent: curl/8.7.1
> Accept: text/html
> HX-Request: true
> HX-Request-Type: partial
> HX-Source: input
> HX-Target: ul#tasks
> HX-Current-URL: http://localhost:8895/tasks
>
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=utf-8
< Vary: HX-Request-Type
< Date: Sat, 28 Nov 2026 21:55:02 GMT
< Content-Length: 150
<
<ul id="tasks">
<li id="task-2">
Read the Go spec
<button hx-delete="/tasks/2" hx-target="closest li" hx-swap="delete">Delete</button>
</li>
</ul>In the browser this is an ordinary fetch call. HX-Request marks it as coming from htmx. HX-Request-Type is partial because the target is an element other than <body>. HX-Source and HX-Target name the triggering and the receiving element as tag#id (the input has no id, hence the bare input), and HX-Current-URL is the address bar at the time of the request.
The response is 150 bytes of HTML, which htmx parses and swaps over #tasks. No JSON is involved and no client-side template: the server sent the representation the user sees.
htmx 2.0.11 sent a different set of headers for the same keystrokes: HX-Request, HX-Current-URL, HX-Target: tasks (the bare id) and HX-Trigger-Name: q. It has no HX-Request-Type.
One URL, two representations
The fragment came from /tasks, the URL of the page itself. The handler decides what to render from the request type:
// wantsFragment reports whether htmx asked for part of a page.
func wantsFragment(r *http.Request) bool {
return r.Header.Get("HX-Request-Type") == "partial"
}
func (a *app) index(w http.ResponseWriter, r *http.Request) {
v := a.view(r.URL.Query().Get("q"))
w.Header().Add("Vary", "HX-Request-Type")
if wantsFragment(r) {
render(w, http.StatusOK, "list", v)
return
}
render(w, http.StatusOK, "page", v)
}a.view collects the tasks that match the filter, and render executes a named template into a buffer and writes it with the given status. The page template includes list, so the fragment and the full page cannot drift apart (the htmx essays call this template fragments). Without the htmx headers, the same URL returns the document:
curl -i 'http://localhost:8895/tasks?q=go'HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Vary: HX-Request-Type
Date: Sat, 28 Nov 2026 21:55:02 GMT
Content-Length: 1201
<!doctype html>
<html lang="en">
...A separate fragment endpoint such as /tasks/list looks tidier and breaks two things. hx-push-url would put /tasks/list?q=go in the address bar, a URL that renders as a bare list when it is reloaded or sent to someone else. And on Back, htmx 4 keeps no snapshot of the previous page: in the headless session it requested /tasks again, with HX-History-Restore-Request: true and HX-Request-Type: full, and swapped the body. Every URL that enters the history has to answer with a full page. In the same test 2.0.11 restored the page from the snapshot it keeps in sessionStorage and sent nothing.
Branch on HX-Request-Type rather than on HX-Request. A link with hx-boost, or any element with hx-target="body", sends HX-Request: true together with HX-Request-Type: full, and it needs the whole page.
The Vary header tells caches, the browser’s own included, that the response for this URL depends on that request header. Without it, a cache keyed on the URL alone can answer a full page load with the fragment. The htmx documentation on caching gives the same advice for HX-Request.
The POST handler follows the same rule, which keeps the form usable when the script has not loaded:
func (a *app) create(w http.ResponseWriter, r *http.Request) {
title := strings.TrimSpace(r.FormValue("title"))
if problem := a.validate(title); problem != "" {
v := a.view("")
v.Title, v.Error = title, problem
name := "page"
if wantsFragment(r) {
name = "form"
}
render(w, http.StatusUnprocessableEntity, name, v)
return
}
t := a.add(title)
if !wantsFragment(r) {
http.Redirect(w, r, "/tasks", http.StatusSeeOther)
return
}
v := a.view("")
v.Created, v.OOB = t, true
render(w, http.StatusOK, "created", v)
}A plain form post, without the header, gets 303 See Other with Location: /tasks on success and the whole page with status 422 on a validation error.
Swap styles
hx-swap takes one of these values in 4.0.2. Each was run in the browser against the same response:
| Value | What happens |
|---|---|
innerHTML (default) |
The target’s children are replaced by the response. |
outerHTML |
The target itself is replaced. |
beforebegin, afterbegin, beforeend, afterend |
The response is inserted before the target, before its first child, after its last child, or after the target. before, prepend, append and after are aliases, in that order. |
delete |
The target is removed and the response body is ignored. |
none |
Nothing is swapped. Out-of-band elements in the response are still processed. |
textContent |
The response is set as the target’s text, without HTML parsing. |
innerMorph, outerMorph |
The response is merged into the existing nodes, which are kept where they match. |
outerSync |
The target element stays. Its attributes are updated and its children replaced. |
The aliases, the two morph styles and outerSync do not exist in 2.0.11.
Error statuses
htmx 4.0.2 swaps every response except a 204 or a 304. That includes 4xx and 5xx responses, which first fire an htmx:response:error event. In 2.x they were not swapped unless you configured it.
The new default exists for validation. Submitting a title that is already on the list:
curl -i http://localhost:8895/tasks \
-H 'HX-Request: true' \
-H 'HX-Request-Type: partial' \
-d 'title=ship IT'HTTP/1.1 422 Unprocessable Entity
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 21:55:02 GMT
Content-Length: 259
<form id="new-task" method="post" action="/tasks"
hx-post="/tasks" hx-target="this" hx-swap="outerHTML">
<input name="title" value="ship IT" placeholder="New task">
<button>Add</button>
<p role="alert">That task is already on the list.</p>
</form>The handler rendered the form template with the message and the submitted value, and htmx put the result where the form was. The status is honest and showing the error took no client code. With 2.0.11 loaded in the same page, the 422 was not swapped and the form did not change.
The default cuts the other way for failures that nobody designed a response for. Go’s http.Error writes a plain-text body, and with the default configuration a 500 from the POST replaced the form with the words Internal Server Error. The page’s <head> separates the two cases:
<meta name="htmx-config" content='{"noSwap": [204, 304, "5xx"]}'>
<script src="/static/htmx.min.js"></script>
<script>
document.addEventListener("htmx:response:error", (event) => {
const status = event.detail.ctx.response.status;
if (status >= 500) {
document.querySelector("#flash").textContent =
"The server answered " + status + ". Nothing was saved.";
}
});
</script>With 5xx in noSwap, a 500 leaves the form and what was typed in place, and the listener writes a message into #flash. The attribute hx-status:5xx="swap:none" does the same for a single element. A request that gets no response at all (a dropped connection, in the test) swaps nothing and fires htmx:error.
Out-of-band swaps
One response normally updates one target. Adding a task has to change three places: the form, the list and the counter. The response to a valid POST carries all three:
curl -i http://localhost:8895/tasks \
-H 'HX-Request: true' \
-H 'HX-Request-Type: partial' \
-d 'title=Buy milk'HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 21:55:02 GMT
Content-Length: 412
<form id="new-task" method="post" action="/tasks"
hx-post="/tasks" hx-target="this" hx-swap="outerHTML">
<input name="title" value="" placeholder="New task">
<button>Add</button>
</form>
<ul id="tasks" hx-swap-oob="beforeend">
<li id="task-4">
Buy milk
<button hx-delete="/tasks/4" hx-target="closest li" hx-swap="delete">Delete</button>
</li>
</ul>
<p id="count" hx-swap-oob="true">4 in total</p>The empty form is ordinary content and replaces the old one. The other two elements carry hx-swap-oob, which takes them out of the main content and swaps each one by id. true replaces the existing #count. beforeend appends the children of the <ul> wrapper to the existing #tasks and discards the wrapper. Deleting a task returns only the counter, marked the same way, while the button’s own delete swap removes the row.
On the server this is one more template:
{{define "count"}}<p id="count"{{if .OOB}} hx-swap-oob="true"{{end}}>{{.Total}} in total</p>{{end}}
{{define "created"}}{{template "form" .}}
<ul id="tasks" hx-swap-oob="beforeend">
{{template "task" .Created}}
</ul>
{{template "count" .}}
{{end}}The cost is coupling: the handler for one action has to know every region of the page that shows data it changed. When the regions sit close together, a wider target avoids that. Re-render their common parent and no out-of-band element is needed. htmx 4 also accepts <hx-partial hx-target="..." hx-swap="..."> wrappers in a response, which do the same job with an explicit selector.
What state lives where
Application state is on the server and nowhere else. The browser never holds the tasks as data, so there is nothing to reconcile after a delete: the server counts again and sends the new counter.
View state that should survive a reload goes in the URL. The filter lives in ?q=go, and the server renders from it.
Everything else is in the DOM, such as the text typed into a field and which element has focus. That state lasts as long as its element does, so choosing a target is choosing what to throw away. The filter input sits outside #tasks and kept focus while the list was replaced next to it. The form is replaced on every response, which is how it comes back empty after a successful add, and why the 422 response has to echo the submitted title. In a test with a text field inside the target, an innerHTML swap produced a new field and lost what had been typed, while innerMorph kept the same node and its text.
Where the model is the wrong tool
Every interaction costs a round trip to the server, and some interfaces cannot pay that.
Dragging an element, or moving a slider that updates a preview, produces events faster than responses can come back. The 300 ms delay on the filter is already a concession to this. Handle the gesture in a script and send one request when it ends.
A spreadsheet or a rich text editor is a function of data that changes with every keystroke, most of which the server has no reason to see. Rendering it remotely means sending that state to the server and back for each change. A client-side framework with a real state model, talking JSON, is the right tool there.
Offline use is out entirely. With no server there are no interactions, so the data and the logic have to live on the device.
The server pays too. These endpoints return HTML for one page layout, so a mobile app or a third party needs a JSON API next to them.
The choice can be made one interaction at a time. The page above already carries a short script for its error message, and a widget that needs local state can be a script or a framework component inside a server-rendered page. htmx itself adds one file, 37,477 bytes minified and 13,465 after gzip -c. The useful test is whether the server has to be consulted anyway, to load or to save something. If it does, sending HTML removes a serialization layer and a client-side copy of the state. If it does not, a request is the wrong mechanism.