SvelteKit Forms 05 ๐ Schema Adapters & superValidate() โ Defining Zod schemas and validating on the server
The architecture of a modern SvelteKit form revolves around the transition from untrusted user input to validated application data. superValidate() serves as the crucial gateway in this process. By utilizing schema adaptersโsuch as the Zod adapterโthis function bridges the gap between raw FormData and your TypeScript-defined schemas. It is responsible for two distinct states: preparing the initial form state for the server-side rendering phase and validating the submitted data during form actions.
This chapter covers the implementation of schema adapters and the lifecycle of superValidate(). We will examine how to define robust schemas, how to initialize the form state within your load function, and the critical step of performing server-side validation within your actions. By mastering these patterns, you eliminate manual data parsing and ensure that your application enforces strict data contracts at the entry point of every request.
Key point: superValidate() is the interface between untrusted user input and your application logic; it accepts a schema adapter (like zod), validates the FormData, and returns a structured object that handles both initial server-side rendering and POST submission states, ensuring consistent error feedback.
Why exists
- The Unstructured Input problem.
FormDatais inherently untyped and string-based, forcing developers to manually convert values (e.g., strings to numbers) and check for existence, which is error-prone. - The Validation Drift problem. When validation logic is duplicated between frontend inputs and backend logic, the rules inevitably diverge, leading to confusing user experiences and security vulnerabilities.
- The Initial State mismatch. The server needs to know the “default” state of a form to render it correctly for the initial page load;
superValidate()reconciles these defaults with the schema. - The Complexity of Schema Adapters. Libraries like Zod or Valibot provide rich, composable validation, but SvelteKit needs a standard way to interface with them; adapters normalize these libraries into a common API.
- The Progressive Enhancement hurdle. Server actions must validate data even if the client-side JavaScript bundle never executes, requiring a server-first validation strategy.
a. Defining schemas with Zod or Valibot
The first step in any Superforms workflow is defining the data structure. While Zod is the most popular choice, the library supports multiple adapters, including Valibot. The schema must be defined in a way that allows the adapter to read it, translate it into types, and extract validation rules.
import { z } from 'zod';
export const schema = z.object({
name: z.string().min(2, "Name must be at least 2 characters"),
age: z.coerce.number().int().min(18, "You must be 18+"),
email: z.string().email("Invalid email address")
});
By defining the schema here, you gain immediate TypeScript type safety. The library uses this schema to generate the validation logic, provide helpful error messages, and guide the type-checking for the form object used in your UI.
b. Using superValidate in the load function
The load function is responsible for providing the form to the UI for the first time. superValidate() creates an initial form state, optionally accepting default values. This is essential for SvelteKitโs SSR (Server-Side Rendering) because it ensures the user sees a valid, empty (or pre-filled) form immediately upon reaching the page.
import { superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import { schema } from './schema.ts';
export const load = async () => {
const form = await superValidate(zod(schema));
return { form };
};
This returns a form object that contains data, errors, and valid status. It is the standardized object that the superForm client-side hook expects to receive, ensuring the client and server stay perfectly aligned from the first paint.
c. Server-side validation in form actions
When the user submits the form, the actions handler uses the same schema adapter. By passing the Request object into superValidate(), the library automatically handles parsing the FormData and validating it against your schema. If validation fails, it returns the form state, including error messages, to the client.
export const actions = {
default: async ({ request }) => {
const form = await superValidate(request, zod(schema));
if (!form.valid) {
return fail(400, { form });
}
// Data is now guaranteed to be type-safe
await saveToDatabase(form.data);
return { form };
}
};
This ensures that your business logic only ever runs on data that has passed validation. If the data is invalid, the fail() helper returns the form object, which SvelteKit uses to repopulate the UI, preserving the user’s input and displaying the validation errors.
Complete Example Session
// ============================================
// PART 1: DEFINING THE SCHEMA
// ============================================
import { z } from 'zod';
export const schema = z.object({
username: z.string().min(3),
password: z.string().min(8)
});
// ============================================
// PART 2: SERVER LOAD INITIALIZATION
// ============================================
export const load = async () => {
return { form: await superValidate(zod(schema)) };
};
// ============================================
// PART 3: SERVER-SIDE VALIDATION ACTION
// ============================================
export const actions = {
default: async ({ request }) => {
const form = await superValidate(request, zod(schema));
if (!form.valid) return fail(400, { form });
// form.data is fully typed here!
return { form };
}
};
// ============================================
// PART 4: CLIENT-SIDE CONSUMPTION
// ============================================
const { form, enhance } = superForm(data.form);
This session showcases the complete lifecycle, where the server provides an initial state via load and validates the submission in actions, while the client uses that same logic for reactivity.
Quick Reference
Schema Adapters
| Adapter | Library |
|---|---|
zod | Zod |
valibot | Valibot |
superValidate Usage
| Context | Purpose |
|---|---|
superValidate(zod(s)) | Creates initial empty form |
superValidate(req, zod(s)) | Validates submitted POST data |
form.valid | Boolean check for integrity |
Validation Result
| Property | Description |
|---|---|
form.data | Typed object of values |
form.errors | Map of field error messages |
form.constraints | HTML5 validation attributes |
Best Practices
โ Do This:
// Always use adapter functions from the library
await superValidate(zod(schema)); // โ
// Define schemas in shared files
import { schema } from '$lib/schemas'; // โ
// Use fail() for non-validating forms
return fail(400, { form }); // โ
// Coerce values in your Zod schema
z.coerce.number() // โ
โ Don’t Do This:
// Don't validate manually inside the action
if (data.get('x').length < 3) ... // โ
// Don't import Zod directly without the adapter
// (causes adapter errors) // โ
// Don't ignore form.valid
// (executes logic on invalid data) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mismatched Schema | Schema edited but load/action not updated | Keep schema in a single file |
FormData Errors | Using raw request.formData() | Rely on superValidate(request) |
| Serialization | Passing non-serializable data | Stick to JSON-friendly schema data |
Real-World Examples
1. Zod string validation
z.string().min(1, "Required")
2. Valibot adapter import
import { valibot } from 'sveltekit-superforms/adapters';
3. Handling numeric coercion
z.coerce.number().min(0)
4. Initial form state
await superValidate(defaults, zod(schema))
5. Returning fail
return fail(400, { form })
6. Accessing typed data
const { username } = form.data
7. Schema composition
z.intersection(base, extra)
8. Field-level error messages
z.string().email("Please enter a valid email")
9. Async validation
z.string().refine(async () => ...)
10. Form level errors
setError(form, 'password', 'Wrong credentials')
Visual
The Validation Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FORM โโโบ superValidate(adapter) โโโบ Valid? โ
โ โ โ
โ [ Valid ] โโโบ Action Logic โโโโโโ โ
โ [ Invalid ] โโโบ fail(400, form) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Adapter Layer
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LIBRARY (Zod/Valibot) โ
โ โ โ
โ ADAPTER (zod/valibot function) โ
โ โ โ
โ SUPERFORMS (superValidate) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Load and Action Sync
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LOAD โโโบ Init Form (SSR) โ
โ โ
โ SUBMIT โโโบ Validate Form (Server Action) โ
โ โ
โ Both use same adapter and schema. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Logic interface | superValidate() |
| Schema integration | zod() / valibot() adapters |
| State control | form.valid |
| UI feedback | fail() return value |
Key takeaways:
- Adapters are mandatory. They map Zod or Valibot rules to the internal logic Superforms requires to generate validation.
superValidateis versatile. It works for the initialload(SSR) and the final submission (action), keeping logic unified.- Type safety is default. By defining your schema correctly, you get full TypeScript support for all form fields in your actions.
- Validation is mandatory. Never bypass the schema by parsing
FormDatamanually; the schema is your single source of truth. - Fail with intent. Returning the
formobject viafail()is the standard way to inform the UI of errors while maintaining the input state.
Remember: Schema adapters are the engine behind Superforms’ reliability. By using superValidate() with Zod or Valibot, you create a declarative contract between your server and client, ensuring that data is always processed according to the rules you defined, and that the UI can always reflect the state of that validation without complex manual state handling.
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!