Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 28 ยท HTMX in Practice

Events, Headers and JavaScript Integration

Hook into HTMX with htmx:configRequest and htmx:beforeSwap, steer responses with HX-Trigger, HX-Retarget and HX-Reswap, and call htmx.ajax and htmx.process.

Attributes cover most needs, but sooner or later you want to step in: add a header to every request, swap an error response that HTMX would normally ignore, show a toast when the server says "saved", or start a request from your own JavaScript. HTMX gives you two doors for this. One is a rich set of DOM events that fire at every stage of a request. The other is a set of HTTP headers that the server can send to tell HTMX what to do with a response.

Both are plain web platform features: events are ordinary CustomEvents you listen to with addEventListener, and headers are ordinary headers. In this lesson you will use the most important events, the most useful response headers, and the small JavaScript API (htmx.on, htmx.ajax, htmx.process).

Request life cycle events

htmx:configRequest Change headers and parameters before sending.
htmx:beforeSwap Decide whether and where to swap.
htmx:afterSwap New content is in the page.
htmx:responseError A 4xx or 5xx answer arrived.

Every event bubbles, so one listener on body can serve the whole page.

1 / 2

Listening to HTMX events

Listen with document.body.addEventListener, or with the shortcut htmx.on, which works the same way:

JavaScript
htmx.on("htmx:afterSwap", (evt) => {
  console.log("Swapped into", evt.detail.target);
});

Event names come in two spellings: htmx:afterSwap (camel case) and htmx:after-swap (kebab case). Both fire, and HTMX's own docs use the kebab form in attributes such as hx-on::after-swap. The evt.detail object carries what you need: the elt that triggered the request, the target, the xhr object and more, depending on the event.

The events you will use most:

Event When Typical use
htmx:configRequest Before the request is sent Add headers or parameters, such as a CSRF token
htmx:beforeRequest / htmx:afterRequest Around the request Logging, analytics, custom busy state
htmx:beforeSwap Response received, before swapping Allow or block swapping, change the target
htmx:afterSwap / htmx:afterSettle After the swap / after settling Focus, scroll, initialize widgets
htmx:responseError HTTP status 4xx or 5xx Show an error message
htmx:sendError Network failure "You appear to be offline"
htmx:targetError The target selector matched nothing Debugging typos

Changing the request

In htmx:configRequest, evt.detail.headers and evt.detail.parameters can both be edited, and the changes go out with the request. This is the right place for something that must be on every request, like an authentication header.

Add a header and a parameter to every request

Besides your own header, you can see the headers HTMX itself adds to every request: HX-Request: true, HX-Target (the id of the target) and, when present, HX-Trigger (the id of the element) and HX-Current-URL. A server can use them to return a fragment instead of a full page, as you will see in the server-side lesson.

Error responses and htmx:beforeSwap

HTMX swaps 2xx and 3xx responses, but not 204 and not 4xx or 5xx. That is a sensible default (an error page should not wipe out a working screen), yet it surprises everyone the first time a validation error with status 422 just... does nothing.

You have two ways to change the rules:

  1. A global table, htmx.config.responseHandling, a list of {code, swap, error} entries matched in order. For example, adding { code: "422", swap: true } before the catch-all makes every 422 swap.
  2. A htmx:beforeSwap listener for case-by-case decisions. Set evt.detail.shouldSwap = true to swap an error response, and optionally redirect it with evt.detail.target.
flowchart TD
    A["Response arrives"] --> B["htmx:beforeSwap"]
    B --> C{"shouldSwap?"}
    C -->|"yes"| D["Swap into target"]
    C -->|"no"| E{"status 4xx or 5xx?"}
    E -->|"yes"| F["htmx:responseError"]
    E -->|"no"| G["Nothing happens"]
    D --> H["htmx:afterSwap, then htmx:afterSettle"]

The swap decision happens in htmx:beforeSwap; unswapped errors raise htmx:responseError.

Choose what happens for each status code

Try each button. 200 swaps normally. 422 is allowed to swap into the result area. 404 is swapped too, but into the notice area instead. 500 is not swapped at all; our htmx:responseError listener shows a friendly message instead of the server's raw error text.

Never put raw server error output (stack traces, SQL) into the page. For 5xx responses, show a short, fixed message, as the demo does, and keep details in your server logs.

Telling HTMX what to do: response headers

The server can steer HTMX with headers on the response. The ones you will use most:

Header Effect
HX-Trigger Fire one or more events on the client. A plain name, or JSON with event details
HX-Trigger-After-Swap, HX-Trigger-After-Settle Same, but later in the life cycle
HX-Retarget A CSS selector that replaces the request's hx-target
HX-Reswap A swap value that replaces the request's hx-swap
HX-Reselect A selector, like hx-select, chosen by the server
HX-Push-Url / HX-Replace-Url Update the address bar (a URL, or false to prevent it)
HX-Redirect Do a full page redirect to a URL
HX-Location Navigate with an HTMX-style swap instead of a full reload
HX-Refresh true reloads the whole page

HX-Trigger is the bridge between server and client code. A save endpoint can answer HX-Trigger: {"toast": {"message": "Saved!"}}. HTMX then fires a toast event on the element that made the request, with {message: "Saved!"} in evt.detail. Your listener decides how to display it. The server never needs to know how toasts look.

HX-Trigger, HX-Retarget and HX-Reswap

"Save" swaps its text into the main area and also fires a toast event, which your own listener turns into a message. "Warn" asks for #main but the response redirects it to #side and changes the swap to beforeend, so repeated clicks append warnings to the side area.

HX-Redirect and HX-Location navigate away from the page, and HX-Push-Url changes the address bar. The preview sandbox does not allow navigation or history changes, so those headers are described here but not run. See URLs, History and Navigation.

Calling HTMX from JavaScript

htmx.ajax(verb, path, options) issues a request from code and swaps the response like an attribute-driven one. It returns a promise. The options can be a target selector string, or an object with target, swap, source, values, headers, select and handler.

htmx.process(element) tells HTMX to scan an element for hx-* attributes. HTMX does this automatically for content it swaps in, and for the page at load time. But if your own JavaScript inserts new HTML (with innerHTML, a template, a third-party widget), the new hx-* attributes are dead until you call htmx.process on the new element.

htmx.ajax and htmx.process

The first button calls htmx.ajax and uses the returned promise. Insert a "Dead button" and click it: nothing happens, because HTMX never saw its attributes. Insert a "Live button" (which calls htmx.process) and it works.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where is the best place to add an authentication header to every HTMX request?

    htmx:configRequest runs before each request is sent and lets you edit its headers and parameters.
  2. 2. By default, what does HTMX do with a 422 response containing an HTML error fragment?

    4xx and 5xx responses are not swapped by default. Allow them with htmx.config.responseHandling or htmx:beforeSwap.
  3. 3. A response carries the header HX-Trigger: {"toast": {"message": "Saved"}}. What happens on the client?

    HX-Trigger fires client-side events by name, with the JSON object as the event's detail.
  4. 4. When do you need to call htmx.process(element)?

    HTMX processes swapped content automatically; HTML inserted by other code must be processed manually.
  5. 5. Which header lets the server change where the response is swapped?

    HX-Retarget is a response header holding a CSS selector that overrides the request's hx-target.

Summary

  • HTMX events bubble and carry details in evt.detail; listen with addEventListener or htmx.on.
  • Use htmx:configRequest to add headers and parameters, htmx:beforeSwap to allow or retarget error responses, and htmx:responseError for friendly failure messages.
  • By default only 2xx and 3xx responses are swapped, except 204; htmx.config.responseHandling changes that table.
  • Response headers such as HX-Trigger, HX-Retarget, HX-Reswap and HX-Push-Url let the server steer the client.
  • htmx.ajax starts requests from code; htmx.process activates hx-* attributes in HTML your own code inserted.

Continue with URLs, History and Navigation.