Skip to content
Next.js Fundamentals

Lesson 5 of 6 · 22 min

x
5/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Server Actions, Form Mutations & Optimistic UI

Server Actions are asynchronous functions defined with the 'use server' directive that execute on the server. They can be invoked directly from HTML forms, event handlers, or Client Components, eliminating the need to write manual REST or GraphQL API route handlers for data mutations.

Server Actions seamlessly integrate with React 19 hooks like useActionState and useOptimistic. useOptimistic allows the UI to render immediate state updates before the server mutation completes, rolling back automatically if the server request fails.

Before
Legacy API Route Handler + Manual Fetch Mutation
1// client component calling /api/comments endpoint2const handleSubmit = async (e) => {3  e.preventDefault();4  await fetch('/api/comments', { method: 'POST', body: JSON.stringify({ text }) });5  router.refresh();6};
After
Inline Server Action with Form Action Integration
1// app/actions.ts2'use server';3import { db } from '@/lib/db';4import { revalidatePath } from 'next/cache';5 6export async function addComment(formData: FormData) {7  const text = formData.get('comment') as string;8  await db.comment.create({ data: { text } });9  revalidatePath('/comments');10}11 12// app/form.tsx13import { addComment } from './actions';14export function CommentForm() {15  return (16    <form action={addComment}>17      <input name="comment" required />18      <button type="submit">Post Comment</button>19    </form>20  );21}

Exercise

Create a Server Action that receives form data, validates the inputs, inserts a database record, and purges the page cache with revalidatePath.

Check your understanding

  • Where must the 'use server' directive be placed?Show answer

    Answer

    At the top of a dedicated server actions file, or at the top of an individual async function inside a Server Component.
  • What advantage does form action={serverAction} offer for user experience?Show answer

    Answer

    Progressive enhancement: forms can submit even before client JavaScript has fully downloaded and hydrated.
Previous

Progress is saved in this browser.

Next Lesson