htmx, redirect after request

By

Two ways to redirect after an htmx request: a client-side redirect on the afterRequest event (htmx 2 and htmx 4 names), or the cleaner HX-Redirect response header.

~~~

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>

That’s the htmx 2 event name. htmx 4 renamed it to htmx:after:request, so there the same code becomes:

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

Check which major you load before picking the name. As of September 2026 the latest tag on npm still points at htmx 2 (2.0.10), and htmx 4 sits on the next tag, so you only get it with htmx.org@4.

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 /. This header is unchanged in htmx 4, so it works the same on both majors.

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.

Tagged: htmx · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about htmx: