Documentation Shento Hendriks
Svelte / SvelteKit
Svelte / SvelteKit
  • Getting Started with SvelteKit
    • Installing SvelteKit
      • Tailwind Typography plugin
    • Base Syntax & Core Features of Svelte
      • Curly Braces & Understanding Core Syntax
      • Reactive Variables
      • Two-way-binding Shortcut
      • Using multiple components
      • Components & Communication via Props
      • Display HTML in Svelte
      • Dynamic classes
      • Using $effect
      • Working with Javascript and Rune reactivity
    • Working with Conditionals & Loops
      • Showing code conditionally in Svelte
      • Looping through arrays (lists)
      • Lists & Keys
    • Closer look at reactivity
      • Updating Arrays & Objects
      • Event Modifiers
    • Component Events
    • Best Practices
    • Adding Google Font in Tailwind and SvelteKit
    • Adding Local Fonts to SvelteKit with Tailwind
    • Prevent flicker in images
    • Enhanced Images
    • Form Submissions in SvelteKit
    • Effective SEO in SvelteKit
    • Automatic Site Maps in Svelte
    • Creating Custom Elements with Svelte, SvelteKit, and Vite
    • Creating a Svelte Library with JavaScript Functions
  • Useful Code Snippets
    • Hover effects
    • Navigation
    • Centering Items
    • Setting Footer Bottom Page
  • Installing Useful Libraries
    • Documenting Javascript with JSDocs (Crash Course)
    • Adding Lottie Animations to Svelte Application
    • SvelteKit Melt-ui
      • First Component - accordion
    • Installing Shadcn/ui Svelte
    • Getting Started with GSAP with SvelteKit
      • What is GSAP?
      • Installing GSAP & Your first animation
      • GSAP in SvelteKit
    • Installing Locomotive Scroll with Svelte 5 and SvelteKit
  • SvelteKit Server Fetching and Deployment
    • Preparing a SvelteKit application for Deployment
    • Utility Functions for URL Handling in SvelteKit
    • Fetching Directus Data from Rest API with SvelteKit
    • Fetching data from api with caching
    • Displaying Fetched Data in a Each Loop
    • Creating slug friendly urls based on query data
    • Finding correct query in api based on url slug
Powered by GitBook
On this page
  • Basic Form Setup
  • Handling Form Submissions
  • Displaying Form Feedback
  • Named Form Actions
  • Progressive Enhancement
  1. Getting Started with SvelteKit

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.

PreviousEnhanced ImagesNextEffective SEO in SvelteKit

Last updated 9 months ago