Validation and error handling in actions

Intermediate · 7 min

Validate FormData on the server with a schema, return expected errors as state with useActionState, and leave unexpected failures to error boundaries.

Before thisForms and pending states

Codevolution · 7 min

Validation and error handling in actions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Client-side validation is a convenience; the server must validate every Server Action input again, because an action can be called without your form.
  • Treat expected errors, such as an invalid email or a failed request, as return values rather than thrown exceptions, and show them from the state returned by useActionState.
  • A schema library such as Zod gives you safeParse, which returns success or a structured list of field errors without throwing.
  • Unexpected failures, bugs and outages, should throw so the nearest error boundary renders the fallback instead of being swallowed by try/catch.
  • Shape what an action returns to what the UI renders, because return values are serialized to the browser.

Two kinds of failure

Not all errors deserve the same treatment. The Next.js docs split them in two.

Expected errors happen when the app works as designed: the email is malformed, the username is taken, the upstream API said no. They are information for the user. Uncaught exceptions are bugs and outages: the database is down, a variable is undefined. Nothing the user typed can fix them.

For the first kind, the docs advise avoiding try/catch and throwing; model the error as a return value. For the second, let it throw and let an error boundary (error.tsx, or catchError for a component) show the fallback.

Validate on the server, always

Browser validation (required, type="email") is a convenience. The action is a public endpoint, as the Server Actions lesson showed, so it must check its own input. The docs suggest a schema library such as Zod or Valibot:

'use server'
import { z } from 'zod'

const schema = z.object({
  email: z.string().email('Invalid email'),
})

export async function createUser(prevState: { message: string; errors?: Record<string, string[]> }, formData: FormData) {
  const parsed = schema.safeParse({ email: formData.get('email') })

  if (!parsed.success) {
    return { message: 'Please fix the errors below.', errors: parsed.error.flatten().fieldErrors }
  }

  // mutate data
  return { message: 'Signed up.' }
}

safeParse never throws. It returns success: true with data, or success: false with an error you can turn into field messages. The action returns the errors; it does not throw them. Zod’s API varies between major versions, so check the version you install against its docs for the exact method names.

Show the errors with useActionState

The form reads the returned object. Because it reads state, the form component is a Client Component, as in the last lesson:

'use client'
import { useActionState } from 'react'
import { createUser } from '@/app/actions'

const initialState = { message: '' }

export function Signup() {
  const [state, formAction, pending] = useActionState(createUser, initialState)

  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" aria-describedby="email-error" />
      <p id="email-error" aria-live="polite">{state.errors?.email?.[0]}</p>
      <button disabled={pending}>Sign up</button>
    </form>
  )
}

Because the action now receives the previous state first, its signature is (prevState, formData). If you forget that and keep (formData), the FormData argument will actually be the old state. That is the most common mistake when converting a plain action.

Failures from other services

The docs’ example for a failed request is the same pattern: call the API, check res.ok, and if it failed, return { message: 'Failed to create post' }. The user gets a message and can retry.

Do not return raw errors or database rows. Action return values are serialized to the browser, so the docs advise shaping them to what the UI renders. A database error message can include table names you would rather keep private.

Letting real errors throw

Anything the user cannot act on should throw. error.tsx in the route catches it and renders a fallback; it is a Client Component that receives the error and a reset function. Error handling and not found covers it. Using try/catch around the whole action and returning “something went wrong” hides bugs from the boundary and from your error tracking.

redirect() throws on purpose to stop the action. Never call it inside a try block you also use to catch real errors, or the catch will swallow it. Put it after the block.

What the video covers

Codevolution’s tutorial walks through error state for a React form with useActionState. By its chapters: setting up error-handling types, implementing the hook, validating form data, displaying error messages, handling submission, and troubleshooting common errors. It hand-writes its checks instead of using a schema library, and does not discuss expected versus unexpected errors, so those parts are in this lesson. It is a Next.js 15 recording; the hook usage is unchanged in 16.

Where this fits

The form now validates and explains. Next: optimistic updates, which make the UI react before the server answers.

Check yourself

  1. 01Why validate in the Server Action if the form already uses required and type=email?

    Those attributes only help honest users in a browser, while the action is a POST endpoint anyone can call directly, so the server has to check the data itself.

  2. 02What is the difference between an expected error and an uncaught exception in Next.js?

    Expected errors happen in normal operation, like failed validation, and are modeled as return values shown in the UI, while uncaught exceptions are bugs or outages that throw to an error boundary.

  3. 03Why does an action used with useActionState take prevState as its first argument?

    useActionState passes the previous state to the action so it can return the next state, which pushes the FormData to the second parameter.

  4. 04What does schema.safeParse return, and why is that handy in an action?

    An object with success true and data, or success false and an error you can flatten into field messages, so the action can return the errors as state instead of throwing.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark