← Back

Server Functions with Zod

Server Functions with "use server", Zod validation, returning errors, cache invalidation.

PublishedMarch 5, 2026132 words
Edit

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:

'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 }; }
'use server'; export async function createPost(formData: FormData): Promise<ActionResult> { const rawData = { title: formData.get('title'), ...

Returning Errors

export type ActionResult = | { success: true } | { success: false; error: string; formData?: FormValues };

Return submitted data on errors so forms can repopulate.

Cache Invalidation

export async function updatePost(slug: string, formData: FormData) { // ... validate and update updateTag('posts'); // Invalidate the list updateTag(`post-${slug
}
;
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
}
;
}
export
type
ActionResult
=
|
{
success
:
true
}
|
{
success
:
false
;
error
:
string
;
formData
?
:
FormValues
}
;
}
`
)
;
// Invalidate this post
}
export async function updatePost(slug: string, formData: FormData) { // ... validate and update updateTag('posts'); // Invalidate the list updateTag(`post-${slug}`); // Invalidate this post }