javascript 36 lines · 7 steps

Handling form submits with Next.js Server Actions

A server action validates form input with Zod, persists it, notifies, and revalidates the page cache.

Explained by highlit
1'use server'
2 
3import { z } from 'zod'
4import { revalidatePath } from 'next/cache'
5import { db } from '@/lib/db'
6import { sendContactNotification } from '@/lib/mailer'
7 
8const ContactSchema = z.object({
9 name: z.string().trim().min(1, 'Name is required').max(120),
10 email: z.string().trim().email('Enter a valid email address'),
11 message: z.string().trim().min(10, 'Message must be at least 10 characters'),
12})
13 
14export async function submitContact(_prevState, formData) {
15 const parsed = ContactSchema.safeParse({
16 name: formData.get('name'),
17 email: formData.get('email'),
18 message: formData.get('message'),
19 })
20 
21 if (!parsed.success) {
22 return {
23 status: 'error',
24 errors: parsed.error.flatten().fieldErrors,
25 }
26 }
27 
28 const submission = await db.contactSubmission.create({
29 data: parsed.data,
30 })
31 
32 await sendContactNotification(submission)
33 revalidatePath('/contact')
34 
35 return { status: 'success', message: "Thanks! We'll be in touch soon." }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validating on the server with a schema keeps trusted logic off the client and returns structured errors.
  2. 2Server actions can talk directly to your database and side-effect services without a separate API route.
  3. 3Calling revalidatePath after a mutation keeps cached pages in sync with fresh data.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling form submits with Next.js Server Actions — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code