Requests and responses

Use status codes deliberately

Distinguish success, validation failure, missing resources, and server failure so HTMX and your error handling can react correctly.

8 minute lesson

~~~

HTTP status and swap behavior are related but separate decisions.

Successful 2xx responses normally swap their HTML. 204 No Content is a deliberate exception: HTMX performs no content swap. It fits an operation whose visible result arrives through an out-of-band update or event, but do not use it when the user needs confirmation.

Error responses such as 404, 422, and 500 are not swapped by default. HTMX triggers htmx:responseError, and htmx:beforeSwap receives shouldSwap: false.

Keep accurate status codes. Do not return 200 for every failure merely to force markup into the page. Instead, explicitly allow a safe validation fragment:

document.addEventListener("htmx:beforeSwap", event => {
  if (event.detail.xhr.status === 422) {
    event.detail.shouldSwap = true
    event.detail.isError = false
  }
})

Use this only when the 422 body is designed for the target. A generic proxy error page or stack trace must not be swapped into a form.

Force each status in development and inspect the event, response body, target, and final DOM.

Lesson completed