Server-rendered apps with Go, templ and HTMX
First htmx interactions
How htmx 4 triggers, targets and swaps a request, how the server tells a fragment request from a page request, and three interactions built on that.
- lesson
- 04 of 08
- read
- 14 min
Every click in the application reloads the whole page. htmx removes that limit with attributes that let any element issue a request on an event of your choice and put the returned HTML into an element you name. This lesson adds htmx to the page and converts three interactions, each with a different target and swap.
The course uses htmx 4.0.2. Version 4.0 was released in August 2026 and is documented at four.htmx.org, while the front page of htmx.org and npm’s latest tag still show the 2.x line. If you know 2.x, expect differences in the request headers, in attribute inheritance and in how error responses are handled. The article What htmx actually does covers the same version and compares the two. Every attribute and header below was run against 4.0.2.
Serve htmx yourself
mkdir static
curl -sSfLo static/htmx.min.js https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.js
openssl dgst -sha384 -binary static/htmx.min.js | openssl base64 -A6NzMyCdh08UZ4b4M17SJJKQLdDijx4z2IqqKLKD0Q/PzCFQLpFuk3konY0WgqbTyThat is the integrity hash the htmx installation docs publish for 4.0.2. wc -c reports 37477 bytes for the file, and gzip -9 -c static/htmx.min.js | wc -c reports 13450.
The script is downloaded once and served by the application instead of being loaded from a CDN on every page view. It is then pinned to the version you tested and works without internet access. No third party can change what your pages load or see who loads them.
Add a small stylesheet next to it:
body { font: 16px/1.5 system-ui, sans-serif; max-width: 42rem; margin: 2rem auto; padding: 0 1rem; }
form { display: flex; flex-wrap: wrap; gap: .5rem; align-items: end; margin: 1rem 0; }
#links { list-style: none; padding: 0; }
#links > li { padding: .75rem 0; border-top: 1px solid #ddd; }
#links > li.read > a { color: #777; text-decoration: line-through; }
#links > .empty:not(:only-child) { display: none; }Reference both files from the layout’s <head>:
<title>{ title }</title>
<link rel="stylesheet" href="/static/app.css"/>
<script src="/static/htmx.min.js"></script>And serve the directory, as the first route in routes.go:
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))http.Dir("static") is relative to the working directory, so this works only when the server is started from the project root. Lesson 8 removes that restriction.
Trigger, target, swap
Start with the “Mark read” button. Its form gains three attributes:
templ LinkItem(l Link) {
<li
id={ fmt.Sprintf("link-%d", l.ID) }
if l.Read {
class="read"
}
>
<a href={ l.URL }>{ l.Title }</a>
<small>{ host(l.URL) }, { l.CreatedAt.Format("Jan 2") }</small>
if l.Note != "" {
<p>{ l.Note }</p>
}
<form
action={ fmt.Sprintf("/links/%d/toggle", l.ID) }
method="post"
hx-post={ fmt.Sprintf("/links/%d/toggle", l.ID) }
hx-target="closest li"
hx-swap="outerHTML"
>
<button type="submit">
if l.Read {
Mark unread
} else {
Mark read
}
</button>
</form>
</li>
}For every request, htmx needs to know three things.
The first is the trigger. Without hx-trigger, an element uses its natural event: submit for a form, change for an input, select or textarea, click for everything else. So this form sends its request when it is submitted, and htmx cancels the browser’s own submission.
The second is the target, the element that receives the response. hx-target takes a CSS selector, or an extended one such as closest li, which walks up from the form to the list item around it. Without the attribute the target is the element itself.
The third is the swap. hx-swap="outerHTML" replaces the target with the response. The default, innerHTML, would put the response inside the target and keep the old <li> as a wrapper. The hx-swap reference lists the other styles.
The form keeps its action and method. A browser without scripts ignores the hx- attributes and submits it as before.
Fragment or page
The toggle handler now has two kinds of client. A plain form submission should end in a redirect to the page. htmx wants only the new list item. These are the htmx headers on the request, as recorded in a browser when clicking the button for link 2:
HX-Request: true
HX-Request-Type: partial
HX-Source: form
HX-Target: li#link-2
HX-Current-URL: http://localhost:8792/linksHX-Request marks a request made by an htmx element. HX-Request-Type says what htmx will do with the answer: partial when the target is an element inside the page, full when the target is the document body. The second header is the one to branch on, because an htmx request can need a whole page. A button with hx-target="body", tried in the browser, sent HX-Request: true together with HX-Request-Type: full. Add a helper to handlers.go and use it:
// isPartial reports whether htmx made the request and will swap the response
// into part of the page.
func isPartial(r *http.Request) bool {
return r.Header.Get("HX-Request-Type") == "partial"
}
func (a *app) toggleLink(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
http.NotFound(w, r)
return
}
l, err := a.store.ToggleRead(r.Context(), id)
if err != nil {
a.storeError(w, r, err)
return
}
if isPartial(r) {
a.render(w, r, http.StatusOK, LinkItem(l))
return
}
http.Redirect(w, r, "/links", http.StatusSeeOther)
}The fragment is rendered by LinkItem, the same component the page uses for each row. There is no second template to keep in sync. With curl standing in for htmx by sending the one header the server reads:
curl -i -X POST -H 'HX-Request-Type: partial' localhost:8792/links/1/toggleHTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sat, 28 Nov 2026 22:15:42 GMT
Content-Length: 371
<li id="link-1" class="read"><a href="https://htmx.org/essays/hypermedia-driven-applications/">Hypermedia-Driven Applications</a> <small>htmx.org, Nov 29</small> <p>The architecture this app follows.</p><form action="/links/1/toggle" method="post" hx-post="/links/1/toggle" hx-target="closest li" hx-swap="outerHTML"><button type="submit">Mark unread</button></form></li>Without the header, a toggle still answers 303 See Other with Location: /links.
Filter without a reload
The search form uses hx-get and a non-default trigger:
templ SearchForm(f Filter) {
<form
id="search"
action="/links"
method="get"
hx-get="/links"
hx-trigger="submit, change target:select"
hx-target="#links"
hx-swap="outerHTML"
hx-push-url="true"
>
<input type="search" name="q" value={ f.Query } placeholder="Search" aria-label="Search"/>
<select name="filter" aria-label="Show">
<option value="all">All</option>
<option value="unread" selected?={ f.Status == "unread" }>Unread</option>
<option value="read" selected?={ f.Status == "read" }>Read</option>
</select>
<button type="submit">Search</button>
</form>
}hx-trigger lists two triggers separated by a comma. submit is the form’s default and has to be restated once the attribute is present. change target:select listens for change events, which bubble up from the fields, and the target: modifier keeps only those that come from a <select>. The dropdown therefore applies at once, while leaving the text field does nothing until you press Enter. The hx-trigger reference lists the other modifiers.
For a GET, htmx puts the form’s fields in the query string. The response replaces the element with id links, and hx-push-url="true" puts the requested URL in the address bar, so the filtered view can be reloaded or bookmarked.
That last attribute creates an obligation. A URL in the address bar has to produce a full page when it is loaded directly, and htmx 4 relies on this itself: when the user presses Back, it requests the previous URL again and replaces the body. In the browser, that request carried HX-History-Restore-Request: true and HX-Request-Type: full. The handler therefore answers with a fragment only for partial and with the page in every other case:
func (a *app) listLinks(w http.ResponseWriter, r *http.Request) {
f := Filter{
Query: r.URL.Query().Get("q"),
Status: r.URL.Query().Get("filter"),
}
links, err := a.store.List(r.Context(), f)
if err != nil {
a.serverError(w, r, err)
return
}
w.Header().Add("Vary", "HX-Request-Type")
if isPartial(r) {
a.render(w, r, http.StatusOK, LinkList(links))
return
}
a.render(w, r, http.StatusOK, LinksPage(links, f))
}The Vary header tells caches that one URL has two representations, selected by that request header.
Link 1 was marked as read a moment ago, so it is the only one the filter returns:
curl -i -H 'HX-Request-Type: partial' 'localhost:8792/links?filter=read'HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Vary: HX-Request-Type
Date: Sat, 28 Nov 2026 22:15:42 GMT
Content-Length: 431
<ul id="links"><li id="link-1" class="read"><a href="https://htmx.org/essays/hypermedia-driven-applications/">Hypermedia-Driven Applications</a> <small>htmx.org, Nov 29</small> <p>The architecture this app follows.</p><form action="/links/1/toggle" method="post" hx-post="/links/1/toggle" hx-target="closest li" hx-swap="outerHTML"><button type="submit">Mark unread</button></form></li><li class="empty">Nothing here yet.</li></ul>Add without a reload
The third interaction inserts instead of replacing:
templ AddForm() {
<form
id="add-link"
action="/links"
method="post"
hx-post="/links"
hx-target="#links"
hx-swap="afterbegin"
hx-on::after:request="this.reset()"
>
<label>URL <input type="url" name="url" required/></label>
<label>Title <input type="text" name="title" required/></label>
<label>Note <textarea name="note" rows="2"></textarea></label>
<button type="submit">Add link</button>
</form>
}The target is the list and the swap is afterbegin, which inserts the response as the list’s first child. That matches where a reload would show the newest link. hx-on::after:request runs a line of JavaScript when htmx has received the response (:: is short for htmx:, so the event is htmx:after:request). Here it clears the fields. The handler returns the new item with 201 Created, and htmx swaps it like any other successful response:
func (a *app) createLink(w http.ResponseWriter, r *http.Request) {
l, err := a.store.Create(r.Context(),
r.PostFormValue("url"), r.PostFormValue("title"), r.PostFormValue("note"))
if err != nil {
a.serverError(w, r, err)
return
}
a.logger.Info("link created", "id", l.ID)
if isPartial(r) {
a.render(w, r, http.StatusCreated, LinkItem(l))
return
}
http.Redirect(w, r, "/links", http.StatusSeeOther)
}There is one consequence for the list. Its “Nothing here yet.” line used to be decided by the server on every page load. Now the list changes in the browser, and the server is not asked to render it again. The empty-state item is therefore always present, and the last rule of the stylesheet hides it whenever it has siblings:
templ LinkList(links []Link) {
<ul id="links">
for _, l := range links {
@LinkItem(l)
}
<li class="empty">Nothing here yet.</li>
</ul>
}Run templ generate and go run ., then open the page with the browser’s network panel visible. Marking a link sends one POST and receives one <li>. Choosing “Unread” changes the address bar to /links?q=&filter=unread without a page load, and Back returns to the unfiltered list.
The add form still accepts anything. The next lesson validates it and deals with what htmx does when the server says no.
Exercises
- Turn scripts off in the browser’s developer tools and use the page. A correct result: adding, filtering with the Search button and marking all still work, each with a full page load, because the server redirects or renders a page whenever
HX-Request-Typeis notpartial. - Add a “Refresh” button outside the search form with
hx-get="/links",hx-target="#links"andhx-swap="outerHTML". Create a link from the terminal with curl, click the button, and the link should appear. Then make the button respect the current filter withhx-include="#search": the request URL should now carryqandfilter. Finally addevery 10sto itshx-triggerand watch the network panel show a request every ten seconds. - Write a middleware that logs
HX-Request-Type,HX-TargetandHX-Sourcewhen they are present. Clicking “Mark read” on link 2 should logpartial,li#link-2andform. Changing the dropdown should logpartial,ul#linksandform#search. A page reload should log none of them.