| | |

Zod 24 🛡️ Next.js Server Actions — Validating FormData with safeParse and flatten()

⏱️ Estimated read: 10 min | |

A Next.js Server Action receives FormData, not a typed object. The form entries are strings, and the handler has no compile-time guarantee about which fields are present or what they contain. Zod’s safeParse converts the raw entries into the schema’s output type, or returns a structured error that the client can map back to fields. The flatten() method—now z.flattenError() in Zod v4—is the formatter that turns the issues array into the { fieldErrors, formErrors } shape that useActionState expects.

This chapter covers the Server Action validation pattern with safeParse, the error formatting with z.flattenError(), and the useActionState wiring that connects the server result to the client form. The sections that follow walk through the action, the error shape, and the client consumption.

Key point: In a Server Action, call Schema.safeParse({ field: formData.get("field") }) and return z.flattenError(result.error).fieldErrors on failure; the client’s useActionState receives that object and renders the errors per field.


a. The Server Action with safeParse

A Server Action is an async function marked with "use server". It receives FormData as its argument and returns a serializable value that React’s useActionState can hold. The validation happens at the top of the function, before any database write or side effect.

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

import { z } from "zod";
import { revalidatePath } from "next/cache";

const CreatePostSchema = z.object({
  title: z.string().min(3, "Title must be at least 3 characters."),
  content: z.string().min(10, "Content must be at least 10 characters."),
});

export type FormState = {
  errors?: {
    title?: string[];
    content?: string[];
  };
  message?: string | null;
  success?: boolean;
};

export async function createPost(
  prevState: FormState,
  formData: FormData
): Promise<FormState> {
  const validatedFields = CreatePostSchema.safeParse({
    title: formData.get("title"),
    content: formData.get("content"),
  });

  if (!validatedFields.success) {
    return {
      errors: z.flattenError(validatedFields.error).fieldErrors,
      message: "Missing fields. Failed to create post.",
    };
  }

  const { title, content } = validatedFields.data;

  await db.post.create({ data: { title, content } });
  revalidatePath("/posts");

  return { success: true, message: "Post created." };
}

The safeParse call is the gate. If it fails, the action returns before touching validatedFields.data. The formData.get("title") call returns string | File | null, which is why the schema must handle the raw input type. For a string field, z.string() rejects null and File, which is the correct behavior—a missing form field is an error, not an empty string .


b. Error formatting with z.flattenError()

In Zod v4, the ZodError instance method .flatten() is deprecated, and the top-level function z.flattenError() replaces it . The function returns { formErrors, fieldErrors }, where formErrors contains issues at the root path ([]) and fieldErrors maps each field name to an array of messages .

const result = CreatePostSchema.safeParse(data);

if (!result.success) {
  const { formErrors, fieldErrors } = z.flattenError(result.error);
  // formErrors: [] (no root-level issues)
  // fieldErrors: { title: ["Title must be at least 3 characters."], ... }
}

The fieldErrors object is what the client needs. Each key is a field name, and each value is an array of messages for that field. The useActionState hook receives the entire return value from the action, and the client component reads state.errors.title?.[0] to display the first message .

The z.flattenError() function is for flat schemas—one level deep. For nested objects, z.treeifyError() returns a tree that mirrors the schema’s shape, and the client navigates it with optional chaining . The choice depends on the form’s structure: a flat form with title and content uses flattenError; a form with a nested address object uses treeifyError and a tree-shaped error state.


c. The client wiring with useActionState

The client component calls useActionState(action, initialState), which returns the current state, the form action to pass to <form action={...}>, and a pending flag. The state is the return value of the Server Action, typed by the action’s return type.

// app/post-form.tsx
"use client";

import { useActionState } from "react";
import { createPost, type FormState } from "./actions";

const initialState: FormState = {
  message: null,
  errors: {},
};

export function PostForm() {
  const [state, formAction, pending] = useActionState(createPost, initialState);

  return (
    <form action={formAction}>
      <div>
        <label htmlFor="title">Title</label>
        <input id="title" name="title" disabled={pending} />
        {state.errors?.title && (
          <p role="alert">{state.errors.title[0]}</p>
        )}
      </div>

      <div>
        <label htmlFor="content">Content</label>
        <textarea id="content" name="content" disabled={pending} />
        {state.errors?.content && (
          <p role="alert">{state.errors.content[0]}</p>
        )}
      </div>

      <button type="submit" disabled={pending}>
        {pending ? "Creating…" : "Create post"}
      </button>

      {state.message && <p>{state.message}</p>}
    </form>
  );
}

