Advantage of using HTMX is it feels like snappy. Since I am a backend developer in Python I have used HTMX in Django and Flask. But you can also use this in any server side frameworks including Ruby on Rails and ExpressJS. Or anything that server HTML from the server can use HTMX.
When I was developing the application I come across this problem. I need to redirect the user from server side to different page. But HTMX is making Ajax request on the front and getting response from the backend to change the HTML on the run. So to make this happen HTMX support headers. It will scan for
HX-Redirect header present in the response headers if it is then it will make the redirect.
In this blog I’m going to explain this concept in details you can use this in your backend framework.
Make the request
You know that making the HTTP request in HTMX is easy as pie. All you need to do is use the
<div hx-get="/logout">Logout button</div>
Unlike regular response from the server you need to tell the HTMX to make the redirect.. You can use backend code for that.
Tell HTMX to make the redirect
In server side when you return the response you can add the HTTP headers. Saying that you wish to redirect the user to different page and HTMX will take care of the redirection for you.
def whatever_function(): response = HttpResponse("Okay) # reverse("home:index") is "/home" response["HX-Redirect"] = reverse("home:index") return response
I have used Django framework code for the above example but the code is very same to other framework as well.
And that’s it. Now whenever users clicks the button user will redirected to main page.