Search code examples
http-redirectfetch-apisveltekithttp-status-code-303

Redirect for HTTP POST does not work in SvelteKit


In SvelteKit I want to handle a post request and redirect to a route on success. This should be possible by sending a status code of 303 and the location header - as in the SvelteKit docs. Unfortunately, it does not work. In the Dev tools you see the 303 response, but the redirect is not handled. Of course, there are workarounds (for example, a redirect on the client, or directly post to the desired page), but I would like to know why this error happens.

Stackblitz: https://stackblitz.com/edit/sveltejs-kit-template-default-z9rs2c

index.svelte

 <script>
   function submit() {
     fetch("/endpoint", {method: "POST"});
   }
 </script>

 <button on:click={submit}>Click me</button>

endpoint.js

export function post() {
    console.log('got post request at endpoint');
    return {
        status: 303,
        headers: {
            location: '/success'
        }
    };
 }

success.svelte

 <h2>Success</h2>

Solution

  • HTTP POST redirect is handled by web browsers only if you are using native <form method=POST> HTML construct.

    You are using fetch() API, which is very different. Thus you need to handle the redirect yourself.

    You can do this by extracting location from the fetch() response headers and then calling manually goto() from $app/navigation.