Form POST Redirect
Answered
Willow Flycatcher posted this in #help-forum
Willow FlycatcherOP
In my code I'm using a html form where it makes a post request to a api endpoint and in the api endpoint I use redirect to redirect back to the homepage. Even though the api route completes it hangs on the redirect and stays loading.
21 Replies
Willow FlycatcherOP
<form method="POST" action={'/api/post'} className="border-2 border-black w-min mx-auto p-2 gap-2 flex">
{inputs}
</form>export async function POST(req: Request) {
//Some code that registers data that runs
redirect('/')
}try returning the redirect
@Willow Flycatcher ts
export async function POST(req: Request) {
//Some code that registers data that runs
redirect('/')
}
Disclaimer: this is just an educated guess
I think the reason it doesn’t work is because the redirect here is a POST redirect so you are posting to / which doesn't work
To do this I think you have to use server actions here, or don't use action and just use normal onSubmit+fetch+router.push
I think the reason it doesn’t work is because the redirect here is a POST redirect so you are posting to / which doesn't work
To do this I think you have to use server actions here, or don't use action and just use normal onSubmit+fetch+router.push
With server actions it is very simple to do what you are trying to do here. But it is in alpha hence experimental
@joulev Disclaimer: this is just an educated guess
I think the reason it doesn’t work is because the redirect here is a POST redirect so you are posting to / which doesn't work
To do this I think you have to use server actions here, or don't use action and just use normal onSubmit+fetch+router.push
it uses 307... so i am very now very interested to see what occures... like if it still stayes with POST or converts to GET...
As far as I know the method is preserved
And that is a pretty confident guess because people asked this before here
but your 2 solutions are way better anyway
But I can’t say I can confirm it is correct because I haven’t tried that myself
if you use 301/2 then it converts to GET
Answer
Willow FlycatcherOP
Yep did that, used a 303 so it becomes GET
and works now ty
@riský 302?
Willow FlycatcherOP
Nah I read over https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location and that mentioned a 303 so I just tried that
should work the same tho i think
but for better UX for the user, you should probably do joulev's suggestions
Willow FlycatcherOP
probably, just tryna scaffold out the site now atm tho
@Willow Flycatcher Nah I read over https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location and that mentioned a 303 so I just tried that
lol i haven't heard about this... but thats cool