How would you create strongly typed server actions that validate their input and return a predictable, typed result?
Short answer
You define types for both the expected form data shape and the return value of your server action, often combining this with a runtime validation library like zod to ensure the data actually matches your types at runtime, giving both compile time safety and runtime protection…
Advertisement
AModel answer
You define types for both the expected form data shape and the return value of your server action, often combining this with a runtime validation library like zod to ensure the data actually matches your types at runtime, giving both compile time safety and runtime protection against unexpected input.
import { z } from 'zod';
const schema = z.object({ email: z.string().email() });
type FormState = { error?: string; success?: boolean };
export async function subscribe(prevState: FormState, formData: FormData): Promise<FormState> {
const result = schema.safeParse({ email: formData.get('email') });
if (!result.success) {
return { error: 'Invalid email address' };
}
return { success: true };
}Real-world example
A newsletter signup feature combines TypeScript types with zod validation in its server action, catching both type mismatches during development and invalid data at runtime before it ever reaches the database.
Likely follow-ups
- What is the relationship between TypeScript types and runtime validation libraries like zod?
- How do you type the state managed by the useActionState hook?
Related topics