Malhar Ujawane

Blog

Explainer·(updated October 31, 2026)

What is htmx? Hypermedia-driven web apps, explained

htmx is a small JavaScript library that lets HTML attributes make AJAX requests and swap in HTML from the server. How it works, with a runnable Python backend.

What is htmx? Hypermedia-driven web apps, explained

htmx is a small, dependency-free JavaScript library that lets any HTML element issue an HTTP request and swap the server’s HTML response into the page, using attributes like hx-post, hx-target and hx-swap instead of JavaScript you write. The server returns HTML fragments, not JSON, so the application state lives on the server and the browser stays a hypermedia client. The docs put it in one line: “htmx is a library that allows you to access modern browser features directly from HTML, rather than using javascript.”

What problem does htmx solve?

The htmx home page frames it as four questions about plain HTML:

  • “Why should only <a> & <form> be able to make HTTP requests?”
  • “Why should only click & submit events trigger them?”
  • “Why should only GET & POST methods be available?”
  • “Why should you only be able to replace the entire screen?”

Remove those four limits and a lot of what people reach for a single-page app framework to do (inline edits, live search, infinite scroll, partial reloads) becomes an attribute on an element. The library describes itself as “small (~16k min.gz’d), dependency-free, extendable”, and the home page calls it “the successor to intercooler.js.”

The deeper claim is architectural. Because responses are HTML, the docs say htmx “keeps you firmly within the original web programming model, using Hypertext As The Engine Of Application State.” HATEOAS is the REST constraint most JSON APIs quietly drop: the server tells the client what it can do next by sending links and forms, so the client does not need its own copy of the application’s state machine.

How does htmx work?

You add attributes; htmx reads them, listens for events and does the request and the DOM swap. The example from the home page:

<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.11/dist/htmx.min.js"></script>
<!-- have a button POST a click via AJAX -->
<button hx-post="/clicked" hx-swap="outerHTML">
  Click Me
</button>

On click, htmx sends POST /clicked and replaces the whole button with whatever HTML comes back. Five attributes cover most apps:

  1. hx-get, hx-post, hx-put, hx-patch, hx-delete: each “takes a URL to issue an AJAX request to.” All five HTTP verbs, from any element.
  2. hx-trigger: which event fires the request. The default for a button is click, for a form is submit, and you can say things like keyup changed delay:500ms for a search box.
  3. hx-target: where to put the response, as a CSS selector. Without it, the element that made the request is the target.
  4. hx-swap: how to put it there: innerHTML (the default), outerHTML, beforeend for appending to a list, and so on.
  5. hx-select and friends, for cutting out part of a response. You will need these less often.

htmx also adds request headers so the server can tell an htmx request from a full page load. The one you use most is HX-Request: true.

What does an htmx backend look like?

Any language that returns HTML works, which is the point. Here is a complete todo backend in Python’s standard library. The page has one form; htmx posts it and swaps in a new list. The script starts the server, then makes the same request htmx would make, and the same request a browser with JavaScript off would make.

# htmx_server.py: an htmx backend in the stdlib. It returns HTML fragments, not JSON.
import html, threading, urllib.request, urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TODOS = ["write the spec"]

def todo_list():
    items = "".join(f"<li>{html.escape(t)}</li>" for t in TODOS)  # escape user input
    return f'<ul id="todos">{items}</ul>'

PAGE = f"""<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.11/dist/htmx.min.js"></script>
<form action="/todos" method="post" hx-post="/todos" hx-target="#todos" hx-swap="outerHTML">
  <input name="title"><button>Add</button>
</form>
{{list}}"""

class Handler(BaseHTTPRequestHandler):
    def send(self, body):
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        self.wfile.write(body.encode())

    def do_GET(self):
        self.send(PAGE.replace("{list}", todo_list()))

    def do_POST(self):
        form = urllib.parse.parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode())
        TODOS.append(form["title"][0])
        # htmx sends HX-Request: true; a plain form post gets the full page instead
        self.send(todo_list() if self.headers.get("HX-Request") else PAGE.replace("{list}", todo_list()))

    def log_message(self, *a): pass

srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{srv.server_port}/todos"

# What the browser does when htmx submits the form:
data = urllib.parse.urlencode({"title": "<b>ship it</b>"}).encode()
req = urllib.request.Request(url, data=data, headers={"HX-Request": "true"})
print("htmx POST ->", urllib.request.urlopen(req).read().decode())
# The same form without JavaScript still works and gets a whole page:
plain = urllib.request.urlopen(urllib.request.Request(url, data=urllib.parse.urlencode({"title": "test"}).encode())).read().decode()
print("plain POST ->", len(plain), "bytes, full page:", plain.startswith("<script"))
srv.shutdown()

Output (Python 3.13.11):

htmx POST -> <ul id="todos"><li>write the spec</li><li>&lt;b&gt;ship it&lt;/b&gt;</li></ul>
plain POST -> 321 bytes, full page: True

