Sveltekit Form Endpoint

Sveltekit Form Endpoint has some breaking changes. Let's see what they are.

svelte logo

Want to build a Svelte/SvelteKit site? Hire Me.

Sveltekit Form Endpoint

After merging this pull request there have been a few changes in Sveltekit Endpoints and how it works.

I did a video on Sveltekit contact form which uses an endpoint but some changes should be done to get it working.

Contact Form

<form action="/api/contact" method="POST">
  <label>
    Email
    <input type="email" name="email" />
  </label>

  <label>
    Password
    <input type="password" name="password" />
  </label>

  <input type="submit" />
</form>

Endpoint /api/contact.js

export const post = async ({ request }) => {
  const data = await request.formData();
  const email = data.get("email");
  const password = data.get("password");
  //login the user with email and password

  return {
    body: {
      //redirect or send success or failure state
    },
  };
};

Please make these corrections in the video below,

Sveltekit Form Without Redirect

The form above will redirect the user to /api/contact if no redirect is mentioned in the endpoint.

If you do not want the redirect to happen, you can use svelte on:submit with preventDefault event modifier on the form.

<script>
  const handleSubmit = async({currentTarget}) => {
    const formData = new FormData(currentTarget);
    const res = await fetch("/api/contact", {
      method: "POST",
      body: formData,
    });
    const data = await res.json();
    // do something with the returned data from endpoint
  }
</script>


<form on:submit|preventDefault={handleSubmit}>
  <label>
    Email
    <input type="email" name="email" />
  </label>

  <label>
    Password
    <input type="password" name="password" />
  </label>

  <input type="submit" />
</form>

The same endpoint mentioned above will work with this form.

Find related articles

Let's discuss on Twitter