javascript
44 lines · 7 steps
How a Next.js Server Action validates a form
A server-side action parses form data with Zod, persists it, and redirects — returning structured errors when anything fails.
Explained by
highlit
1'use server'
2
3import { z } from 'zod'
4import { redirect } from 'next/navigation'
5import { db } from '@/lib/db'
6import { auth } from '@/lib/auth'
7
8const ContactSchema = z.object({
9 name: z.string().min(1, 'Name is required').max(80),
10 email: z.string().email('Enter a valid email address'),
11 subject: z.string().min(3, 'Subject must be at least 3 characters'),
12 message: z.string().min(20, 'Message must be at least 20 characters'),
13})
14
15export async function submitContact(prevState, formData) {
16 const parsed = ContactSchema.safeParse({
17 name: formData.get('name'),
18 email: formData.get('email'),
19 subject: formData.get('subject'),
20 message: formData.get('message'),
21 })
22
23 if (!parsed.success) {
24 return {
25 errors: parsed.error.flatten().fieldErrors,
26 values: Object.fromEntries(formData),
27 }
28 }
29
30 const session = await auth()
31
32 try {
33 await db.message.create({
34 data: { ...parsed.data, userId: session?.user?.id ?? null },
35 })
36 } catch {
37 return {
38 errors: { _form: ['Something went wrong. Please try again.'] },
39 values: parsed.data,
40 }
41 }
42
43 redirect('/contact/thanks')
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Server Actions let a form submit straight to server code without hand-written API routes.
- 2Returning a shaped state object with errors and values lets the UI re-render with feedback and preserved input.
- 3safeParse plus a try/catch cleanly separates validation failures from persistence failures.
Related explainers
javascript
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 steps
rust
use std::time::Duration; use tokio::time::sleep; #[derive(Debug)]
Async retry with exponential backoff in Rust
retry
exponential-backoff
async
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from "react"; export function Dropdown({ label, children }) { const [open, setOpen] = useState(false);
Closing a dropdown on outside click in React
outside-click
event-listeners
cleanup
Intermediate
8 steps
rust
use std::fs; use std::io; use std::path::{Path, PathBuf};
Recursive file search by extension in Rust
recursion
filesystem
error-handling
Intermediate
8 steps
typescript
type Ok<T> = { ok: true; value: T }; type Err<E> = { ok: false; error: E }; export type Result<T, E> = Ok<T> | Err<E>;
A Result type for typed error handling
discriminated-union
error-handling
type-guards
Intermediate
8 steps
javascript
const cache = new Map(); const inflight = new Map(); async function fetchResults(query) {
Building a typeahead with an LRU cache
caching
lru-eviction
request-deduplication
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-next-js-server-action-validates-a-form-explained-javascript-7505/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.