HX-Redirect: how to do a full redirect and avoid hx-target?
See original GitHub issueConsider this common form validation pattern:
- I have a form that gets posted to the server.
- If form validation occurs, just return the <form> content with error messages+user input and insert into the DOM.
- If form is valid, perform whatever server-side action and then redirect to another page.
So I have a form like this:
<form class="rounded border bg-white mb-3"
id="article-form"
method="post"
hx-post="/post-url/"
hx-target="this">
The server returns the form HTML correctly with errors. However, when sending a redirect, the whole page is loaded into the form tag (given the hx-target).
To get around this I’ve tried setting the HX-Redirect and HX-Refresh headers in the response, but neither appear to have any effect: the content is still loaded into the hx-target element.
Is there an idiomatic way to do this with htmx, or do I just have to go back to full server-side page reloads for validation?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:5
- Comments:5 (1 by maintainers)
Top Results From Across the Web
htmx: hx-target: swap html vs full page reload
I found this: you can use the HX-Redirect http response header to trigger a redirect on the client. I create this class for...
Read more >Attributes
HX -Redirect, can be used to do a client-side redirect to a new location. HX-Refresh, if set to "true" the client side will...
Read more >How do you use HX-Redirect ?. : r/htmx
You just need to trigger a htmx event (for example hx-get and return the hx-redirect header, and the whole page reloads.
Read more >How to do a boosted hx-redirect ? #876
For people who stumble upon this you can also use hx-target="body" hx-swap="outerHTML" hx-push-url="true" to do a boosted redirect. Beta Was this translation ...
Read more >HTTP - django-htmx 1.13.0 documentation
htmx can trigger a client side redirect when it receives a response with the HX-Redirect header. HttpResponseClientRedirect is a HttpResponseRedirect ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Two thoughts here:
If you send an
HX-Redirectheader, you want just a normal 200 response code because the redirect is going to be done server side.It sounds like you want to replace a different target on success. Would the OOB swap mechanism be acceptable for this? https://htmx.org/docs/#oob_swaps
We could add a new header,
HX-Retargetthat allows you to change the target of the response via the header. Worth considering.Yes, it should.