Five Minutes with htmx — A New Spin on an Old Reliable Architecture
First a quick review of pros and cons of SPAs vs. MPAs:
- Better performance and user experience since full pages aren’t constantly being loaded. Assets are loaded once and only JSON data is sent between the client and server.
- Separation of concerns since the same backend code can be used for web and native mobile.
- SEO Optimization is tricky
- Easier SEO Optimization
fragments often convolute the development process and code).
- No separation of concerns. Front- and back-end are tightly coupled together.
- User experience suffers because full pages tend to be loaded and overall front-end UI is slower.
Let’s now discuss htmx. For a description from the website — “htmx gives you access to AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, using attributes, so you can build modern user interfaces with the simplicity and power of hypertext.”
Here’s a basic example:
<div><h1>Simple htmx demo</h1></div> <button hx-post="https://htmxdemo.herokuapp.com/demo/?curr_num=0" hx-swap="outerHTML">Click Me</button></body>
Quite simply when the user clicks the button, we are using html (declarative) attributes from htmx including hx-post to post the URL and then hx-swap to replace the returned html snippet from the server with the current button html.
Here is the live version where the button is being replaced by the server without replacing the full page. Implementation is an html page making a post request against a Flask server hosted on Heroku (GitHub source).
Obviously not very exciting since you’ve already seen AJAX working many years ago and you were wowed then because you weren’t used to seeing such dynamic requests from the webpage. This is really no different but now we are using just html for the front-end; simple and clean.
I was going to put together a bunch of examples, but the htmx website has terrific simple examples that are clear to understand. Let me point out a few:
Here is a listing of great htmx resources:
- htmx website
- Htmx with server-side examples (e.g., Rails, .NET, Java/Spring)
- Htmx and Django instruction videos
- Port of React to htmx — “They reduced the code base size by 67%”
- Sizable list of resources related to using htmx with several popular tech stacks
- Htmx alternatives: Hotwire/Turbo and Unpoly
What do you think about htmx? Have you tried using it in any applications? How did it work out?