| | |

SvelteKit Forms 06 ๐Ÿ“ Superforms & Svelte 5 Runes โ€” Client Setup with superForm()

โฑ๏ธ Estimated read: 7 min | |

Form handling in SvelteKit often involves boilerplate: managing error states, client-side validation, server-side synchronization, and optimistic UI. Superforms simplifies this by providing a unified, type-safe API that works perfectly with Svelte 5โ€™s new reactivity system. By combining the superForm store with Svelte 5โ€™s $props() and refined reactivity, you can build production-grade forms with minimal code while maintaining full progressive enhancement.

This chapter covers the initialization of the superForm store, the binding of form fields to Svelte 5 components, and the integration of the enhance action. We will also explore how the new Svelte 5 component architecture handles form data binding, ensuring that your state remains predictable and your validation logic remains strictly typed.

Key point: Superforms bridges the gap between server-side Zod validation and client-side reactivity; by using $form, $errors, and enhance in a Svelte 5 component, you create a declarative form lifecycle where validation, error display, and submission are all handled automatically.


Why exists

The validation synchronization problem. Maintaining separate validation logic for the client and server is an anti-pattern. Superforms uses Zod to define a single schema that drives both server-side validation and client-side feedback.

The boilerplate overhead. Implementing isLoading, error object arrays, and individual input binding for every form input is tedious. Superforms provides a set of stores ($form, $errors, $constraints) that eliminate this repetitive work.

The progressive enhancement requirement. Web forms must work without JavaScript, but users expect a seamless SPA-like experience when JS is enabled. Superforms provides enhance to intercept form submissions, making them feel instant without breaking native form capability.

The Svelte 5 reactivity transition. Svelte 5โ€™s migration to Runes ($state, $derived) requires a more explicit approach to reactivity. Superformsโ€™ store-based architecture remains highly performant and compatible with Svelte 5, allowing for easy migration while keeping reactive state management robust.

The complex form state challenge. Handling dirty states, touched fields, and submit-time validation is complex. Superforms centralizes this, providing helper methods to track exactly which parts of your form need attention.


a. Initializing the superForm store

The superForm function initializes your form state. It takes the data from your load function and returns a suite of stores that you use within your Svelte component. You pass the schema and initial data from the +page.server.ts result.

// +page.svelte
<script>
  import { superForm } from 'sveltekit-superforms';

  let { data } = $props(); // Svelte 5 prop declaration
  const { form, errors, constraints, enhance } = superForm(data.form);
</script>

