Context & Why: The JavaScript Framework Fatigue Is Real
Three months into building an internal dashboard for our team, I was staring at a 2MB JavaScript bundle that did exactly three things: fetch data, render a list, and show a modal. The React component tree had grown into something that required a team meeting just to understand. That was the moment I seriously looked at htmx.
htmx is not a new idea. It is a modern take on hypermedia — the original web architecture. Your server returns HTML fragments directly instead of shipping a JavaScript application to the browser. The browser updates just the part of the page that changed. No state management, no virtual DOM reconciliation, no hydration errors.
Version 2.0 (released mid-2024) cleaned up the API, dropped deprecated shortcuts, and tightened security defaults. If you used 1.x, most attributes are identical — upgrading takes under an hour. Coming in fresh? 2.0 is the right starting point.
When does htmx earn its place?
- Your backend already renders HTML (Django, Flask, Rails, Laravel, Go templates)
- You need interactivity — search-as-you-type, inline editing, paginated tables — without committing to a full SPA
- Your team knows HTML and backend code better than TypeScript and npm ecosystems
Both projects I shipped with htmx are still running. First-load times dropped roughly 60% when we eliminated that 2MB bundle. New developers read the codebase in an afternoon instead of spending a week fighting webpack configs. Not marketing copy — measured results, two separate production deployments.
Installation: Getting htmx 2.0 Running
The fastest path is a CDN tag in your <head>:
<!-- htmx 2.0 from CDN -->
<script src="https://unpkg.com/[email protected]/dist/htmx.min.js"></script>
For production, pin your version and serve the file yourself — CDN outages are rare but they happen:
npm install [email protected]
# Copy the minified file to your static assets folder
cp node_modules/htmx.org/dist/htmx.min.js static/js/htmx.min.js
Any server that renders HTML works as a backend. Here is a minimal Flask setup covering every example below:
from flask import Flask, render_template_string, request
app = Flask(__name__)
BASE_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>htmx Demo</title>
<script src="/static/js/htmx.min.js"></script>
</head>
<body>{{ content }}</body>
</html>
"""
@app.route("/")
def index():
content = '<button hx-get="/hello" hx-target="#result">Click me</button><div id="result"></div>'
return render_template_string(BASE_HTML, content=content)
@app.route("/hello")
def hello():
return "<p>Server says hello — no JavaScript written.</p>"
if __name__ == "__main__":
app.run(debug=True)
Run it with python app.py, open http://localhost:5000, click the button. The /hello endpoint returns an HTML fragment. htmx drops it into #result. That is the entire model.
Configuration: Core Attributes and Hypermedia Patterns
htmx works through HTML attributes. You declare intent in the markup — no event listeners, no fetch calls.
The Four Attributes You Will Use Constantly
<!-- GET request on click, replace #results content -->
<button
hx-get="/api/items"
hx-target="#results"
hx-swap="innerHTML">
Load Items
</button>
<!-- POST form without page reload, append new item to list -->
<form hx-post="/api/items" hx-target="#item-list" hx-swap="beforeend">
<input name="title" placeholder="New item" />
<button type="submit">Add</button>
</form>
<div id="results"></div>
<ul id="item-list"></ul>
hx-swap controls where the response HTML lands. The most useful values:
innerHTML— replace content inside the target (default)outerHTML— replace the target element itselfbeforeend— append inside the target, after the last child (ideal for lists)delete— remove the target after a successful response (great for “delete row” flows)
Custom Triggers for Search-as-You-Type
Buttons trigger on click and inputs trigger on change by default. Override that with hx-trigger:
<!-- Fire search 400ms after the user stops typing -->
<input
type="search"
name="q"
hx-get="/search"
hx-target="#search-results"
hx-trigger="input changed delay:400ms"
placeholder="Search..."
/>
<div id="search-results"></div>
delay:400ms debounces the request — nothing fires until the user pauses. The changed modifier skips the request entirely if the value has not actually changed, like when a user presses an arrow key without modifying the text. The corresponding Flask route:
@app.route("/search")
def search():
query = request.args.get("q", "").lower()
items = [i for i in ["docker", "kubernetes", "nginx", "redis"] if query in i]
if not items:
return "<p>No results.</p>"
return "".join(f"<li>{item}</li>" for item in items)
Out-of-Band Swaps: Update Multiple DOM Regions at Once
A single htmx request can only target one element — that limitation trips up beginners. Out-of-band (OOB) swaps break it. Any element in the response tagged with hx-swap-oob="true" gets swapped into the matching element by ID, alongside the main target update:
@app.route("/api/items", methods=["POST"])
def add_item():
title = request.form.get("title", "")
# Save to DB, get updated count...
new_count = 42
# Primary response: new list item goes into hx-target
main = f"<li>{title}</li>"
# OOB: also update the counter badge elsewhere on the page
oob = f'<span id="item-count" hx-swap-oob="true">{new_count} items</span>'
return main + oob
Progressive Enhancement with hx-boost
Drop hx-boost="true" on any container and htmx converts every anchor and form inside into an AJAX request. URL updates, back button works, page title changes. It behaves like normal browser navigation — only the body content swaps:
<nav hx-boost="true">
<a href="/dashboard">Dashboard</a>
<a href="/settings">Settings</a>
</nav>
Fastest way to bolt SPA-like navigation onto an existing multi-page app. No routing library. No component system.
Verification & Monitoring: Debug Before You Deploy
htmx does its work silently by default — good for production, frustrating when something is not behaving as expected.
Enable htmx Logging During Development
Drop this into your page while debugging:
<script>
htmx.logAll();
</script>
Every htmx lifecycle event appears in the browser console: htmx:beforeRequest, htmx:afterRequest, htmx:beforeSwap, and htmx:afterSwap. Nine times out of ten, checking these is all you need — you see exactly what request fired, what came back, and which element was targeted.
Distinguish htmx Requests from Full-Page Requests
Every htmx request includes an HX-Request: true header. Use it to return fragments for htmx calls and full pages for direct URL access:
@app.route("/dashboard")
def dashboard():
is_htmx = request.headers.get("HX-Request")
if is_htmx:
return render_template("dashboard_content.html") # fragment only
return render_template("dashboard.html") # full page
In the network tab, filter by Fetch/XHR to isolate htmx requests. Each should return a small HTML fragment — not a full page. Seeing full HTML responses for htmx calls? That check above is what you need.
Response Headers for Server-Driven Client Control
Several response headers let your server steer client behavior without writing JavaScript:
from flask import make_response
@app.route("/api/items/<int:item_id>", methods=["DELETE"])
def delete_item(item_id):
# Delete from DB...
response = make_response("", 200)
response.headers["HX-Redirect"] = "/items" # full navigation after delete
response.headers["HX-Trigger"] = "itemDeleted" # fire a JS event on client
return response
HX-Redirect triggers a full navigation. HX-Trigger fires a JavaScript event on the client — close a modal, refresh a counter, whatever needs to happen without coupling that logic into the response body.
Pre-Launch Checklist
- Remove
htmx.logAll()calls before deploying — they add console noise in production - Confirm your server returns fragments (not full pages) when
HX-Requestis present - Test with JavaScript disabled: forms should submit normally, links should navigate (baseline progressive enhancement)
- Verify
hx-boostpages update browser history correctly by testing the back button - Add CSRF tokens globally if your backend requires them:
<script>
document.addEventListener("DOMContentLoaded", function () {
htmx.config.defaultHeaders["X-CSRFToken"] = document.cookie
.split("; ")
.find(row => row.startsWith("csrftoken="))
?.split("=")[1];
});
</script>
One security change in htmx 2.0 worth noting: htmx.config.selfRequestsOnly now defaults to true, meaning htmx only processes requests to the same origin. Migrating a 1.x project that called cross-origin endpoints? That setting is what changed.
Debugging htmx is nothing like debugging a React app. No source maps to trace. No component tree to untangle. No hydration mismatch stack traces. Open the network tab, watch the requests, read the HTML. If something breaks, you will find it in under two minutes. Ship one project with htmx and you will stop looking for the next framework to learn.
