日本語

How to Receive Form Submissions with React Server Functions

​​React​Forms,Next.js,TypeScript,useActionState

With React 19 Server Functions, you can handle form submissions on the server in a single function. When you pass an async function marked with 'use server' to <form action>, that function is called on the server each time the form is submitted, and the inputs arrive as FormData. I built a small app on Next.js 16 (I did not create any API routes) and checked the shape of the submission request, what happens without JavaScript, and how errors are returned.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, Next.js 16.4.3 (App Router, built with Turbopack), React 19.3.1, TypeScript 7.0.2, and Chromium (Chrome for Testing 153). I only checked the production build (next build) and next start. I did not test the development server (next dev), frameworks other than Next.js, or a setup split across multiple servers.

Write the function in a 'use server' file and pass it to the form's action

According to the 'use server' reference, if you put 'use server' at the top of a file, every function exported from that file becomes a Server Function. Because it is called over the network, it must be an async function.

In the test, I built a form that adds a cat's name to a list. The list is saved in data/cats.json, and I read and write it with readCats and writeCats in lib/cats.ts. I wrote the Server Function like this:

ts
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { readCats, writeCats } from '../lib/cats';

export async function addCat(formData: FormData) {
  const name = formData.get('name');
  console.log('[addCat]', [...formData.keys()], name);
  if (typeof name !== 'string' || name.trim() === '') return;

  const cats = await readCats();
  await writeCats([...cats, name.trim()]);
  revalidatePath('/');
}

formData.get returns null if there is no entry with that name. A FormData value is either a string or a file (Blob or File). I made the function return without doing anything when the value is not a string or is empty.

The page stays a Server Component. It imports addCat and passes it to action.

tsx
// app/page.tsx
import { addCat } from './actions';
import { readCats } from '../lib/cats';

export default async function Page() {
  const cats = await readCats();
  return (
    <main>
      <ul>
        {cats.map((name, i) => (
          <li key={i}>{name}</li>
        ))}
      </ul>
      <form action={addCat}>
        <input name="name" aria-label="名前" />
        <button>追加</button>
      </form>
    </main>
  );
}

On submit, a single POST goes to the same URL

In the test environment (Ubuntu 24.04, Node.js 22, Chromium), I typed "Mike" into the input and clicked the Add button. The browser sent exactly one request:

text
POST の数: 1
method: POST  url: http://localhost:3000/  type: fetch
next-action ヘッダー: 40d4a2b83b25a6c69b3b7d004d6adc7e4c99bb5c40
content-type: multipart/form-data; boundary=(省略)

The destination was not a separate API URL but /, the same as the page. The browser tells the server which Server Function to call with a Next-Action header. The header value is the action ID that replaces the function in client-side code at build time, and it was the same string that follows $ACTION_ID_ in the request body below. The request body contained the input's value under its name (I have omitted the boundary strings):

text
----(区切り)
Content-Disposition: form-data; name="_1_$ACTION_ID_40d4a2b83b25a6c69b3b7d004d6adc7e4c99bb5c40"


----(区切り)
Content-Disposition: form-data; name="_1_name"

みけ
----(区切り)
Content-Disposition: form-data; name="0"

["$K1"]
----(区切り)--

The response was 200 text/x-component. The list became two cats, Tama and Mike, and the input was cleared. A value my test script had put on window before submitting was still there after submission. The page was loaded only once. In other words, only the list was updated without reloading the page.

The console.log inside addCat printed the following on the server side (in the terminal running next start):

text
[addCat] [ '$ACTION_ID_40d4a2b83b25a6c69b3b7d004d6adc7e4c99bb5c40', 'name' ] みけ

The FormData contained an entry starting with $ACTION_ID_ in addition to the name input. The Next.js forms guide also notes that if you extract everything with Object.fromEntries(formData), entries starting with $ACTION_ get mixed in. It is safest to pick out entries by name, as in formData.get('name').

The same form works without JavaScript

The <form> reference says that if you pass a Server Function to a <form> rendered by a Server Component, submission works even when JavaScript is disabled or has not yet loaded. The Next.js docs also state that forms in Server Components submit without JavaScript.

I turned off JavaScript in the browser and opened the same page. The form was rendered as the following HTML:

html
<form action="" enctype="multipart/form-data" method="POST">
<input type="hidden" name="$ACTION_ID_40d4a2b83b25a6c69b3b7d004d6adc7e4c99bb5c40">
<input aria-label="名前" name="name">
<button>追加</button>
</form>

The function to call is sent as the name of a hidden input instead of a header. I submitted "Kuro". The browser sent an ordinary form submission as a POST to /, and the response was 200 text/html. The whole page reloaded, and the list became three cats: Tama, Mike, and Kuro. The FormData that reached the server function contained only name.

Two-row diagram comparing with and without JavaScript. In the top row, the browser sends a POST with a Next-Action header via fetch, the server's addCat returns text/x-component, and only the list changes on the page. In the bottom row, the browser makes an ordinary form submission with a hidden $ACTION_ID_ input, the server returns text/html, and the whole page reloads
The same form action={addCat} is sent in two ways depending on whether JavaScript is available

On a static page, the list stays stale unless you call revalidatePath

In the next build output, this page was prerendered statically (○ /). I removed only the revalidatePath('/') line from addCat, rebuilt, and submitted with JavaScript enabled. "Mike" was added to data/cats.json, but the list on screen still showed only Tama. Reloading the page did not change it either.

text
送信から1秒後の li: [ 'たま' ]
再読み込みした後の li: [ 'たま' ]

