Requests and responses
Control the result with response headers
Use an HX- response header when the server knows the correct target, swap, history update, event, refresh, or redirect.
Response headers let the server refine what should happen after it knows the result. Markup sets the default behavior. Headers adjust that behavior when the outcome depends on server-side logic.
A failed create can send its form to an error region:
HTTP/1.1 422 Unprocessable Content
HX-Retarget: #task-form
HX-Reswap: outerHTML
Content-Type: text/html
Other useful controls include:
HX-Push-UrlandHX-Replace-Urlfor historyHX-Triggerfor a named browser eventHX-Refresh: truefor a full refreshHX-Redirectfor a full client redirectHX-Locationfor an HTMX-style navigation
Use headers when the server result determines the behavior. Keep stable defaults in markup when the behavior belongs to the component regardless of outcome. A search box that always targets #results should say so in hx-target, not in a header you might forget on one route.
HTMX-specific response headers are not processed on an ordinary 3xx response because the browser follows the redirect before HTMX sees the original headers. Return an appropriate non-3xx response when using HX-Redirect or HX-Location. This trips people up when they reuse an existing redirect helper that always sends 302.
Do not turn headers into an invisible application protocol. Inspect and document the small set each endpoint may return. If a route sometimes sends HX-Trigger and sometimes HX-Refresh, write that down where your team can find it. Future you will not remember from the markup alone.
Response headers are also useful when one route serves multiple HTMX controls. The markup might share a generic target, and the server can retarget to a detail panel only when the create succeeded.
Try this on your own project: return HX-Trigger from one successful POST and listen for the event in a small document.addEventListener handler.
Lesson completed