htmx forms and Astro View Transitions

By

Learn how to fix htmx forms that break when you enable Astro View Transitions by adding the data-astro-reload attribute so the page does not reload early.

~~~

If a form controlled by htmx stops working after you enable Astro View Transitions, add the data-astro-reload attribute to the form. That’s the fix. Let me explain why it’s needed.

I already wrote about htmx and Astro View Transitions.

But I’ve got a new tip to work with forms.

Had this issue today with a form controlled by htmx (htmx sends a POST request when this form is submitted) that was working fine until I enabled View Transitions on the site (built with Astro).

I was POSTing data to a URL like /api/project/:project_id and expected the returned HTML of this POST request to be shown in the place I wanted to, but turns out View Transitions automatically trigger a page transition and that reloads the current page:

Browser developer tools showing network requests where page reload interrupts htmx form submission

My page refreshed before htmx could handle the response from the server. I was a bit confused until I analyzed carefully my requests log server-side. The POST request arrived, the server returned the right HTML, and yet the page never showed it.

Why does this happen?

Astro’s View Transitions router doesn’t just handle links. It also intercepts form submissions, so it can animate navigation on regular forms.

The problem is that the router doesn’t know htmx already took charge of that form. Both libraries listen for the submit event. The Astro router treats the submission as a navigation and reloads the page while the htmx request is still in flight. The response comes back to a page that’s already gone.

Nothing errors out, which makes it confusing to debug. The network tab shows the POST succeeding. You have to notice the extra page load right after it.

The fix

Adding data-astro-reload to the forms fixed the problem:

<form hx-post="/api/project/42" data-astro-reload>
  ...
</form>

The attribute tells the Astro router to leave that form alone. With the router out of the way, htmx intercepts the submit like it always does, prevents the browser’s default navigation, and swaps the returned HTML into the target element.

Nothing reloads, and the form works exactly like it did before View Transitions were enabled. The rest of the site keeps its animated transitions.

Remember to add the attribute to every htmx-controlled form on the site, not just the one you’re testing. Any form you miss will show the same silent failure.

Tagged: Astro, htmx · All topics
~~~

Related posts about astro: