Sub topic 7
Using Server Functions as form actions
This chapter assumes you know React components, props, state and hooks, async/await, and how HTML forms and FormData work. It also assumes you have read the earlier chapters on what "use server" marks and how to define Server Functions. Here you will wire a Server Function to a <form>, see what React does when the form is submitted, and learn the errors people commonly make.
What a form action is
React lets you pass a function to the action prop of a <form>. Plain HTML only accepts a URL string there. In React, a function value means "call this function when the form is submitted."
When the user submits, React does three things:
- It prevents the browser's default full-page navigation.
- It builds a
FormDataobject from the form's named fields. - It calls your function with that
FormDataas the argument.
If the function is a Server Function, the call crosses the network. React sends the FormData to the server, runs the function there, and returns the result to the client.
The name attribute on each input decides the key in FormData. An input without a name is not included.
The simplest case: a Server Component form
The most direct setup defines the Server Function inside a Server Component and passes it to action.
// app/page.js (a Server Component)
import { db } from './db';
export default function Page() {
async function createNote(formData) {
'use server';
await db.notes.insert({ title: formData.get('title') });
}
return (
<form action={createNote}>
<input name="title" required />
<button type="submit">Add note</button>
</form>
);
}Points to notice:
createNoteis declared inside the component, but the'use server'directive at the top of its body makes it a Server Function. Its code stays on the server.- The form needs no
onSubmit, nofetchcall and no API route. React and your framework supply the transport. formData.get('title')returns astring, aFile, ornull. It never returns a number or a boolean. Convert values yourself.
The same function can live in a separate file instead, which lets Client Components import it:
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(formData) {
const title = formData.get('title');
await db.notes.insert({ title });
}A file-level 'use server' marks every exported async function in the file as a Server Function. A non-async export in that file causes a build error, because every export must be a function the client can call over the network.
Progressive enhancement
A form wired to a Server Function in a Server Component can work before any JavaScript has loaded. This is called progressive enhancement: the basic behavior works on the plainest platform, and richer behavior is added when more is available.
The sequence looks like this:
- The server renders the form into HTML. React encodes the Server Function reference into the form so the browser can submit it as an ordinary POST request.
- If JavaScript has not loaded (slow network, script blocked, hydration not finished), the browser submits the form natively. The server runs the function and responds with a fresh page.
- If JavaScript has loaded, React intercepts the submit and does the same work without a full reload.
This holds only when the form is set up in a way the framework can serialize without client code. A form that uses useActionState can still work before hydration if you pass a permalink as the third argument of the hook, which tells React which URL to submit to. In a Client Component, the form is hydrated first, and before then the submission may be queued or fall back to the server path, depending on your framework. Check how your framework handles this before you promise "works without JavaScript" to anyone.
Using a Server Function from a Client Component
Client Components cannot define Server Functions inline, because a Client Component's code is shipped to the browser. They can import functions from a 'use server' file, and they can receive Server Functions as props from a Server Component.
// app/NoteForm.js
'use client';
import { createNote } from './actions';
export function NoteForm() {
return (
<form action={createNote}>
<input name="title" />
<button type="submit">Add note</button>
</form>
);
}In the browser bundle, the imported createNote is not the real function. The bundler replaces it with a reference, a small stub that tells React which server function to call. Calling the stub sends a request to the server.
Returning results: useActionState
A form action that returns nothing gives the user no feedback. To show validation messages or a success status, wrap the Server Function with useActionState. It returns three values: the latest state, a wrapped action to pass to the form, and a pending flag.
// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
await db.notes.insert({ title });
return { error: null };
}// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, { error: null });
return (
<form action={formAction}>
<input name="title" />
<button type="submit" disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}The key change is the signature. With useActionState, React calls the function with the previous state first and the FormData second. If you pass a function written as createNote(formData) to useActionState, formData will actually hold the previous state object, and formData.get will throw. This is the most common error when moving from a plain form action to useActionState.
The second argument to useActionState is the initial state. The value you return from the function becomes the next state, so it must be serializable, which the next section covers.
Return values must be serializable
Arguments and return values travel over the network, so they must be types React can serialize. Plain objects, arrays, strings, numbers, booleans, null, undefined, Date, Map, Set, BigInt, typed arrays, FormData, and Promises are supported. Functions (other than Server Functions), class instances, symbols, and DOM nodes are not.
A common mistake is returning an Error object or a database row that contains methods. Return a plain object with only the fields the UI needs. This also avoids leaking fields such as password hashes by accident.
Reading and validating FormData
FormData is untyped and the user controls it. Treat every field as unverified input.
| Task | Pattern |
|---|---|
| Read one text field | `String(formData.get('title') ?? '')` |
| Read a checkbox | `formData.get('done') === 'on'` |
| Read a number | `Number(formData.get('qty'))`, then check `Number.isInteger` |
| Read repeated fields | `formData.getAll('tag')` |
| Read a file | `formData.get('upload')` is a `File`; check `size` and `type` |
| Read all fields | `Object.fromEntries(formData)` (repeated keys collapse to the last value) |
A checkbox that is unchecked is absent from FormData, not false. A number input still yields a string.
Validation belongs in the Server Function even if the form has required or maxLength attributes. Those attributes only help honest users. Anyone can send a request directly to the endpoint without your form.
Resetting and keeping form values
After a successful action in React, uncontrolled form fields are reset automatically. That is convenient after a successful create, but it is annoying after a failed validation, because the user's typed text disappears.
The usual fix is to return the submitted values with the error and use them as defaultValue:
// app/NoteForm.js
'use client';
import { useActionState } from 'react';
import { createNote } from './actions';
export function NoteForm() {
const [state, formAction, isPending] = useActionState(createNote, {
error: null,
title: '',
});
return (
<form action={formAction}>
<input name="title" defaultValue={state.title} />
<button type="submit" disabled={isPending}>Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}// app/actions.js
'use server';
import { db } from './db';
export async function createNote(prevState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.', title };
}
await db.notes.insert({ title });
return { error: null, title: '' };
}Common errors
- The function is not async. A Server Function must be
async, even if it awaits nothing, because the call is always asynchronous from the client's view. - A missing
nameattribute.formData.get('title')returnsnulland you insert an empty record. - Wrong parameter order with
useActionState. The previous state comes first. - Using
'use server'where you meant'use client'.'use server'does not make a component run on the server. It marks callable functions. Components are server components by default in frameworks that support them, and'use client'marks the boundary. - Passing a non-serializable prop. Passing an inline arrow function from a Server Component to a Client Component fails unless the function is a Server Function.
- Skipping authorization. A form action is a public HTTP endpoint. Check the session and permissions inside the function, as the security chapter explains.
- Expecting redirects or revalidation to happen on their own. After a mutation, your framework decides how to refresh data. In Next.js, for example, you call
revalidatePathorredirectfrom inside the action.
Exercises
Exercise
A developer writes export async function addItem(formData) { ... } and passes it to useActionState(addItem, { error: null }). On submit, formData.get throws "get is not a function". What is wrong, and how do they fix it?
Show answer
With useActionState, React calls the function with the previous state as the first argument and the FormData second, so formData actually holds the state object. Change the signature to addItem(prevState, formData).
Exercise
A checkbox named done is unchecked when the user submits the form. What does formData.get('done') return, and how should you test for a checked box?
Show answer
It returns null, because unchecked checkboxes are not included in FormData. A checked box returns its value, which is 'on' by default, so test with formData.get('done') === 'on'.
Exercise
Why is a required attribute on an input not enough validation for a Server Function used as a form action?
Show answer
The attribute only affects the browser UI. Any client can send a request directly to the Server Function's endpoint without using your form, so the function must validate its own input.