Q14: What are Server Actions and how do they eliminate API endpoints?
Server Actions are asynchronous functions executed directly on the server. Annotated with 'use server', they can be called from client form submissions or event handlers to perform data mutations, set cookies, and revalidate cached paths without manual API route boilerplate.
Server Action Definition and Usage
// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
export async function updateProfile(formData) {
const name = formData.get('name');
await db.user.update({ where: { id: 1 }, data: { name } });
revalidatePath('/profile'); // Invalidate static cache
}💡 Server Actions run on Node.js/Edge servers, performing direct DB writes and cache revalidations.
Key Takeaways
- Annotated using
'use server'directive. - Can be invoked directly from
<form action={myAction}>or client button event callbacks.
Knowledge Check
Which directive marks a function or file as an executable Server Action in Next.js?