According to the Next.js Server Actions guide, revalidatePath invalidates the cache for the path you specify. When called inside a Server Action (the Next.js term for a Server Function used for things like form submissions), it re-renders the current route on the server and includes the result in the same response. After you change data, specify with revalidatePath the path whose display depends on that data.

Use useActionState to return input errors

To receive a Server Function's return value and show it on screen, use useActionState. The React reference explains that you add useActionState when you want the pending state or the last return value. The Next.js guide says that to display input errors, you should make the form a Client Component and use useActionState. In this case, the Server Function receives the previous state as its first argument and the FormData as its second.

ts
// app/actions.ts (continued)
export type AddCatState = { error: string | null; name: string };

export async function addCatWithState(
  prevState: AddCatState,
  formData: FormData,
): Promise<AddCatState> {
  const name = formData.get('name');
  console.log('[addCatWithState]', prevState, name);
  if (typeof name !== 'string' || name.trim() === '') {
    return { error: '名前を入れてください', name: '' };
  }
  if (name.length > 10) {
    return { error: '名前は10文字までです', name };
  }

  const cats = await readCats();
  await writeCats([...cats, name.trim()]);
  revalidatePath('/with-state');
  return { error: null, name: '' };
}

When there is an error, the function returns the submitted name in the state as well. On the form side, I put that into the input's defaultValue.

tsx
// app/with-state/cat-form.tsx
'use client';

import { useActionState } from 'react';
import { addCatWithState } from '../actions';

export function CatForm() {
  const [state, formAction, isPending] = useActionState(addCatWithState, {
    error: null,
    name: '',
  });

  return (
    <form action={formAction}>
      <input name="name" aria-label="名前" defaultValue={state.name} />
      <button disabled={isPending}>追加</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

The page (app/with-state/page.tsx) renders the list the same way as /, with <CatForm /> placed below it. I submitted an empty name, a 12-character name, and then Shiro, in that order. The results are below. To see the state while submitting, the test script delayed the POST by 500 milliseconds.

Submitted name Button while submitting Error shown Input after submission List
(empty) Disabled Please enter a name Empty Tama
12-character name Disabled Name must be 10 characters or fewer Submitted name kept Tama
Shiro Disabled None Empty Tama, Shiro

Looking at the server output, the second and third calls received the previous return value as the first argument:

text
[addCatWithState] { error: null, name: '' } 
[addCatWithState] { error: '名前を入れてください', name: '' } ながいながいなまえのねこ
[addCatWithState] { error: '名前は10文字までです', name: 'ながいながいなまえのねこ' } しろ

Errors are shown even without JavaScript

The <form> reference states that to display a form submission error before JavaScript has loaded, the form must be rendered by a Client Component and the Server Function must be combined with useActionState. This form has that structure.

With JavaScript turned off, the form's HTML contained hidden inputs holding the information for the function to call and the initial state ({"error":null,"name":""}):

html
<form action="" enctype="multipart/form-data" method="POST">
<input type="hidden" name="$ACTION_REF_1">
<input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;605bcec8199f68a777859c5a5919ba3f1ec05320ce&quot;,&quot;bound&quot;:&quot;$@1&quot;}">
<input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:null,&quot;name&quot;:&quot;&quot;}]">
<input type="hidden" name="$ACTION_KEY" value="k625ff5bee164c3ceca102f434eb10857">
<input aria-label="名前" name="name" value="">
<button>追加</button>
</form>

When I submitted the 12-character name, the reloaded page showed the error "Name must be 10 characters or fewer", and the input kept the submitted name. The server function received, as its first argument, the initial state that had been in the hidden inputs.

Because the function can be called without the form, check input and permissions inside it

The Next.js docs warn that Server Functions can be called directly with a POST that does not go through the app's UI, so authentication and permissions must be checked inside the function. The React reference also asks you to treat all arguments as values the client can choose freely.

In the test, I pulled the $ACTION_ID_ value out of the page HTML and used curl to send a POST shaped like the no-JavaScript form. addCat had no length check, so a 30-character name was saved as-is. The script output is below (excerpted):

text
# (1) Sent without an Origin header, with a 30-character name
HTTP 200
# (2) Sent with the Origin of a different site
HTTP 500
# data/cats.json after sending
["たま","しろ","ねこねこねこねこねこねこねこねこねこねこねこねこねこねこねこ"]

The second request, with another site's Origin, was rejected without the function being called. The server printed this message (excerpted; a long line is wrapped here):

text
`x-forwarded-host` header with value `localhost:3000` does not match `origin` header
with value `attacker.example` from a forwarded Server Actions request. Aborting the action.
⨯ Error: Invalid Server Actions request.

Next.js rejects requests whose Origin and Host do not match. However, a request without an Origin header, like the curl one, only produced a warning on the server (Missing `origin` header from a forwarded Server Actions request.) and went through. Limits set on the page, such as maxLength on an input, have no effect on this kind of submission. Write length and format checks inside the Server Function, as addCatWithState does. Checks on whether the logged-in user may perform the operation also belong inside the function.

Point

Key points for receiving form submissions with a Server Function:

  • Pass an async function exported from a 'use server' file to <form action>, and read values by name, as in formData.get('name').
  • After you change data, specify with revalidatePath the path whose display depends on that data.
  • To show errors on screen, use useActionState in a Client Component form, and write the function to take (prevState, formData).
  • The function can be called without going through the UI, so do input and permission checks inside the function.

​Posted by 86