Form Submissions in SvelteKit

Have you ever wondered how to handle form submissions in a SvelteKit app to implement user login, registration, or data collection? SvelteKit provides a powerful way to handle forms using form actions

Basic Form Setup

Let's start with a basic form setup in SvelteKit:

<!-- src/routes/contact/+page.svelte -->
<form method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea>

  <button type="submit">Send</button>
</form>

This basic form includes input fields for name, email, and a message, along with a submit button. The method attribute is set to "POST", indicating that the form data will be sent to the server when submitted.

Handling Form Submissions

To handle the form submission, we need to create a corresponding +page.server.js file:

// src/routes/contact/+page.server.js
export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const name = formData.get('name');
    const email = formData.get('email');
    const message = formData.get('message');

    // Process the form data (e.g., send an email, store in a database)

    return { success: true };
  }
};

In the +page.server.js file, we export an actions object with a default function. This function receives the request object, which contains the submitted form data. We can access the form data using request.formData() and retrieve individual field values using the get() method.

Inside the function, you can process the form data as needed, such as sending an email or storing it in a database. Finally, you can return a response object, which can be used to provide feedback to the user.

Displaying Form Feedback

To display feedback to the user after form submission, we can use the form property in our +page.svelte file:

<!-- src/routes/contact/+page.svelte -->
<script>
  export let form;
</script>

{#if form?.success}
  <p>Thank you for your message!</p>
{/if}

<!-- Form code here -->

The form property is automatically populated with the response from the form action. In this example, we check if form.success is truthy and display a success message if the form submission was successful.

Named Form Actions

If you have multiple forms on a single page, you can use named form actions instead of the default action:

<!-- src/routes/contact/+page.svelte -->
<form method="POST" action="?/contact">
  <!-- Form fields -->
  <button type="submit">Send</button>
</form>

<form method="POST" action="?/subscribe">
  <!-- Form fields -->
  <button type="submit">Subscribe</button>
</form>
// src/routes/contact/+page.server.js
export const actions = {
  contact: async ({ request }) => {
    // Handle contact form submission
  },
  subscribe: async ({ request }) => {
    // Handle subscription form submission
  }
};

By specifying the action attribute on the form with a value like ?/contact or ?/subscribe, you can map the form submission to a specific named action in the +page.server.js file. This allows you to handle multiple forms on the same page with different actions.

Progressive Enhancement

SvelteKit forms support progressive enhancement out of the box. This means that even if JavaScript is disabled in the user's browser, the form will still submit and be handled by the server.

However, you can enhance the form submission experience using the use:enhance directive from $app/forms:

<!-- src/routes/contact/+page.svelte -->
<script>
  import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance>
  <!-- Form fields -->
  <button type="submit">Send</button>
</form>

By adding use:enhance to the form, SvelteKit will intercept the form submission and handle it using JavaScript. This allows for a smoother user experience, such as displaying loading states or handling form validation without a full page reload.

Last updated