Production Guide to Next.js 15 Server Actions & Mutations
A practical cheat sheet on handling form submissions, optimistic UI updates, revalidation, and error handling with Server Actions.
1. What Are Server Actions?
Server Actions are asynchronous functions executed on the server that can be invoked directly from Client or Server Components without manual REST endpoint definition.
'use server';
import { revalidatePath } from 'next/cache';
export async function createNoteAction(formData: FormData) {
const text = formData.get('text') as string;
if (!text || text.trim().length === 0) {
return { error: 'Note text cannot be blank.' };
}
// Save to DB or backend service
await db.note.create({ data: { text } });
revalidatePath('/notes');
return { success: true };
}2. Optimistic UI with useOptimistic
Provide instant UI feedback to the user before the server request completes using React’s useOptimistic Hook.
'use client';
import { useOptimistic } from 'react';
export function NoteList({ initialNotes, createAction }) {
const [optimisticNotes, addOptimisticNote] = useOptimistic(
initialNotes,
(state, newNote) => [newNote, ...state]
);
async function formAction(formData: FormData) {
const text = formData.get('text');
addOptimisticNote({ id: 'temp', text, isPending: true });
await createAction(formData);
}
return <form action={formAction}>{/* render list */}</form>;
}