<form method="POST" use:enhance>
  <input name="email" bind:value={$form.email} {...$constraints.email} />
  {#if $errors.email}<span>{$errors.email}</span>{/if}
</form>

The $form store acts as a reactive proxy for your data. When you bind inputs to $form.field, Superforms handles the updates and validation internally. The $constraints store automatically applies HTML5 validation attributes (like required or minlength) based on your Zod schema.


b. Binding and reactive state

In Svelte 5, you interact with stores exactly as you did beforeโ€”by prepending a $ to the store name to access the reactive value. Because Superforms stores are proxies, binding them to inputs automatically marks the field as “touched” or “dirty,” enabling real-time validation feedback.

// Advanced binding with field state
const { form, tainted } = superForm(data.form);

// Reactive check if the form has been modified
let isDirty = $derived($tainted !== undefined);

By leveraging $derived, you can easily build UI components that only enable the “Save” button when the form is actually changed. This reactivity is granular; Svelte 5 will only re-render the specific components that observe the changes in the store.


c. Enhancement and lifecycle

The enhance action is the glue that makes the form “progressive.” By applying use:enhance to your form, SvelteKit skips the default browser page reload, sends the data to the server action, validates it, and updates your $form and $errors stores seamlessly.

<form method="POST" use:enhance={{
  onSubmit: () => { /* Logic before submit */ },
  onResult: ({ result }) => { /* Handle server response */ }
}}>
  ...
</form>

This interaction is fully asynchronous and supports complex server outcomes, such as redirects or specific error messaging. Because it builds on top of the native HTML <form>, the application remains resilientโ€”if the JavaScript fails to execute, the form still submits via the standard HTTP path.


Complete Example Session

// ============================================
// PART 1: COMPONENT SETUP
// ============================================
<script>
  import { superForm } from 'sveltekit-superforms';
  let { data } = $props();

  const { form, errors, enhance, submitting } = superForm(data.form);
</script>

// ============================================
// PART 2: FORM BINDING
// ============================================
<form method="POST" use:enhance>
  <input name="username" bind:value={$form.username} />
  {#if $errors.username} <p>{$errors.username}</p> {/if}

  <button disabled={$submitting}>
    {$submitting ? 'Saving...' : 'Save'}
  </button>
</form>

// ============================================
// PART 3: DYNAMIC RUNES
// ============================================
// Use $derived to check form status
let canSubmit = $derived(!$submitting);

// ============================================
// PART 4: ENHANCE CALLBACKS
// ============================================
const { enhance } = superForm(data.form, {
  resetForm: true,
  onUpdated: ({ form }) => {
    if (form.valid) console.log('Saved!');
  }
});

The sequence demonstrates a standard Superforms setup in Svelte 5, using $props() for data injection, store-based reactivity for binding, and enhancement options for success callbacks.


Quick Reference

Superforms Stores

StorePurpose
$formReactive object of current field values
$errorsReactive object of current validation errors
$constraintsHTML5 validation attributes derived from Zod
$submittingBoolean state for active submission

Enhance Options

OptionEffect
resetFormClears form on success
onUpdatedHook after server action completes
applyActionHandles redirects/failures

Best Practices

โœ… Do This:

// Bind to fields via the $form proxy
bind:value={$form.username}                                  // โœ…

// Always use the constraint store for native validation
{...$constraints.email}                                      // โœ…

// Handle submission state in the button
<button disabled={$submitting}>                              // โœ…

// Use derived for UI states
let isValid = $derived($errors.email === undefined);         // โœ…

โŒ Don’t Do This:

// Don't modify $form values outside of bindings
$form.username = 'new'; // May bypass validation           // โŒ

// Don't manually manage individual error strings
// (Use $errors proxy)                                       // โŒ

// Don't omit the form method="POST"
// (Required for enhancement)                                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
No feedbackMissing use:enhanceAdd use:enhance to <form>
Stale errorsNot using $errorsAlways bind to error store
Validation lagClient vs Server mismatchEnsure same Zod schema used
Binding errorsMisnamed inputsname attribute must match schema

Real-World Examples

1. Input with error

<input name="email" bind:value={$form.email} />
{#if $errors.email}<span>{$errors.email}</span>{/if}

2. Native constraint injection

<input {...$constraints.age} bind:value={$form.age} />

3. Submit loader

<button disabled={$submitting}>{$submitting ? '...' : 'Submit'}</button>

4. Post-save logic

onUpdated: () => toast.success('Saved!')

5. Form reset

const { enhance } = superForm(data.form, { resetForm: true })

6. Dirty state tracking

const { tainted } = superForm(data.form);

7. Array field mapping

{#each $form.tags as _, i}
  <input bind:value={$form.tags[i]} />
{/each}

8. Custom validation message

$errors.password = 'Must be stronger';

9. Svelte 5 component prop

let { data } = $props();

10. Manual submission

const { submit } = superForm(data.form);
submit();

Visual

Superforms Data Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  FORM (UI) โ”€โ”€โ–บ $form (Proxy)                 โ”‚
โ”‚  โ”‚                                           โ”‚
โ”‚  โ”œโ”€โ–บ Validation (Zod)                        โ”‚
โ”‚  โ”‚                                           โ”‚
โ”‚  โ””โ”€โ–บ use:enhance โ”€โ”€โ–บ POST (Server)           โ”‚
โ”‚        โ”‚                                     โ”‚
โ”‚        โ””โ”€โ–บ Result โ”€โ”€โ–บ Update UI ($errors)    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Reactive Store Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Input Change โ”€โ”€โ–บ $form update               โ”‚
โ”‚                   โ”‚                          โ”‚
โ”‚                   โ”œโ”€โ–บ Validation Check       โ”‚
โ”‚                   โ”‚                          โ”‚
โ”‚                   โ””โ”€โ–บ $errors update         โ”‚
โ”‚                         โ”‚                    โ”‚
โ”‚                         โ””โ”€โ–บ UI Render        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
InitializationsuperForm(data.form)
Field Access$form.field
Error Handling$errors.field
Progressiveuse:enhance
Props$props()

Key takeaways:

  • Use $props() for Svelte 5. The transition from export let is simple, and it keeps your components clean and standard-compliant.
  • Bind directly to $form. The proxy-based store ensures that any change you make to the UI is instantly reflected in the form’s state and validation engine.
  • Constraints are built-in. Using ...$constraints is the easiest way to give users immediate feedback for basic HTML validation requirements.
  • Enhance for power. use:enhance is the secret sauce that makes your application feel like an SPA while remaining as reliable as a standard web form.
  • Granular reactivity. Leveraging $derived on your superForm stores allows you to build complex state-aware UI components without overhead.

Remember: Forms represent the most frequent interaction point between your application and your user. By standardizing your form setup with Superforms and embracing the reactive power of Svelte 5, you eliminate the friction that makes form development difficult, leaving you with a robust, type-safe, and highly responsive data-entry experience.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!