Server Actions

0/2 in this phase0/36 across the roadmap

📖 Concept

Server Actions are a way to handle form submissions and data mutations without writing a manual API route. They are asynchronous functions that are executed on the server but called from your client-side forms.

Why they are cool:

  1. No API Boilerplate: No more fetch('/api/submit', { method: 'POST' }).
  2. Type Safety: If you use TypeScript, your server-side function and client-side form share the same types.
  3. Progressive Enhancement: Server Actions work even if JavaScript is disabled in the user's browser (if they are used inside a standard form).
  4. Integration with useFormStatus and useFormState: Easy ways to handle loading and error states for your forms.

💻 Code Example

codeTap to expand ⛶
1// 1. Define the action (actions.ts)
2'use server';
3
4export async function createTodo(formData: FormData) {
5 const title = formData.get('title');
6
7 // Save to database
8 await db.todo.create({ data: { title } });
9
10 // Tell Next.js to refresh the UI
11 revalidatePath('/todos');
12}
13
14// 2. Use the action in a form (page.tsx)
15function TodoPage() {
16 return (
17 <form action={createTodo}>
18 <input name="title" type="text" className="border" />
19 <button type="submit">Add Todo</button>
20 </form>
21 );
22}

🏋️ Practice Exercise

  1. Implement a 'Contact Form' using a Server Action.
  2. Use revalidatePath or revalidateTag to update the UI after a mutation.
  3. Use the useFormStatus hook to show a 'Saving...' state on your submit button.
  4. Add 'Server-side Validation' to your action (using a library like Zod) and return errors to the UI.

⚠️ Common Mistakes

  • Forgetting to add 'use server' at the top of the file or function.

  • Performing sensitive actions without checking the user's session (Authentication!).

  • Not handling server-side errors gracefully, leading to crashes.

  • Thinking Server Actions are only for forms (they can also be called like regular async functions).

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Server Actions