Building Interactive Web Apps with HTMX and Go Templates

Dropping heavy client-side JavaScript bundles in favor of Go html/template fragments and HTMX turned our internal operations consoles into single-binary speed demons.

VW
Viery Wahyu•Author
•7 min read

Modern web development has a strange habit of convincing engineers that every single screen needs the architectural complexity of a distributed spacecraft. Whenever a team needs to build an internal hardware diagnostic console, a laboratory job tracker, or a fleet management dashboard, the default reflex is spinning up a heavy frontend build pipeline alongside a separate backend API server. Suddenly you are maintaining hundreds of megabytes of node_modules, writing REST or GraphQL serialization layers, duplicating validation schemas between Go and TypeScript, and debugging client-side cache invalidation bugs just to let an technician update a ticket status on a table. When I needed to ship a fast, rock-solid operations console for our data recovery and hardware servicing workflows without adding another high-maintenance repository to our CI pipeline, I decided to skip the single-page application industrial complex entirely and built the whole system using Go templates and HTMX.

The Quiet Power of Returning to Hypermedia

To appreciate why HTMX feels like such a breath of fresh air, you have to examine why we started shipping massive JavaScript runtimes to the browser in the first place. Traditional HTML only allowed two elements—anchor tags and forms—to trigger HTTP requests using only two methods, GET and POST, and every single response forced the browser to blow away the entire screen and repaint the whole document from scratch. To avoid that jarring full-page flash, our industry spent a decade moving routing, state management, and HTML templating out of the server and into gigabytes of client-side JavaScript that talks to the backend exclusively through raw JSON payloads.

HTMX fixes the root limitation of HTML rather than replacing the browser with a JavaScript virtual machine. By loading a single fourteen-kilobyte script tag with zero dependencies, any DOM element on your page can issue GET, POST, PUT, PATCH, or DELETE requests in response to any user event and swap the resulting HTML fragment directly into a specific target node on the screen. Your backend server goes back to being the single source of truth for application state, and your network tab carries crisp, ready-to-render HTML fragments instead of bloated JSON payloads that require client-side reconciliation.

Compiling an Entire Full-Stack Application Into One Go Binary

Pairing HTMX with Go's standard library unlocks a deployment model that feels almost illegally simple compared to modern JavaScript meta-frameworks. Using Go's native //go:embed directive alongside the built-in html/template and net/http packages, we embedded all of our HTML templates, CSS stylesheets, and the static HTMX script directly inside the compiled Go binary.

Instead of deploying separate frontend CDN buckets, Node.js SSR containers, and backend API pods, our entire full-stack application compiles in two seconds into a single fifteen-megabyte static Linux binary that boots in three milliseconds and consumes less than eighteen megabytes of RAM under load. Even better, Go's {{ block }} template syntax allows us to define reusable partial fragments right inside the main page template, so the exact same markup can render during an initial full-page browser load or be executed independently as a surgical micro-fragment when triggered by an HTMX request header.

golang
1package main
2
3import (
4 "embed"
5 "html/template"
6 "net/http"
7 "time"
8)
9
10//go:embed templates/*.html
11var templateFS embed.FS
12
13type DiagnosticJob struct {
14 ID string
15 DriveModel string
16 Status string
17 UpdatedAt string
18 ActiveCount int
19}
20
21var appTemplates = template.Must(template.ParseFS(templateFS, "templates/*.html"))
22
23func handleAdvanceJobStatus(w http.ResponseWriter, r *http.Request) {
24 if r.Method != http.MethodPost {
25 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
26 return
27 }
28
29 jobID := r.PathValue("id")
30 nextState := r.FormValue("next_status")
31
32 // Mutate state directly in local database or in-memory engine
33 updatedJob := DiagnosticJob{
34 ID: jobID,
35 DriveModel: "WD-12TB-NAS-PRO",
36 Status: nextState,
37 UpdatedAt: time.Now().Format("15:04:05 MST"),
38 ActiveCount: 14,
39 }
40
41 w.Header().Set("Content-Type", "text/html; charset=utf-8")
42
43 // Execute only the partial row and out-of-band counter fragment for HTMX
44 err := appTemplates.ExecuteTemplate(w, "job-row-update", updatedJob)
45 if err != nil {
46 http.Error(w, err.Error(), http.StatusInternalServerError)
47 }
48}

Look at the execution path inside handleAdvanceJobStatus. There is no JSON marshaling, no DTO mapping layer, no CORS preflight negotiation, and zero client-side state hydration. When the technician clicks a status button, Go reads the form parameter, updates the database record, and streams the compiled job-row-update HTML template straight back to the socket in less than four hundred microseconds. Because Go's html/template package automatically escapes variables based on whether they land inside an HTML body, an attribute, or a URL parameter, cross-site scripting vulnerabilities are neutralized at the compiler level before a single byte leaves the server.

Updating Multiple Distant DOM Nodes With Out-of-Band Swaps

The most common skepticism engineers voice when evaluating HTMX is what happens when a single user mutation needs to update two completely separate areas of the screen at once. In a trivial demo, clicking a button inside a table row and replacing that exact <tr id="job-104"> element via hx-target is obvious. In a real operations console, however, transitioning a job from QUEUED to IN_CLEANROOM also needs to decrement the pending queue counter sitting inside the top navigation bar and append an audit toast at the bottom of the viewport.

In React, you solve that by lifting state up into a global store or invalidating multiple TanStack Query keys. In HTMX, you solve it without writing a single line of custom JavaScript by returning an Out-of-Band swap fragment using the hx-swap-oob="true" attribute right alongside your primary HTML response.

html
1<!-- templates/dashboard.html -->
2<header class="flex items-center justify-between border-b p-4">
3 <h1 class="text-xl font-bold">Lab Recovery Queue</h1>
4 <span id="active-queue-badge" class="rounded bg-blue-100 px-3 py-1 text-sm font-semibold">
5 Active Jobs {{ .ActiveCount }}
6 </span>
7</header>
8
9<table class="w-full text-left text-sm">
10 <tbody id="jobs-table-body">
11 {{ block "job-row" . }}
12 <tr id="job-row-{{ .ID }}" class="border-b">
13 <td class="p-3 font-mono">{{ .ID }}</td>
14 <td class="p-3">{{ .DriveModel }}</td>
15 <td class="p-3 font-semibold">{{ .Status }}</td>
16 <td class="p-3 text-gray-500">{{ .UpdatedAt }}</td>
17 <td class="p-3">
18 <button
19 hx-post="/jobs/{{ .ID }}/advance"
20 hx-vals='{"next_status": "CLEANROOM_IMAGING"}'
21 hx-target="#job-row-{{ .ID }}"
22 hx-swap="outerHTML"
23 class="rounded bg-black px-3 py-1.5 text-xs text-white"
24 >
25 Move to Cleanroom
26 </button>
27 </td>
28 </tr>
29 {{ end }}
30 </tbody>
31</table>
32
33<!-- Partial response template rendered by handleAdvanceJobStatus -->
34{{ define "job-row-update" }}
35 {{ template "job-row" . }}
36 <span
37 id="active-queue-badge"
38 hx-swap-oob="true"
39 class="rounded bg-emerald-100 px-3 py-1 text-sm font-semibold text-emerald-900"
40 >
41 Active Jobs {{ .ActiveCount }}
42 </span>
43{{ end }}

Trace how HTMX processes that job-row-update payload when it arrives in the browser. First, it takes the primary <tr> element rendered by {{ template "job-row" . }} and swaps it cleanly into #job-row-104 as instructed by the button's hx-target and hx-swap="outerHTML" attributes. Next, HTMX spots the sibling <span id="active-queue-badge" hx-swap-oob="true"> element in the response stream, plucks it out of the payload, locates the matching #active-queue-badge node sitting all the way up in the page <header>, and swaps the updated counter into place automatically. We get instant, multi-region UI reactivity driven entirely by server-rendered HTML templates over a single sub-millisecond HTTP round trip.

Knowing Where Hypermedia Shines and Where It Stops

Building production interfaces with HTMX and Go templates taught me that architectural minimalism is a massive competitive advantage when applied to the right problem domain. If you are building an offline-capable graphic design canvas, a spreadsheet with complex client-side formula cells, or a multi-window trading terminal that processes fifty WebSocket ticks per second on the client CPU, you still want a rich client-side state runtime like React or SolidJS.

However, be honest about how much of the software we build actually falls into that category. Eighty percent of enterprise back-office portals, SaaS settings panels, CRUD workflows, and operational dashboards are simply forms and tables reading and mutating server-side database rows. Forcing those workloads through a complex client-side SPA pipeline is pure architectural ceremony. By collapsing our stack down to Go html/template and HTMX on our internal tooling, we eliminated build steps, deleted thousands of lines of glue code, and rediscovered the joy of shipping full-stack features from database to browser in fifteen minutes flat.

VW

Written by

Viery Wahyu

📍 Bali, Indonesia

Software Engineer

Software engineer based in Bali with over a decade of experience building fast web applications

The Journal

View all →