CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software // CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software

Getting started with htmx

Cover for Getting started with htmx

Getting started with HTMX

All aboard the hypetrain because a new frontend framework just dropped!

HTMX Logo

Image: HTMX Logo

HTMX?

HTMX is a small (14kb) javascript library, that runs client-side in the browser. It's main promise is to expand the current existing html tags by adding attributes to them. In this way, it expands on the existing HTML capabilities and grants access to AJAX, CSS Transitions, WebSockets and Server Sent Events from your HTML.

Frontend

Consider the following index.html file, which is served to the client. It contains a script tag which downloads the HTMX library from UNPKG.

Next up is a button tag, which includes 2 attributes that are specific to HTMX:

  • hx-post='clicked' specifies an endpoint that will receive a post request when clicked.
  • hx-swap='outerHTML' specifies which part of the HTML needs to be replaced by the response from the endpoint. In this case the outerHTML from the button gets replaced.

// HTML //

Frontend

At the backend we need an api that returns html. Multiple backend technologies are possible, but for the sake of demonstration I've set up a Node Express REST API. The API has a single endpoint that accepts a POST request, and returns the button HTML again, but with an updated counter.

// JAVASCRIPT //

Each time the user presses the button, a counter is updated and the new button tag is returned. This is a minimal example, as many more attributes are available. The HTMX example page showcases a lot of UI and UX patterns ands their implementation with UI/UX.

Conclusion

HTMX is a new library that goes back to the old approach of rendering HTML on the server. While I've never tried to create an entire web application using HTMX, it sure does offer an interesting perspective on front-end technologies!