Building a Single-Page App with htmx

Jake Lazaroff October 7, 2024
Source
People talk about htmx as though it's saving the web from single-page apps. React has mired developers in complexity (so the story goes) and htmx is offering a desperately-needed lifeline. htmx creator Carson Gross wryly explains the dynamic like this: no, this is a Hegelian dialectic: thesis: traditional MPAs antithesis: SPAs synthesis (higher form): hypermedia-driven applications w/ islands of intereactivity Well, I guess I missed the memo, because I used htmx to build a single-page app. It's a simple proof of concept todo list. Once the page is loaded, there is no additional communication with a server. Everything happens locally on the client. How does that work, given that htmx is focused on managing hypermedia exchanges over the network? With one simple trick: the "server-side" code runs in a service worker. Briefly, a service worker acts as a proxy between a webpage and the wider Internet. It intercepts network requests and allows you to manipulate them. You can alter requests, cache responses to be served offline or even create new responses out of whole cloth without ever sending the request beyond the browser. That last capability is what powers this single-page app. When htmx makes a network request, the service worker intercepts it. The service worker then runs the business logic and generates new HTML, which htmx then swaps into the DOM. There are a couple of advantages over a traditional single-page app built with something like React, too. Service workers must use IndexedDB for storage, which is stateful between page loads. If you close the page and then come back, the app retains your data — this happens "for free", a pit of success consequence of choosing this architecture. The app also works offline, which doesn't come for free but is pretty easy to add once the service worker is set up already. Of course, service workers have a bunch of pitfalls as well. One is the absolutely abysmal support in developer tools, which seem to intermittently swallow console.log and unreliably report when a service worker is installed. Another is the lack of support for ES modules in Firefox, which forced me to put all my code (including a vendored version of IDB Keyval, which I included because IndexedDB is similarly annoying) in a single file. This is not an exhaustive list! I would describe the general experience of working with service workers as "not fun". But! In spite of all that, the htmx single-page app works. Let's dive in! Behind the Scenes Let's start with the HTML: This should look familiar if you've ever built a single-page app: the empty husk of an HTML document, waiting to be filled in by JavaScript. That long inline

Discussion in the ATmosphere

Loading comments...