0
# Server-Side Processing
1
2
Server-side form processing with validation, error handling, data coercion, and integration with SvelteKit's action system. Handles form submissions, file uploads, and provides comprehensive validation results.
3
4
## Capabilities
5
6
### SuperValidate Function
7
8
The core server-side validation function that processes form data, validates against schemas, and returns structured results for client consumption.
9
10
```typescript { .api }
11
/**
12
* Validates form data against a schema and returns a structured result
13
* @param adapter - Validation adapter for the schema
14
* @param options - Optional configuration for validation
15
* @returns Promise resolving to SuperValidated result
16
*/
17
function superValidate<Out, Message, In>(
18
adapter: ValidationAdapter<Out, In>,
19
options?: SuperValidateOptions<Out>
20
): Promise<SuperValidated<Out, Message, In>>;
21
22
/**
23
* Validates request data against a schema and returns a structured result
24
* @param data - Request data from various sources (RequestEvent, FormData, etc.)
25
* @param adapter - Validation adapter for the schema
26
* @param options - Optional configuration for validation
27
* @returns Promise resolving to SuperValidated result
28
*/
29
function superValidate<Out, Message, In>(
30
data: RequestEvent | Request | FormData | URLSearchParams | URL | Partial<In> | null | undefined,
31
adapter: ValidationAdapter<Out, In>,
32
options?: SuperValidateOptions<Out>
33
): Promise<SuperValidated<Out, Message, In>>;
34
35
interface SuperValidateOptions<Out> {
36
/** Whether to include validation errors in the result */
37
errors?: boolean;
38
/** Unique identifier for the form */
39
id?: string;
40
/** Array of field names that have been preprocessed */
41
preprocessed?: (keyof Out)[];
42
/** Default values to use when no data is provided */
43
defaults?: Out;
44
/** JSON Schema for additional validation */
45
jsonSchema?: JSONSchema;
46
/** Whether to use strict validation mode */
47
strict?: boolean;
48
/** Whether to allow file uploads */
49
allowFiles?: boolean;
50
/** Transport configuration for data handling */
51
transport?: Transport;
52
}
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { superValidate } from "sveltekit-superforms/server";
59
import { zod } from "sveltekit-superforms/adapters";
60
import { z } from "zod";
61
62
const schema = z.object({
63
name: z.string().min(2),
64
email: z.string().email(),
65
age: z.number().min(18)
66
});
67
68
// Load action - create empty form
69
export const load = async () => {
70
const form = await superValidate(zod(schema));
71
return { form };
72
};
73
74
// Form action - validate submitted data
75
export const actions = {
76
default: async ({ request }) => {
77
const form = await superValidate(request, zod(schema));
78
79
if (!form.valid) {
80
return fail(400, { form });
81
}
82
83
// Process valid data
84
await saveUser(form.data);
85
return { form };
86
}
87
};
88
89
// With custom defaults
90
const form = await superValidate(zod(schema), {
91
defaults: { name: "John", email: "", age: 25 }
92
});
93
94
// Validate specific data
95
const form = await superValidate(
96
{ name: "Alice", email: "alice@example.com", age: 30 },
97
zod(schema)
98
);
99
```
100
101
### Message Management
102
103
Functions for adding messages and status information to forms, useful for providing feedback to users after form submission.
104
105
```typescript { .api }
106
/**
107
* Adds a message to a SuperValidated form result
108
* @param form - The form result to add the message to
109
* @param message - The message to add
110
* @param options - Optional status and type configuration
111
* @returns Updated form with message
112
*/
113
function message<T, M>(
114
form: SuperValidated<T, M>,
115
message: M,
116
options?: {
117
status?: number;
118
type?: 'error' | 'success' | 'warning' | 'info';
119
}
120
): SuperValidated<T, M>;
121
122
/**
123
* Alias for message function
124
*/
125
function setMessage<T, M>(
126
form: SuperValidated<T, M>,
127
message: M,
128
options?: {
129
status?: number;
130
type?: 'error' | 'success' | 'warning' | 'info';
131
}
132
): SuperValidated<T, M>;
133
```
134
135
**Usage Examples:**
136
137
```typescript
138
import { message, superValidate } from "sveltekit-superforms/server";
139
140
export const actions = {
141
default: async ({ request }) => {
142
const form = await superValidate(request, zod(schema));
143
144
if (!form.valid) {
145
return fail(400, { form });
146
}
147
148
try {
149
await saveUser(form.data);
150
return message(form, "User created successfully!", {
151
type: 'success'
152
});
153
} catch (error) {
154
return message(form, "Failed to create user", {
155
type: 'error',
156
status: 500
157
});
158
}
159
}
160
};
161
```
162
163
### Error Handling
164
165
Functions for setting specific validation errors on form fields, useful for custom validation logic and server-side error handling.
166
167
```typescript { .api }
168
/**
169
* Sets validation errors on specific form fields
170
* @param form - The form result to add errors to
171
* @param path - Field path where the error should be set
172
* @param error - Error message or array of error messages
173
* @returns Updated form with errors
174
*/
175
function setError<T, M>(
176
form: SuperValidated<T, M>,
177
path: FormPath<T> | '',
178
error: string | string[]
179
): SuperValidated<T, M>;
180
```
181
182
**Usage Examples:**
183
184
```typescript
185
import { setError, superValidate } from "sveltekit-superforms/server";
186
187
export const actions = {
188
default: async ({ request }) => {
189
const form = await superValidate(request, zod(schema));
190
191
if (!form.valid) {
192
return fail(400, { form });
193
}
194
195
// Custom validation
196
const emailExists = await checkEmailExists(form.data.email);
197
if (emailExists) {
198
return fail(400, {
199
form: setError(form, 'email', 'Email already exists')
200
});
201
}
202
203
// Multiple errors
204
if (form.data.name.includes('admin')) {
205
return fail(400, {
206
form: setError(form, 'name', [
207
'Name cannot contain "admin"',
208
'Please choose a different name'
209
])
210
});
211
}
212
213
// Form-level error
214
if (someGlobalCondition) {
215
return fail(400, {
216
form: setError(form, '', 'Form submission failed')
217
});
218
}
219
220
return { form };
221
}
222
};
223
```
224
225
### File Handling
226
227
Functions for managing file uploads and file-related form data processing.
228
229
```typescript { .api }
230
/**
231
* Processes form data with file handling capabilities
232
* @param form - The form result to process
233
* @param callback - Function to handle file processing
234
* @returns Updated form with file processing results
235
*/
236
function withFiles<T, M>(
237
form: SuperValidated<T, M>,
238
callback: (files: FormData) => Promise<void> | void
239
): Promise<SuperValidated<T, M>>;
240
241
/**
242
* Removes files from form data
243
* @param form - The form result to remove files from
244
* @param paths - Paths to file fields to remove
245
* @returns Updated form without specified files
246
*/
247
function removeFiles<T, M>(
248
form: SuperValidated<T, M>,
249
paths?: FormPath<T>[]
250
): SuperValidated<T, M>;
251
```
252
253
**Usage Examples:**
254
255
```typescript
256
import { withFiles, superValidate } from "sveltekit-superforms/server";
257
import { writeFile } from 'fs/promises';
258
259
const schema = z.object({
260
name: z.string(),
261
avatar: z.any() // File field
262
});
263
264
export const actions = {
265
upload: async ({ request }) => {
266
const form = await superValidate(request, zod(schema));
267
268
if (!form.valid) {
269
return fail(400, { form });
270
}
271
272
return await withFiles(form, async (files) => {
273
const avatar = files.get('avatar') as File;
274
if (avatar && avatar.size > 0) {
275
const buffer = await avatar.arrayBuffer();
276
await writeFile(`uploads/${avatar.name}`, Buffer.from(buffer));
277
}
278
});
279
}
280
};
281
```
282
283
### Schema Utilities
284
285
Utility functions for working with validation schemas and extracting metadata.
286
287
```typescript { .api }
288
/**
289
* Creates default values from a validation adapter
290
* @param adapter - Validation adapter to extract defaults from
291
* @param options - Optional configuration
292
* @returns SuperValidated result with defaults
293
*/
294
function defaults<Out, Message, In>(
295
adapter: ValidationAdapter<Out, In>,
296
options?: { id?: string; defaults?: Out }
297
): SuperValidated<Out, Message, In>;
298
299
/**
300
* Extracts default values from a validation adapter
301
* @param adapter - Validation adapter to extract defaults from
302
* @returns Default values object
303
*/
304
function defaultValues<T>(adapter: ValidationAdapter<T>): T;
305
306
/**
307
* Gets structural shape information from a validation adapter
308
* @param adapter - Validation adapter to analyze
309
* @returns Schema shape metadata
310
*/
311
function schemaShape<T>(adapter: ValidationAdapter<T>): SchemaShape;
312
313
/**
314
* Splits an object path string into an array of path segments
315
* @param path - Dot-separated path string (e.g., "user.profile.name")
316
* @returns Array of path segments (e.g., ["user", "profile", "name"])
317
*/
318
function splitPath(path: string): (string | number)[];
319
```
320
321
### Action Results
322
323
Functions for creating typed action results that integrate with SvelteKit's form handling system.
324
325
```typescript { .api }
326
/**
327
* Creates an action result with proper typing
328
* @param status - HTTP status code
329
* @param data - Data to include in the result
330
* @returns Typed ActionResult
331
*/
332
function actionResult<T>(
333
status: number,
334
data: T
335
): ActionResult<T>;
336
337
/**
338
* Creates a failure action result with automatic form processing
339
* Automatically sets valid: false on SuperValidated forms and removes files
340
* @param status - HTTP status code (typically 400)
341
* @param data - Data to include in the failure result (usually contains form)
342
* @returns Failure ActionResult with processed form data
343
*/
344
function fail<T>(
345
status: number,
346
data: T
347
): ActionFailure<T>;
348
```
349
350
## Core Types
351
352
```typescript { .api }
353
interface SuperValidated<Out, Message = any, In = Out> {
354
/** Unique identifier for the form instance */
355
id: string;
356
/** Whether the form data passed validation */
357
valid: boolean;
358
/** Deprecated: Whether the form was posted (inconsistent behavior) */
359
posted: boolean;
360
/** Validation errors structured by field path */
361
errors: ValidationErrors<Out>;
362
/** The validated and coerced form data */
363
data: Out;
364
/** HTML input constraints derived from schema */
365
constraints?: InputConstraints<Out>;
366
/** Optional message for user feedback */
367
message?: Message;
368
/** Schema structure metadata */
369
shape?: SchemaShape;
370
}
371
372
interface ValidationErrors<T> {
373
/** Form-level errors */
374
_errors?: string[];
375
/** Field-level errors following object structure */
376
[K in keyof T]?: T[K] extends Record<string, unknown>
377
? ValidationErrors<T[K]>
378
: T[K] extends Array<infer U>
379
? U extends Record<string, unknown>
380
? Array<ValidationErrors<U> | undefined>
381
: string[]
382
: string[];
383
}
384
385
interface InputConstraints<T> {
386
[K in keyof T]?: T[K] extends Record<string, unknown>
387
? InputConstraints<T[K]>
388
: T[K] extends Array<infer U>
389
? U extends Record<string, unknown>
390
? Array<InputConstraints<U> | undefined>
391
: InputConstraint
392
: InputConstraint;
393
}
394
395
interface InputConstraint {
396
/** Minimum value/length */
397
min?: number;
398
/** Maximum value/length */
399
max?: number;
400
/** Step value for numbers */
401
step?: number;
402
/** Minimum length for strings */
403
minlength?: number;
404
/** Maximum length for strings */
405
maxlength?: number;
406
/** Regular expression pattern */
407
pattern?: string;
408
/** Whether field is required */
409
required?: boolean;
410
}
411
412
type ValidationAdapter<Out, In = Out> = {
413
/** Identifier for the validation library used */
414
superFormValidationLibrary: ValidationLibrary;
415
/** Validation function that processes data */
416
validate: (data: unknown) => Promise<ValidationResult<Out>>;
417
/** JSON Schema representation */
418
jsonSchema: JSONSchema;
419
/** Default values for the schema */
420
defaults: Out;
421
/** HTML input constraints */
422
constraints: InputConstraints<Out>;
423
/** Schema structure metadata */
424
shape: SchemaShape;
425
/** Unique identifier for caching */
426
id: string;
427
};
428
429
type ValidationResult<T> = {
430
/** Whether validation passed */
431
success: boolean;
432
/** Validated data (if successful) */
433
data?: T;
434
/** Validation error details */
435
issues?: ValidationIssue[];
436
};
437
438
interface ValidationIssue {
439
/** Path to the field with the error */
440
path: (string | number)[];
441
/** Error message */
442
message: string;
443
/** Error code */
444
code?: string;
445
}
446
447
type FormPath<T, Type = any> = string; // String path to any property in T
448
type TaintedFields<T> = Record<string, boolean>; // Tracks modified fields
449
```