0

I'm working with Astro and I love it, but there is something that I don't know if I'm doing in the right way or not.

I just created a form with a POST method and an action

<form method="POST" action={actions.user}>
  <input type="text" name="name" />
  <button type="submit"> Submit </button>
</form>

and an action like this

import type { APIContext } from 'astro';

import { defineAction, type ActionAccept } from 'astro:actions';
import { z } from 'astro:schema';

type InputType = z.infer<typeof inputSchema>;

const inputSchema = z.object({
  name: z.string().min(1),
});

export const server = {
  user: defineAction({
    accept: 'form' as ActionAccept,
    input: inputSchema,
    handler: async (input: InputType) => {
      const { name } = input;
      console.log('test!', name);
      return { status: 200 };
    },
  }),
};

It works very well, as expected, but the problem is that every time I submit the form, Astro adds a _action query param to the URL. If the user reloads the browser, it reruns the action, and I think it's not a good thing, so I would like to avoid it. I tried to redirect the user from the action or similar, but nothing worked, do you know how can avoid this behaviour?

Project with the code and example: https://stackblitz.com/edit/astro-actions-test?file=src%2Factions%2Findex.ts Demo: https://astroactionstest-lfcr--4321--5a421e5b.local-corp.webcontainer.io/

If you write the name phillip, you will get this URL: https://astroactionstest-lfcr--4321--5a421e5b.local-credentialless.webcontainer.io/?_action=phillip. According to the browser, if you reload, you will get this

enter image description here

And the action will run again, so, how can I avoid it?

Thanks in advance!

3
  • Note that for an otherwise static page, you'll need to go the javascript approach (without method=POST etc.). But if you have on-demand rendering enabled, you should redirect like this. Commented Mar 25 at 8:29
  • Yes, but if I try to redirect to the same url, I get this error: The response has already been sent to the browser and cannot be altered. Commented Mar 26 at 7:16
  • sounds like you returned some other response (or set headers or similar) before you returned the redirect response Commented Mar 26 at 8:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.