How to redirect from server side in HTMX

Published 30 Jun, 2022

Reading time: 2 Mins


HTMX works like Ajax request but in this blog post I have explained a way to redirect the user from server side.

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 hx-get method.

<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.

Conclusion

And that’s it. Now whenever users clicks the button user will redirected to main page.

This article published under development on htmx tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.