DEV Community

Cover image for Redirecting the browser using HTMX
TimEngleSF
TimEngleSF

Posted on • Updated on

Redirecting the browser using HTMX

I am currently working on creating my own blogging platform using Go, Templ, and HTMX that I will be hosting myself. I decided this would be a fun and useful project to tackle that will also help me gain knowledge of this stack. In this blog post, I will share my experience and solutions to a challenge I faced with handling redirects using HTMX.

Redirecting the browser

While wrapping up the functionality for the admin, I decided it was time to finally start implementing HTMX into the project. I began with a button element that would send a POST request to my logout handler. Typically, I would accomplish this task using a form element, but as I mentioned, it's time to start implementing HTMX into the project. The issue is I want this POST action to still behave like a form and have the response from the server be a redirect back to the / endpoint.

Issue: handling redirect with http.Redirect

Here's the button element I used:

<button hx-post="/logout" hx-trigger="click">Logout</button>
Enter fullscreen mode Exit fullscreen mode

The issue I encountered was that the response for the redirect is still HTML, and HTMX swaps this content for the logout button element.

Handling the redirect with http.Redirect

func (app *application) handleLogoutPost(w http.ResponseWriter, r *http.Request) {
    // handle business logic...
    //...

    http.Redirect(w, r, "/", http.StatusSeeOther)
}
Enter fullscreen mode Exit fullscreen mode

Image: The content has been swapped with the Logout button
The content has been swapped with the Logout button

Solution: using HX-Redirect header

The swapping of content can be prevented by replacing the http.Redirect with an HX-Redirect header in the response and the target location as its value.

func (app *application) handleLogoutPost(w http.ResponseWriter, r *http.Request) {
    // handle business logic...
    //...

    // Write our HX-Redirect header with location and redirect
    w.Header().Set("HX-Redirect", "/")
    w.WriteHeader(http.StatusNoContent)
}
Enter fullscreen mode Exit fullscreen mode

Image: The browser has been redirected to "/" note the url.

The browser has been redirected to  raw `/` endraw  note the url.

Conclusion

The process of building my own blogging platform with Go, Templ, and HTMX has been a rewarding experience so far. By integrating HTMX, the site will be able to still have many of interactivity features if a modern website without having to write and serve extra javascript code. Handling redirects with the HX-Redirect header was a simple and effective solution. I hope this post helps anyone with their projects and encourages you to explore the potential of HTMX in your web applications.

Top comments (0)