The name attribute on each input must match the key the action reads with formData.get(). The disabled={pending} prevents double submission. The error display reads state.errors?.title?.[0] because fieldErrors maps each field to an array, and the form shows the first message .

The useActionState hook replaced useFormState in React 19, and it is imported from react, not react-dom . The initial state must match the action’s return type, which is why the FormState type is exported from the action file and imported by the client.


Complete Example Session

// ============================================
// PART 1: THE SCHEMA AND STATE TYPE
// ============================================
// app/schemas.ts
import { z } from "zod";

export const SignupSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters."),
  email: z.email("Enter a valid email address."),
  password: z.string().min(8, "Password must be at least 8 characters."),
});

export type SignupState = {
  errors?: {
    name?: string[];
    email?: string[];
    password?: string[];
  };
  message?: string | null;
  success?: boolean;
};

// ============================================
// PART 2: THE SERVER ACTION
// ============================================
// app/actions.ts
"use server";

import { SignupSchema, type SignupState } from "./schemas";

export async function signup(
  prevState: SignupState,
  formData: FormData
): Promise<SignupState> {
  const result = SignupSchema.safeParse({
    name: formData.get("name"),
    email: formData.get("email"),
    password: formData.get("password"),
  });

  if (!result.success) {
    return {
      errors: z.flattenError(result.error).fieldErrors,
      message: "Please correct the errors below.",
    };
  }

  await createUser(result.data);
  return { success: true, message: "Account created." };
}

// ============================================
// PART 3: THE CLIENT FORM
// ============================================
// app/signup-form.tsx
"use client";

import { useActionState } from "react";
import { signup, type SignupState } from "./actions";

const initialState: SignupState = { message: null, errors: {} };

