Server Actions for Data Mutations
Define 'use server' functions to handle form mutations and invalidate cache with revalidatePath.
What Are Server Actions?
Server Actions are async functions marked with 'use server' that run exclusively on the server. They enable form submissions and data mutations without writing API route handlers.
Defining a Server Action
Add 'use server' at the top of the function (or the file) to create a Server Action. It can only be defined in Server Components or in dedicated actions.ts files.
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
await db.post.create({ data: { title } });
revalidatePath('/blog');
redirect('/blog');
}All lessons in this course
- fetch() with Cache Options in Next.js
- unstable_cache & React cache()
- Incremental Static Regeneration (ISR)
- Server Actions for Data Mutations