Skip to Content
Nextjs5.1 Server Actions & Forms

Server Actions & Forms 📮

Server actions let you call server code directly from components—no custom API route required. Think of them as wormholes that drop form data straight into your backend.

Why Server Actions Matter 🌟

  • Co-locate mutation logic with UI.
  • Keep secrets server-side (no API key exposure).
  • Built-in cache invalidation hooks (revalidateTag, revalidatePath).
  • Works with progressive enhancement (plain HTML forms).

Form Actions Basics 📝

'use server'; export async function addNote(formData: FormData) { const content = formData.get('content'); await db.note.create({ data: { content } }); }
// component import { addNote } from './actions'; export default function NoteForm() { return ( <form action={addNote}> <textarea name="content" /> <button type="submit">Save</button> </form> ); }
  • Forms post automatically; result can redirect, throw errors, or revalidate caches.

Validation ✅

  • Use Zod/Yup inside the action:
const schema = z.object({ content: z.string().min(1) }); const { content } = schema.parse(Object.fromEntries(formData));
  • Return structured errors to client components or throw Error to trigger error.tsx.
  • Combine with client-side hints for better UX but always validate server-side.

Optimistic UI ⚡

  • Update client state immediately, then call action.
  • Use useOptimistic (React 19) or manual state updates + startTransition.
const [optimisticNotes, addOptimisticNote] = useOptimistic(notes); <form action={async formData => { addOptimisticNote({ ...newNote }); await addNote(formData); }} >

File Uploads 📁

  • Actions receive FormData, so file inputs can be read via formData.get('file') returning File.
  • For large files, prefer presigned URLs or direct uploads to S3/Supabase via route handlers.
  • Validate MIME type/size before persisting.

Security 🛡️

  • Server actions honor the same auth context as server components (cookies, headers).
  • Mitigate CSRF by relying on same-site cookies + checking origin headers when needed (forms default to POST same-origin).
  • Keep actions small and audited—they run server-side with your credentials.

Analogy: server actions are pneumatic tubes in an old-school bank—drop the form in, and it shoots straight to the vault without detouring through public streets (API routes).

Last updated on