export function SignupForm() {
  const [state, formAction, pending] = useActionState(signup, initialState);

  return (
    <form action={formAction}>
      <label htmlFor="name">Name</label>
      <input id="name" name="name" disabled={pending} />
      {state.errors?.name && <p role="alert">{state.errors.name[0]}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" disabled={pending} />
      {state.errors?.email && <p role="alert">{state.errors.email[0]}</p>}

      <label htmlFor="password">Password</label>
      <input id="password" name="password" type="password" disabled={pending} />
      {state.errors?.password && <p role="alert">{state.errors.password[0]}</p>}

      <button type="submit" disabled={pending}>
        {pending ? "Signing up…" : "Sign up"}
      </button>

      {state.message && <p>{state.message}</p>}
    </form>
  );
}

The parts covered the schema and state type, the Server Action with safeParse and z.flattenError(), and the client form with useActionState.


Quick Reference

Server Action Pattern

StepCode
Read form dataformData.get("field")
ValidateSchema.safeParse({ field: formData.get("field") })
Format errorsz.flattenError(result.error).fieldErrors
Use dataresult.data (typed)
Return{ errors, message, success? }

Error Formatting (v4)

FunctionOutputUse
z.flattenError(){ formErrors, fieldErrors }Flat forms
z.treeifyError()Nested treeNested forms
z.prettifyError()StringLogging

useActionState

ReturnTypePurpose
stateAction return typeErrors, message, success
formActionFunctionPass to <form action={...}>
pendingbooleanDisable inputs and button

Best Practices

✅ Do This:

// Validate at the top of the action
const result = Schema.safeParse({ ... });                    // ✅

// Use z.flattenError in v4
errors: z.flattenError(result.error).fieldErrors;            // ✅

// Match input name to formData.get key
<input name="email" />; formData.get("email");               // ✅

// Export the state type for the client
export type FormState = { ... };                             // ✅

❌ Don’t Do This:

// Use deprecated .flatten()
result.error.flatten().fieldErrors;                          // ❌

// Use parse without try/catch
const data = Schema.parse({ ... });                          // ❌

// Forget the name attribute
<input id="email" />; // formData.get("email") is null       // ❌

// Use useFormState (React 18)
import { useFormState } from "react-dom";                    // ❌

Common Pitfalls

PitfallWhy It HappensFix
formData.get returns nullInput has no name attributeAdd name matching the key
Error shape wrong after v4 upgrade.flatten() deprecatedUse z.flattenError()
State type mismatchAction returns different shapeExport and import the type
Double submissionNo disabled={pending}Disable inputs during pending
useFormState not foundReact 18 importUse useActionState from react

Real-World Examples

1. SafeParse with FormData

const result = Schema.safeParse({ email: formData.get("email") });

2. Flatten error

z.flattenError(result.error).fieldErrors;

3. Client error display

{state.errors?.email && <p>{state.errors.email[0]}</p>}

4. useActionState

const [state, formAction, pending] = useActionState(action, initial);

5. Disable during pending

<input disabled={pending} />

6. Success message

{state.success && <p>Created.</p>}

7. Revalidate path

revalidatePath("/posts");

8. Treeify for nested

z.treeifyError(result.error).properties.address...

9. Initial state

const initial: FormState = { errors: {}, message: null };

10. Action signature

async function action(prev: FormState, formData: FormData): Promise<FormState>

Visual

Server Action Flow

┌─────────────────────────────────────────────────────────┐
│  CLIENT SUBMIT                                          │
│  <form action={formAction}>                             │
│         │                                               │
│         ▼                                               │
│  SERVER ACTION                                          │
│  formData received                                      │
│         │                                               │
│         ▼                                               │
│  Schema.safeParse({ field: formData.get("field") })     │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│  success   failure                                      │
│    │         │                                          │
│    ▼         ▼                                          │
│  result.data  z.flattenError().fieldErrors              │
│    │         │                                          │
│    ▼         ▼                                          │
│  DB write   return { errors, message }                  │
│    │         │                                          │
│    ▼         ▼                                          │
│  return     useActionState state                        │
│  { success }  → render errors                           │
└─────────────────────────────────────────────────────────┘

Error Shape

┌─────────────────────────────────────────────────────────┐
│  z.flattenError(result.error)                           │
│                                                         │
│  {                                                      │
│    formErrors: [],           // root-level issues       │
│    fieldErrors: {                                       │
│      email: ["Enter a valid email."],                   │
│      password: ["Too short."]                           │
│    }                                                    │
│  }                                                      │
│                                                         │
│  Client reads: state.errors.email[0]                    │
└─────────────────────────────────────────────────────────┘

useActionState Wiring

┌─────────────────────────────────────────────────────────┐
│  const [state, formAction, pending] =                   │
│    useActionState(action, initialState)                 │
│                                                         │
│  state       → action's return value                    │
│  formAction  → <form action={formAction}>               │
│  pending     → disable inputs, show spinner             │
│                                                         │
│  The action's return type is the state type.            │
└─────────────────────────────────────────────────────────┘

v3 vs v4 Error Formatting

┌─────────────────────────────────────────────────────────┐
│  v3 (DEPRECATED)          v4 (CURRENT)                  │
│                                                         │
│  error.flatten()          z.flattenError(error)         │
│    .fieldErrors             .fieldErrors                │
│                                                         │
│  Instance method          Top-level function            │
│  Removed in v4            Recommended                   │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Action inputFormData
ValidationSchema.safeParse({ field: formData.get("field") })
Error formatter (v4)z.flattenError(result.error).fieldErrors
Deprecated formatterresult.error.flatten()
Client hookuseActionState from react
State typeAction return type, exported and imported
Nested errorsz.treeifyError()

Key takeaways:

  • Server Actions receive FormData, not typed objects. The safeParse call converts the raw entries into the schema’s output type, and the handler uses result.data only after the success check .
  • z.flattenError() replaces .flatten() in Zod v4. The instance method is deprecated, and the top-level function returns the same { formErrors, fieldErrors } shape that the client expects .
  • The fieldErrors object is the client’s error map. Each key is a field name, each value is an array of messages. The client reads state.errors.fieldName?.[0] to display the first error .
  • useActionState wires the action to the form. It returns the state, the form action, and a pending flag. The state is the action’s return value, and the pending flag disables inputs during submission .
  • The input name attribute must match the formData.get key. A missing name produces null, and the schema rejects it with a type error rather than a validation message .

Remember: A Server Action is a public endpoint. The client can call it directly, and the form validation in the browser never runs. The safeParse call at the top of the action is the security gate, and z.flattenError() is how the gate’s verdict reaches the form. Export the state type, match the input names, and use the v4 formatter. The action validates, the client displays, and the database write happens only after both agree.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!