HTMX is a library that lets you fetch and manipulate HTML using special attributes.
<body>
<button hx-get="/version" hx-target="#version">Get Bun Version</button>
<div id="version"></div>
</body>
This would fetch the content of /version and replace the html inside the #version tag. This is a very server-side approach to creating interactive front-end applications. The same techniques are also used to drive GitHub and Livewire/Alpine, as they both render HTML partials on the server and patch them into the page with some JavaScript.
In vanilla JavaScript it would look something like this:
<html>
<button onclick="getVersion()">Get Bun Version</button>
<div id="version"></div>
<script>
function getVersion() {
fetch('/version')
.then(response => response.text())
.then(html => {
document.querySelector('#version').innerHTML = html
})
}
</script>
</html>
Here is a similar approach to fetch server generated partials using Livewire:
<body>
<button wire:click="getVersion">Get Bun Version</button>
<div>{{ $version }}</div>
</body>
The getVersion function would be run on the server:
public function getVersion(): void
{
$this->version = trim(Process::run('bun --version')->output());
}
This approach to building websites also makes testing very easy as you can easily call functions in a unit test and verify the contents.
HTMX is also very easy to use with different backend frameworks and isn’t restricted to any specific stack, as long as you can generate HTML fragments with templates. The best part is you can create interactive front-end applications without a JavaScript build step.
HTMX also provides or can enable some nice features like:
- Preloading pages
- Lazy loading content
- Live form validation
- Typeahead search
- Optimistic updates: update page before waiting for a server response
- Paginated content
- Infinite scrolling
- Polling
The author also covers the basics of security, like input sanitisation, escaping user content and preventing cross-site scripting (XSS) attacks…
A nice trick to validating the CDN library is to use an integrity check:
<script
src="https://unpkg.com/htmx.org@2.0.0"
integrity="sha384-wS5l5...ZkpCw"
crossorigin="anonymous"
></script>
That’s a neat trick to ensure the code on the CDN hasn’t been compromised.
You can also use web sockets with HTMX by importing a plugin.
The book itself is very simple, and structured a bit like a long tutorial. If you’re an experienced web developer you can probably skip it and head straight to the HTMX docs.