Validation and error handling in actions
Validate FormData on the server with a schema, return expected errors as state with useActionState, and leave unexpected failures to error boundaries.
Validation and error handling in actions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
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
Why 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.
What 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.
Why 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.
What 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
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.