#What is the correct way to do a redirect in an Astro action?

1 messages · Page 1 of 1 (latest)

light sun
#

As the title indicates: What is the correct way to do a redirect in an Astro action?

frozen nebulaBOT
#

Hi @light sun. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To redirect from an Astro action, you have several options depending on your specific use case:

Redirecting from an action handler

When handling an action in your action definition file, you can return the redirect information as part of your action result. Then, in your Astro component, you can check this result and perform the redirect:

// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';

export const server = {
  createProduct: defineAction({
    accept: 'form',
    input: z.object({ /* ... */ }),
    handler: async (input) => {
      const product = await persistToDatabase(input);
      return { id: product.id };
    },
  })
}

Then in your Astro component:

---
import { actions } from 'astro:actions';

const result = Astro.getActionResult(actions.createProduct);
if (result && !result.error) {
  return Astro.redirect(`/products/${result.data.id}`);
}
---
<form method="POST" action={actions.createProduct}>
  <!--...-->
</form>

This approach works well for HTML form submissions as described in the Astro documentation.

Client-side redirects

If you're calling actions from client-side JavaScript, you can use Astro's navigate() function to redirect after a successful action:

import { actions } from 'astro:actions';
import { navigate } from 'astro:transitions/client';

export function LogoutButton() {
  return (
    <button onClick={async () => {
      const { error } = await actions.logout();
      if (!error) navigate('/');
    }}>
      Logout
    </button>
  )
}

This approach is useful when you want to handle client redirects after an action completes.

#

Important note about Astro v5 changes

In Astro v5, there was a breaking change to how actions submitted by HTML forms handle redirects. Previously, actions called from HTML forms would trigger a redirect with results forwarded using cookies. In v5, actions now render the result as a POST result without automatic forwarding.

If you need to preserve the redirect behavior or avoid the "confirm form resubmission" dialog on page refresh, you can implement custom middleware as described in the v5 upgrade guide.

For more advanced use cases, you can also persist action results with a session using middleware.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: