← Back
Edit Post
Title
Description
Server Functions with "use server", Zod validation, returning errors, cache invalidation.
Content
Markdown supported
# Server Functions Server Functions are async functions that run on the server for form submissions and mutations. ## Example: createPost From `data/actions/post-actions.ts`: ```tsx 'use server'; export async function createPost(formData: FormData): Promise<ActionResult> { const rawData = { title: formData.get('title'), ... }; const result = postSchema.safeParse(rawData); if (!result.success) { return { error: result.error.issues[0].message, formData: rawData, success: false }; } await prisma.post.create({ data: result.data }); updateTag('posts'); return { success: true }; } ``` ## Returning Errors ```tsx export type ActionResult = | { success: true } | { success: false; error: string; formData?: FormValues }; ``` Return submitted data on errors so forms can repopulate. ## Cache Invalidation ```tsx export async function updatePost(slug: string, formData: FormData) { // ... validate and update updateTag('posts'); // Invalidate the list updateTag(`post-${slug}`); // Invalidate this post } ```
Published
Save Changes
Cancel