Skip to article content
FrontendXLesson 23 / 40

Actions and Server Functions

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

advanced · about 60 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Interview

What you will be able to do

#
  • Define a server function with the use server directive.
  • Wire a server function to a form action and to a client handler.
  • Apply server-side validation and authorization.

Overview

#

Server functions

A server function is a function marked with the use server directive. The client can call it like a normal async function, but it runs on the server. This gives you a typed RPC without writing an API route by hand.

snippet.tsx
'use server';

export async function createTodo(formData: FormData) {
  const text = String(formData.get('text') ?? '').trim();
  if (!text) return { error: 'Text is required' };
  await db.todo.create({ data: { text } });
  return { error: null };
}

Passing actions to a form

A form can take a server function as its action. The function receives the FormData, so the form works even before JavaScript loads, which is progressive enhancement.

snippet.tsx
<form action={createTodo}>
  <input name="text" />
  <button>Add</button>
</form>

Calling from a client component

A client component can import a server function and call it from an event handler or a transition. Inside a transition, the pending state is tracked and you can show a spinner.

snippet.tsx
'use client';
import { createTodo } from './actions';

function Add() {
  const [isPending, startTransition] = useTransition();
  return (
    <button onClick={() => startTransition(async () => { await createTodo(formData); })} disabled={isPending}>
      Add
    </button>
  );
}

useActionState for results

useActionState wraps an action so it can return a result and expose a pending flag, which is the cleanest way to render validation errors from the server.

Pitfall: trusting the client

A server function is a public endpoint. Validate and authorize on the server every time. Never trust a value because the client sent it. Treat every argument as untrusted input.

Pitfall: non-serializable arguments

Arguments and return values cross the network, so they must be serializable. Do not pass functions, class instances or DOM nodes.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    JavaScript is disabled. Does this form still submit?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    <form action={createTodo}>
      <input name="text" />
      <button>Add</button>
    </form>
    Choose the best answer
  2. Exercise 2Implement

    Write a server function that validates a name and returns an error, then call it from a form.

    starter.tsx
    // actions.ts
    export async function submitName(formData: FormData) {}
    
    // Form.tsx
    export function Form() { return null; }

    Reveal the reference answer
    reference.tsx
    // actions.ts
    'use server';
    export async function submitName(formData: FormData) {
      const name = String(formData.get('name') ?? '').trim();
      if (!name) return { error: 'Name is required' };
      await db.user.create({ data: { name } });
      return { error: null };
    }
    
    // Form.tsx
    'use client';
    import { useActionState } from 'react';
    import { submitName } from './actions';
    
    export function Form() {
      const [result, action, isPending] = useActionState(async (_prev, fd: FormData) => submitName(fd), { error: null });
      return (
        <form action={action}>
          <input name="name" />
          {result.error && <p role="alert">{result.error}</p>}
          <button disabled={isPending}>Save</button>
        </form>
      );
    }

    Authored expected output: The server validates and returns an error that the client renders.

    The server function validates on the server and returns a serializable result. useActionState exposes that result and the pending flag to the client form.

  3. Exercise 3Debug

    This server function can be tricked into deleting any record. Explain the flaw and fix it.

    starter.tsx
    'use server';
    export async function deletePost(id: string) {
      await db.post.delete({ where: { id } });
    }

    Reveal the reference answer
    reference.tsx
    'use server';
    import { auth } from './auth';
    export async function deletePost(id: string) {
      const session = await auth();
      if (!session) throw new Error('Unauthorized');
      const post = await db.post.findUnique({ where: { id } });
      if (post?.authorId !== session.userId) throw new Error('Forbidden');
      await db.post.delete({ where: { id } });
    }

    Authored expected output: Only the owner can delete the post; unauthenticated or non-owner calls are rejected.

    A server function is a public endpoint, so the client can call it with any id. Authentication and an ownership check on the server are required; the client cannot be trusted to send only ids it owns.

  4. Exercise 4Interview

    Explain how server functions change the way you build a form, and what security rules still apply.

    starter.tsx
    // form action, validation, authorization

    Reveal the reference answer
    reference.tsx
    A server function lets a form call server code directly, so you do not hand-write an API route or a fetch wrapper. The form can post to the function and get a typed result, and it works without client JavaScript. The security rules do not change: the function is a public endpoint, so you must validate every input and authorize every action on the server. Client-side checks are for feedback only. Treat arguments as untrusted and return serializable results.

    Authored expected output: A written explanation of the ergonomics plus the unchanged server-side validation and authorization requirements.

    The benefit is developer ergonomics, not a security boundary. The network boundary still requires server-side validation and authorization.

Common misconceptions

#
  • A server function runs on the client. It is called from the client but executes on the server.
  • Server functions remove the need for validation. They are public endpoints; validate and authorize on the server.
  • Arguments can be any value. They must be serializable to cross the network.
  • Form actions require JavaScript. A server function action works without client JavaScript, which is progressive enhancement.

Follow-up practice

#
  • react-server-components
  • react-data-fetching-caches

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.