Three things to see in that output. The htmx response is a fragment, only the list that changed. The <b> tag the user typed came back escaped, because the server is now rendering user input into HTML and owns XSS prevention. And the form has a normal action and method, so with JavaScript off it still posts and gets a full page. That is progressive enhancement for free, and it falls out of the design rather than being bolted on.

There is no client-side model, no JSON schema, no fetch wrapper and no state sync. The list on screen is whatever the server last rendered.

htmx vs React: when should you use which?

Carson Gross’s essay When Should You Use Hypermedia? (October 23, 2022) is unusually honest about the limits, which is why I trust it. Hypermedia is a good fit for text-and-image UIs and for CRUD: “If your main application mechanic is showing forms and saving the forms into a database, hypermedia can work very well.”

It names where it is a poor fit. A spreadsheet, where a user “can enter an arbitrary function into a cell” and cells depend on each other dynamically, so it is “untenable to issue a server request on every cell update”. Google Maps, which “simply can’t afford a server round trip” for every mouse movement. And offline: if you need full functionality without a network, hypermedia “is not going to be an acceptable one.” For offline, look at CRDTs and local-first software instead.

React, especially with Server Components, has moved toward the same idea from the other side: render on the server, ship only the interactive islands. The difference is where the islands are written. In htmx, interactivity is attributes plus small scripts, and the server can be Python, Go or anything. In RSC, the islands are React components and the server is JavaScript.

From the front-end lead seat I had on an e-commerce site, my take is that most of a commerce site (category pages, product detail, account pages, checkout forms) is the CRUD-and-content shape the essay describes. The parts that are not, such as a product configurator with live price recalculation, are exactly the cases the essay says to hand to JavaScript.

What changed in htmx 2?

htmx 2.0.0 ended Internet Explorer support and “tightens up some defaults.” The changes that bite on upgrade: extensions moved to their own repository with their own versions; hx-sse and hx-ws were removed in favor of extensions; the old hx-on syntax became hx-on:; DELETE requests now send parameters in the URL instead of a form body; and selfRequestsOnly now defaults to true, so htmx will only make requests to the page’s own origin unless you opt out. The current docs reference 2.0.11.

Where does htmx break?

XSS moves to the server, and gets sharper. In a JSON API, unescaped text usually lands in a React text node and is harmless. In htmx, the server writes HTML, and any attribute starting with hx- in that HTML is live. The docs’ rule is to “escape all 3rd party, untrusted content that is injected into your site,” and hx-disable on a container prevents “processing of all htmx attributes on a given element, and on all elements within it.” Put it around user-generated content. The same rule, never let untrusted text become instructions, is the core of prompt injection defense too. Add a Content Security Policy, which the docs recommend so you can “tell the browser to, for example, not issue requests to non-origin hosts.”

Server round trips are the unit of interaction. Every interaction that changes the screen is a request. On a slow mobile connection that is visible. Use hx-indicator for feedback and keep pure UI toggles (open a menu, switch a tab with no data) in CSS or a few lines of script.

Endpoint sprawl. Each fragment is an endpoint. Without discipline you end up with dozens of tiny routes that each render one partial. A template engine with named partials and a convention for “full page if no HX-Request, fragment if yes” keeps it sane, as in the example above.

Client-side state that is truly rich. Drag-and-drop canvases, collaborative editors, maps, anything at 60 frames per second. That is not what htmx is for, and the essay says so.

What I would do

For an internal tool, an admin panel, a back office or a content site, I would start with server-rendered HTML and htmx, in whatever backend language the team already writes. You skip a JSON API, a client state layer and a build step, and the team that owns the data owns the UI. If a single widget outgrows it, mount a small JavaScript component there and leave the rest alone.

For a product where the core interaction is real-time, spatial or offline, I would not start with htmx. I would also not start with a full SPA for the account settings page of that product.

Whatever the choice, I would write the escape and hx-disable rule into the code review checklist on day one, because with htmx the template is the security boundary.

FAQ

Is htmx a framework?

No. It is a library you include with one script tag. It has no build step, no components and no client state. Your server-side framework does the routing and rendering.

Does htmx replace JavaScript?

It replaces the JavaScript you would write to fetch data and update the DOM. You still use JavaScript for pure client behavior; the htmx team also makes hyperscript, which the docs call “an experimental front-end scripting language”, but plain JS works fine.

Can I use htmx with Django, Rails, Go or Flask?

Yes. htmx only needs HTML over HTTP, so any backend that renders templates works. The Python example above uses nothing but the standard library.

Is htmx good for SEO?

Server-rendered HTML is what crawlers read most reliably, so pages built this way start in good shape. Content that only appears after an htmx request is not in the initial HTML, so keep primary content in the first render.

Is htmx production-ready?

htmx 2.0 is a stable major release with documented upgrade notes. The more useful question is whether your app’s interactions fit hypermedia; the When Should You Use Hypermedia? essay is the best checklist.

Sources

Get new posts in your inbox

© 2026 Malhar Ujawane. Built with Astro.