Putting the hyper into hypermedia: htmx 4 in Drupal
Table of Contents
This article at a glance…
Who is this for?
- Drupal developers
Why should I read this?
htmx was added to Drupal core in version 11.2, and has been fully integrated since 11.3. One significant implementation of this is the community initiative to replace the AJAX API and jQuery reliance.
htmx 4 was released in August 2026 and brings some new features and some breaking changes. htmx 4 is expected to ship with the Drupal 12 release.
This post provides some background to htmx for those who are new to it, and some examples of how it can be used in Drupal—including some key changes coming with htmx 4.
hypermedia and htmx
htmx is a small JavaScript library that was developed to extend HTML as hypermedia. It attempts to respond to the following limitations of current HTML:
- Any element should be able to send a request, not just
<a>and<form>elements. - Any event should be able to trigger HTTP requests.
- HTML should allow all HTTP methods, not just GET and POST.
- HTML could replace parts of a document, rather than the whole thing.
htmx does these things by adding attributes to HTML elements. The example below is a simple <button> element using htmx. Note the use of the hx-* attributes:
<button hx-get="/locations" hx-trigger="click" hx-target="#locations-list" hx-swap="innerHTML"> See locations</button>
<ul id="locations-list"> <li>Locations will display here.</li></ul>In this example, clicking the button will send a GET request to the /locations endpoint. The server would return an HTML fragment (in this case some <li> items) that would display in the list.
The key here is that the request and response are handled by HTML, instead of JSON.
In this simple way, htmx allows you to create dynamic front-ends that update from interactions with the server.
So what?
There are many tools that allow dynamic front-ends and Single Page Application behaviour—so what makes hypermedia and htmx different?
The most powerful argument for me is its simplicity. It responds to front-end frameworks that are increasingly complex and in constant churn. Leveraging hypermedia—one of the original web technologies—feels freeing.
It also responds to issues arising from JSON API changes that can break existing systems.
Using HTML in this way returns us to RESTful architecture in its original definition by Roy Fielding. One advantage of doing so is that hypermedia becomes the engine of the application state (HATEOAS). No need for API documentation; no need for my application to grab the state from another location. Everything needed is in the request and the response.
htmx in Drupal
htmx is a great option to have in Drupal. Drupal can handle the complex server logic and then return the HTML for us to output via htmx. Twig is a natural fit.
It is no wonder, then, that htmx was seen as a suitable solution when planning to replace the existing AJAX API. Drupal 11.3 saw the full integration of htmx 2 and htmx 4 is intended to be released with Drupal 12.
You could implement our earlier button example in Twig, with some minor additions:
{{ attach_library('core/drupal.htmx')}}
<button data-hx-get="{{path('my_module.my_path')}}" data-hx-trigger="click" data-hx-target="#locations-list" data-hx-swap="innerHTML"> See locations</button>
<ul id="locations-list"> <li>Locations will display here.</li></ul>Drupal uses data-* prefixes and can have the library attached directly.
Alternatively, you can create an htmx object in a controller for rendering:
(new Htmx()) ->get(Url::fromRoute('my_module.my_path')) ->trigger('click') ->target('#locations-list') ->applyTo($button);Ensuring an htmx response
There are a few ways to determine whether a request is an htmx request or not. This is useful because, for example, you may wish to render a full page output at a path on a ‘normal’ HTTP request, but only return an HTML fragment when the user interacts with the page and sends an htmx request. When Drupal identifies an htmx request, it will use a htmxRenderer which will omit the surrounding page.
HtmxRequestInfoTrait::isHtmxRequest()
Probably the easiest to use, this returns a boolean to allow you to branch your actions:
use Drupal\Core\Htmx\HtmxRequestInfoTrait;
if ($this->isHtmxRequest()) { // Return only the fragment htmx will swap in.}else { // Return the full page.}FormBase already includes this trait, so it can be used without having to be added.
Set an htmx route
A route that includes _htmx_route: TRUE will operate in the same way, wrapping the response appropriately and only returning an htmx fragment.
There are some upcoming changes to the way routing is handled, but in 11.3, it might look like:
htmxdemo.dashboard.card_add: path: "/htmxdemo/dashboard/card" defaults: _controller: '\Drupal\htmxdemo\Controller\HtmxdemoDashboardController::addCard' methods: [POST] requirements: _permission: "access content" _csrf_request_header_token: "TRUE" options: _htmx_route: TRUEWhile on Drupal 11.4+, it will use the new attribute method, with the htmx route set under options:
use Drupal\Core\Routing\Attribute\Route;use Drupal\Core\StringTranslation\TranslatableMarkup;
#[Route( path: '/htmxdemo/dashboard/card', name: 'htmxdemo.dashboard.card_add', title: new TranslatableMarkup('htmx Dashboard'), // D12 specific methods: ['POST'], requirements: [ '_permission' => 'access content', '_csrf_request_header_token' => 'TRUE', ], options: [ '_htmx_route' => TRUE, ],)]public function addCard(): array { // Build the card fragment.}onlyMainContent()
htmx in Drupal also has a special method ::onlyMainContent(), which will wrap a response in the drupal_htmx wrapper format (a minimal HTML document containing only status messages and the main content, plus any new CSS/JS), rather than returning the whole page. We can add to our button example from earlier:
(new Htmx()) ->get(Url::fromRoute('my_module.my_path')) ->onlyMainContent() ->trigger('click') ->target('#locations-list') ->applyTo($button);HX-Request in the request headers
You can also look at the request headers for the use of HX-Request and decide the logic based on that.
use Symfony\Component\HttpFoundation\Request;
public function foo(Request $request): array { if ($request->headers->get('HX-Request') === 'true') { // Return only the fragment htmx will swap in. } // Return the full page.}htmx 4 in Drupal
There are a number of changes between htmx 2 and htmx 4, some of which will potentially deprecate your existing code.
This change record on Drupal.org summarises what is new, and provides the links to the htmx documentation.
Under the hood, the big change is that XMLHttpRequest is replaced with fetch(),
but if you are using the library via Drupal, this probably won’t affect you
very much.
We’ll focus on the following changes, as I haven’t read too much about them elsewhere:
- Inheritance is no longer implied
<hx-partial>as an alternative tohx-swap-oobhx-query
Changes to inheritance
For those of you who have not yet had much of a chance to work with htmx, this change might not mean much. I think it’s important to flag it, as those who have might see issues with existing features if the changes to inheritance are not made.
In htmx 2, applying an attribute to a parent element meant that it was inherited by its children. In this example, the hx-target added to the parent <div> would be passed on to the <button>:
<div data-hx-target="#results"> {% for item in items %} <button data-hx-get="{{ path('my_module.item', {'id': item.id}) }}"> {{ item.label }} </button> {% endfor %}</div>
<div id="results"></div>But now we need to explicitly mark inheritance using :inherited:
<div data-hx-target:inherited="#results"> {% for item in items %} <button data-hx-get="{{ path('my_module.item', {'id': item.id}) }}"> {{ item.label }} </button> {% endfor %}</div>In Drupal, we can ensure this renders on the element by adding a $modifier to the method like so:
(new Htmx()) ->target('#someId', Htmx::INHERITED) ->applyTo($form['someWrapper']);This will ensure inheritance. If you have htmx features and are moving from an earlier version into Drupal 12 and they have stopped working—this might be the reason.
<hx-partial>
hx-partials are cool. I feel like they have a real opportunity to help developers build dynamic web applications in a really simple way.
In a nutshell, hx-partial allows you to target multiple elements for replacement in a response. They operate like <template> elements from HTML and are similar to htmx’s own hx-swap-oob. The difference is that rather than marking the returned element itself as out-of-band, each partial is a wrapper that states where its contents should go.
Take an example where you have a button that sends a request to the server which generates a number between 1 and 6 as {{roll}}:
{# partial.twig #}
<button data-hx-get="{{ path('htmxdemo.partials_roll') }}" >Roll</button>
<h3>Latest roll</h3><p><output id="roll-latest">-</output></p>
<h3>History</h3><ol id="roll-history"></ol>The server takes {{roll}} and then returns the following Twig file:
{# partial_response.twig #}
<hx-partial hx-target="#roll-latest" hx-swap="innerHTML">{{ roll }}</hx-partial><hx-partial hx-target="#roll-history" hx-swap="beforeend"><li>{{ roll }}</li></hx-partial>With the two separate hx-targets, we can update the original HTML in two places, and in two different ways.
Extending this thinking, we could have very dynamic front-end displays from a single response.
hx-query
There are a number of new attributes added in htmx 4, but one of the more interesting ones is the introduction of hx-query, which uses the QUERY method as an HTTP verb.
The HTTP spec recently adopted this in RFC 10008, adding the new method to better handle the way queries (like those added to a search input) are handled.
QUERY helps to overcome issues when using either GET or POST. With GET, long strings in query parameters can be rejected by the server. The workaround was to use POST, but POST is not declared safe or idempotent, so browsers can’t cache the response or automatically retry it.
QUERY overcomes these issues by adding the query to the content of the request, like POST, while being defined as safe and idempotent like GET.
Wrapping up
I hope this has inspired you to investigate htmx in Drupal further. It’s a powerful, lightweight, and easy-to-use tool that I think can make our sites more dynamic with far less effort.