HTMX And POST Redirects

I tend to be stuck in my old ways when writing POST handlers. When I accept a POST request from a HTML page, I send a 303 See Other redirect to force the browser to get the resulting page with a GET. This keeps the path routing relatively clean, and saves me from having multiple handlers return the same bit of HTML.

This technique broke down when I started using HTMX. I found that redirects stopped working reliably when posting a form decorated with HTMX’s AJAX attributes. The HTML will be properly replaced, but I couldn’t get the browser to adopt the new URL in it’s address bar.

After poking around the documentation, I found that HTMX has their own form of redirects, sent using their HX-Redirect header. I tried using this, along with sending a 204 No Content in response to a post, and redirects began to work again, complete with the correct URL in the address bar.

Granted, this may not be within the “spirit” of HTMX, since it’s doing a full refresh of the page (I should probably state that the page the browser is sent to doesn’t load HTMX, which maybe why the URLs weren’t being updated now that I think about it). But for a web app used exclusively for myself, it works well enough.