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:
- No API Boilerplate: No more
fetch('/api/submit', { method: 'POST' }). - Type Safety: If you use TypeScript, your server-side function and client-side form share the same types.
- Progressive Enhancement: Server Actions work even if JavaScript is disabled in the user's browser (if they are used inside a standard form).
- Integration with
useFormStatusanduseFormState: Easy ways to handle loading and error states for your forms.
💻 Code Example
code
1// 1. Define the action (actions.ts)2'use server';34export async function createTodo(formData: FormData) {5 const title = formData.get('title');67 // Save to database8 await db.todo.create({ data: { title } });910 // Tell Next.js to refresh the UI11 revalidatePath('/todos');12}1314// 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
- Implement a 'Contact Form' using a Server Action.
- Use
revalidatePathorrevalidateTagto update the UI after a mutation. - Use the
useFormStatushook to show a 'Saving...' state on your submit button. - 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
Was this topic helpful?