Server Actions ("use server"): Type-Safe Mutations Without API Endpoints
Server Actions ("use server"): Type-Safe Mutations Without API Endpoints
In traditional web development, submitting a form required creating an API endpoint (/api/feedback), setting up body parsers, managing HTTP methods, writing client-side fetch logic, and synchronizing state. Server Actions revolutionize data mutations by allowing client components and forms to invoke asynchronous server-side functions directly using the "use server" directive.
1. What are Server Actions?
A Server Action is an asynchronous function that executes exclusively on the server. They can be invoked:
- Directly inside HTML
<form action={myAction}>elements (works even if JavaScript is disabled!). - Programmatically from client components via event handlers or React hooks.
- Provide end-to-end TypeScript type safety between the UI form and the database mutation.
2. Defining Server Actions in a Dedicated File
Placing server actions in a dedicated file marked with 'use server' allows them to be shared across Server and Client Components:
3. Consuming Server Actions in Components
Multiple Choice Questions
<form action={action}> compared to traditional onSubmit with fetch?action attribute of an HTML <form>?'use client'?revalidatePath('/courses') inside a Server Action that adds a new course?Form Handling with useActionState, useFormStatus & Zod Validation
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.