0 day streak
javascript / intermediate
Snippet

Server Actions with Type Validation

Server Actions allow you to handle form submissions and data mutations directly on the server. Combining them with Zod ensures that input data is validated before processing.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'use server';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';
const Schema = z.object({ name: z.string().min(3) });
export async function updateUsername(formData: FormData) {
const validated = Schema.safeParse({ name: formData.get('name') });
if (!validated.success) return { error: 'Invalid name' };
await db.user.update({ data: validated.data });
revalidatePath('/profile');
}
nextjs
Breakdown
1
'use server';
Marks the file or function as a Server Action for Next.js.
2
revalidatePath('/profile');
Purges the cached data for the specific path to show updated content.