Skip to content

htmx, redirect after request

New Course Coming Soon:

Get Really Good at Git

On a site using htmx I had the need of redirecting to the homepage (/) after I did a network DELETE request to the server.

A first implementation I did involved client-side redirect by listening to the htmx:afterRequest event.

The event happened after clicking a button with id button-delete-project, so I used this code:

<script>
  document.addEventListener('htmx:afterRequest', 
    function (event) {
    if ((event as CustomEvent).detail.target.id === 
      'button-delete-project') {
       window.location.href = '/'
    }
  })
</script>

An alternative approach, the one I decided to go for, involved setting a custom htmx header in the server response.

After deleting an item, I set the HX-Redirect HTTP header to /.

Using an Astro route, I used this code:

if (Astro.request.method === 'DELETE') {
  await deleteProject(id)

  return new Response(null, {
    status: 204,
    statusText: 'No Content',
    headers: {
      'HX-Redirect': '/',
    },
  })
}

After doing the HTTP request, htmx automatically redirects to that URL, client-side.

You can set a wide variety of custom headers in the response, to do many interesting things like this one, for which you might think you’d have to write custom code, but it’s all built-in for you.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my HTMX Tutorial on The Valley of Code

Here is how can I help you: