# Server Actions

> The modern, API-less way to mutate data on the server directly from React components.

Subject: React | Lesson 47 of 48 | 6 min read
Interactive lesson: https://codewithanimation.in/react/server-actions
Previous: [React Server Components (RSCs)](https://codewithanimation.in/react/react-server-components.md) | Next: [Meta-Frameworks](https://codewithanimation.in/react/meta-frameworks.md)

## Mutating Data without API Routes

For years, if a user submitted a form in a React app, you had to: 1. Prevent default behavior. 2. Serialize the form data into JSON. 3. Call `fetch('/api/submit')`. 4. Write a separate API route handler on the backend to receive the request.

**Server Actions** eliminate this boilerplate. They are asynchronous JavaScript functions that run on the server, but can be called directly from your React components on the client.

## Seamless RPC (Remote Procedure Call)

When you pass a Server Action to a `<form action={submitData}>` or call it in an `onClick` handler, React automatically creates a hidden, secure API endpoint for you.

It handles the serialization, network request, and deserialization behind the scenes. You just write a function, mark it with `'use server'`, and call it. It feels like you are calling a local function, but it executes on the backend.

## The 'use server' Directive

To create a Server Action, you simply add the `'use server'` directive at the top of an async function (or at the top of a file containing multiple actions).

```tsx
// actions.ts
'use server'

export async function updateUsername(formData) {
  const newName = formData.get('name');
  await db.query('UPDATE users SET name = ?', [newName]);
}
```

You can then import this function into a Client Component and attach it directly to a form's `action` attribute.

## Common mistake: Security and Validation

Because Server Actions feel so magical and seamless, it is easy to forget that they are publicly accessible API endpoints.

If you write a Server Action, **anyone on the internet can call it**. You must always authenticate the user and validate the input data (using libraries like Zod) inside the Server Action before touching your database.

## Tip: Progressive Enhancement

If you pass a Server Action directly to a `<form action={...}>`, it works even if JavaScript is disabled in the browser! React uses standard HTML form submissions under the hood.

When JavaScript is enabled, React intercepts the submission and uses `fetch` for a smoother, page-refresh-free experience.

## Try it: The Disappearing API Route

Compare the traditional REST API approach for form submission with the modern Server Actions approach. Watch how the boilerplate vanishes.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/server-actions

## Check yourself

### Question 1

What is a React Server Action?

- A. A tool for configuring the Express.js server.
- B. An asynchronous function that executes on the server but can be called directly from a client-side component.
- C. A Redux middleware for handling asynchronous API requests.

Correct answer: B

Server Actions bridge the gap between client and server, allowing you to invoke server-side code seamlessly without manually setting up API endpoints.

### Question 2

How do you define a function as a Server Action?

- A. By using the `'use server'` directive inside or at the top of the file containing the function.
- B. By wrapping it in a `createServerAction()` utility.
- C. By placing it in a folder named `/actions`.

Correct answer: A

The `'use server'` directive tells the bundler to extract this function and turn it into a secure, hidden API endpoint.

### Question 3

True or False: Server Actions are secure by default, so you don't need to check user authentication inside them.

- A. True. React encrypts the payload so only authorized users can trigger it.
- B. False. A Server Action is just a hidden API endpoint. Anyone can trigger it, so you must always authenticate the user and validate input.

Correct answer: B

Server Actions are exposed to the internet. If you have an `adminDeleteUser` action, you MUST verify the caller is an admin inside that function, exactly like you would in a traditional REST API route.

## Remember this

- Server Actions eliminate the need for manual API routes for data mutations.
- Use the `'use server'` directive to mark an async function as a Server Action.
- React handles the network request (RPC) automatically behind the scenes.
- They work with `<form action={...}>` even without JavaScript (Progressive Enhancement).
- ALWAYS validate inputs and authenticate users inside your Server Actions.
