Server Actions and useActionState

Validate a form with createServerValidate in a React 19 action, so the server parses the FormData by field type, applies the form's rules and sends errors back to repaint the form.

View as Markdown

Server Actions and useActionState

What it combines

  • createServerValidate(form) from @saastro/forms/standard-schema — an action (prevState, formData) => Promise<ServerValidateState> (Standard Schema)
  • React 19 useActionState — keeps the state the action returns and calls it when the <form action> submits
  • One form config — shared by the page and the action, so both apply the same rules

Send it empty, then with an age of 12, then filled in properly. The action here runs in the page, but it is the code you would put behind 'use server': nothing is sent anywhere.

import { FormBuilder } from '@saastro/forms';
import type { ValidatableForm } from '@saastro/forms/validation';
import {
  createServerValidate,
  initialServerValidateState,
  type ServerValidateState,
} from '@saastro/forms/standard-schema';
import { useActionState } from 'react';

/** One config, shared by the page and the action: the rules cannot drift apart. */
export function createConfig() {
  return FormBuilder.create('server-action-signup')
    .addField('email', (f) => f.type('email').label('Email').required().email())
    .addField('age', (f) => f.type('number').label('Age').required().numberRange(18, 120))
    .addField('terms', (f) => f.type('checkbox').label('I accept the terms').mustBeTrue())
    .addStep('main', ['email', 'age', 'terms'])
    .build();
}

// `FormConfig.fields` also admits custom field types, which `ValidatableForm` does not: cast.
const validate = createServerValidate(createConfig() as unknown as ValidatableForm);

/**
 * The action. In Next.js this file (or just this function) starts with `'use server'`;
 * it only runs on the server there. It parses the FormData by field type, validates it with
 * the form's rules and returns a serialisable state.
 */
export async function send(
  prev: ServerValidateState,
  formData: FormData,
): Promise<ServerValidateState> {
  const state = await validate(prev, formData);
  if (state.status === 'valid') {
    // save(state.data) — typed values: age is a number, terms is true.
    return { status: 'valid', data: state.data };
  }
  return state;
}

/** A plain <form action>: React 19 sends its FormData to the action and keeps the state it returns. */
export function SignupForm({ action = send }: { action?: typeof send }) {
  const [state, formAction, pending] = useActionState(action, initialServerValidateState);
  const errors = state.errors ?? {};
  const values = state.values ?? {};
  const field = 'flex flex-col gap-1';
  const input = 'rounded-md border px-3 py-2';

  return (
    <form action={formAction} noValidate className="space-y-4">
      {errors._form && (
        <p role="alert" className="text-sm text-red-600">
          {errors._form.join(' ')}
        </p>
      )}

      <div className={field}>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          name="email"
          type="email"
          defaultValue={String(values.email ?? '')}
          aria-invalid={Boolean(errors.email)}
          aria-describedby={errors.email ? 'email-error' : undefined}
          className={input}
        />
        {errors.email && (
          <p id="email-error" className="text-sm text-red-600">
            {errors.email.join(' ')}
          </p>
        )}
      </div>

      <div className={field}>
        <label htmlFor="age">Age</label>
        <input
          id="age"
          name="age"
          type="number"
          defaultValue={String(values.age ?? '')}
          aria-invalid={Boolean(errors.age)}
          aria-describedby={errors.age ? 'age-error' : undefined}
          className={input}
        />
        {errors.age && (
          <p id="age-error" className="text-sm text-red-600">
            {errors.age.join(' ')}
          </p>
        )}
      </div>

      <div className={field}>
        <label className="flex items-center gap-2">
          <input
            name="terms"
            type="checkbox"
            defaultChecked={values.terms === true}
            aria-invalid={Boolean(errors.terms)}
          />
          I accept the terms
        </label>
        {errors.terms && <p className="text-sm text-red-600">{errors.terms.join(' ')}</p>}
      </div>

      <button type="submit" disabled={pending} className="rounded-md border px-4 py-2">
        {pending ? 'Sending…' : 'Sign up'}
      </button>

      {state.status === 'valid' && <p role="status">Thanks, you are in.</p>}
    </form>
  );
}

The code

The Code tab above has createConfig(), the send action and a SignupForm that uses it. The action is three lines:

const validate = createServerValidate(createConfig());

export async function send(prev: ServerValidateState, formData: FormData) {
  const state = await validate(prev, formData);
  if (state.status === 'valid') await save(state.data);
  return state;
}

How it works

  • parseFormData runs first: a checkbox becomes a boolean (unchecked is false), a number field a number (empty means absent), a repeated key a list.
  • The state has three shapes: idle (not sent yet), invalid with errors (field name → messages, _form for form-level problems) and valid with data.
  • On invalid, values carries what was received, so the form can be repainted with defaultValue.
  • Passwords, one-time codes and signatures are not returned in values, and neither are files.
  • The state is serialisable, so it can cross from a Server Action to the client.

Caveats

  • 'use server' is yours to add — the helper is React-free and runs anywhere; making it a Server Action is a framework matter (Next.js, for instance). In a client-only app the action simply runs in the browser, as in the demo above, and is no protection.
  • This is a plain <form>: <Form /> renders and validates in the browser with React Hook Form. Use the action for forms you write by hand, or as the server’s second check behind <Form /> (Validate the same rules on the server).
  • Files stay in data — use them on the server and do not return that state to the client.
  • A hidden field is not validated unless you pass { validateHidden: true }.
  • Validation is not authorisation — add your own auth, rate limiting and bot protection.

Variations

  • Return { ...state, data: undefined } after saving if the client has no use for the validated values.
  • Use toStandardSchema(form) to validate a JSON body in a route handler with the same rules.