SvelteKit Forms 06 ๐ Superforms & Svelte 5 Runes โ Client Setup with superForm()
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
| Store | Purpose |
|---|---|
$form | Reactive object of current field values |
$errors | Reactive object of current validation errors |
$constraints | HTML5 validation attributes derived from Zod |
$submitting | Boolean state for active submission |
Enhance Options
| Option | Effect |
|---|---|
resetForm | Clears form on success |
onUpdated | Hook after server action completes |
applyAction | Handles 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No feedback | Missing use:enhance | Add use:enhance to <form> |
| Stale errors | Not using $errors | Always bind to error store |
| Validation lag | Client vs Server mismatch | Ensure same Zod schema used |
| Binding errors | Misnamed inputs | name 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
| Item | Value |
|---|---|
| Initialization | superForm(data.form) |
| Field Access | $form.field |
| Error Handling | $errors.field |
| Progressive | use:enhance |
| Props | $props() |
Key takeaways:
- Use
$props()for Svelte 5. The transition fromexport letis 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
...$constraintsis the easiest way to give users immediate feedback for basic HTML validation requirements. - Enhance for power.
use:enhanceis the secret sauce that makes your application feel like an SPA while remaining as reliable as a standard web form. - Granular reactivity. Leveraging
$derivedon yoursuperFormstores 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.
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!