Sub topic 14
Submitting to an API and showing server errors
This chapter assumes you can build a form with useForm, register, and handleSubmit, and that you have connected a Zod schema with zodResolver. It also assumes you are comfortable with async/await and fetch. Here you will send validated values to an API and display the errors the server sends back.
Why server errors need their own path
A Zod schema checks the shape of the data. It cannot know whether an email is already registered, whether a coupon has expired, or whether the server is reachable. Only the server knows those things, and it answers after the schema has passed.
React Hook Form gives you setError for this. It writes into the same formState.errors object that the resolver fills. A field error from the server therefore renders with the same markup as a schema error, and you need no second error component.
The submit flow
handleSubmit runs the resolver first. It calls your onSubmit only when the schema passes. Your function then talks to the server and reports failures with setError.
isSubmitting is true from the moment handleSubmit starts until the promise returned by onSubmit settles. Always return a promise from onSubmit, which an async function does. If you forget to await the request, the button re-enables while the request is still running.
Showing a conflict on one field
A 409 Conflict response means the email already exists. The following component is complete. It handles that case, any other failed response, and a network failure.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function SignUpForm() {
const {
register,
handleSubmit,
setError,
formState: { errors, isSubmitting },
} = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
defaultValues: { email: "", password: "" },
});
const onSubmit = async (values: SignUpValues) => {
try {
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
setError(
"email",
{ type: "server", message: "This email is already registered" },
{ shouldFocus: true }
);
return;
}
if (!response.ok) {
setError("root.serverError", {
type: String(response.status),
message: "Something went wrong. Please try again.",
});
return;
}
} catch {
setError("root.serverError", {
type: "network",
message: "Could not reach the server. Check your connection.",
});
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register("password")} />
{errors.password && <p role="alert">{errors.password.message}</p>}
{errors.root?.serverError && (
<p role="alert">{errors.root.serverError.message}</p>
)}
<button type="submit" disabled={isSubmitting}>
Create account
</button>
</form>
);
}Three details matter here.
setErrortakes the field name, an error object, and an optional third argument.shouldFocus: truemoves focus to that input, which helps keyboard users.- The
typestring is yours to choose."server"lets you tell server errors apart from Zod errors when you readerrors.email.type. - The field name is typed against
SignUpValues, so a misspelled name fails at compile time.
Mapping many server errors at once
Servers often validate several fields and return them together. Suppose your API answers 422 with a body like this:
{ "fieldErrors": { "email": ["Domain is not allowed"], "password": ["Too common"] } }A small helper copies each entry onto the matching field. It shows the first message per field.
import type { UseFormSetError } from "react-hook-form";
type SignUpValues = { email: string; password: string };
type ServerFieldErrors = Partial<Record<keyof SignUpValues, string[]>>;
export function applyServerErrors(
fieldErrors: ServerFieldErrors,
setError: UseFormSetError<SignUpValues>
) {
const entries = Object.entries(fieldErrors) as [keyof SignUpValues, string[]][];
for (const [name, messages] of entries) {
if (messages.length > 0) {
setError(name, { type: "server", message: messages[0] });
}
}
}Call it in the 422 branch with applyServerErrors((await response.json()).fieldErrors, setError). Treat the response body as untrusted. A field name the form does not have would create an error that no input displays. In production code, parse the body with a Zod schema before you use it.
Errors that belong to the whole form
Some failures belong to no field: a 500, a dropped connection, or "too many attempts". Use the root key for these. setError("root.serverError", ...) stores the error at errors.root.serverError. The second segment is a name you pick, so you can keep separate entries such as root.network and root.rateLimit.
Avoid attaching a general failure to an arbitrary field. The message would appear beside an input that did nothing wrong.
How long a server error lasts
The lifetime of an error depends on how it was set.
| Error | Set by | Cleared when |
|---|---|---|
| Schema error on a field | `zodResolver` | The next validation run replaces it |
| Server error on a field | `setError("email", ...)` | The next submit, because the resolver result replaces `errors`. It is also cleared if you call `clearErrors("email")` |
| Root error | `setError("root.x", ...)` | The start of the next submit, or `clearErrors("root.x")` |
With a resolver in place, a server error on a field does not survive the next submit. This is usually what you want, because the user has probably edited the field. If the user resubmits the same bad email, the server rejects it again and the error returns.
If you want the error to disappear as soon as the user edits the field, call clearErrors("email") from an onChange handler. You can pass one to register("email", { onChange: () => clearErrors("email") }).
Common failure modes
- Throwing inside
onSubmit.handleSubmitdoes not catch exceptions from your function. A rejectedfetchbecomes an unhandled promise rejection and the user sees nothing. Wrap the request intry/catchas shown above. - Treating
fetchas if it rejects on HTTP errors. It only rejects on network failure. A409or500resolves normally, so checkresponse.statusorresponse.ok. - Double submission.
disabled={isSubmitting}blocks repeat clicks, but pressing Enter in an input can still submit in some setups. If the operation is not idempotent, have the server reject duplicates as well. - Setting errors after unmount. If the component unmounts while the request is in flight, a later
setErrorhas nothing to update. For long requests, pass anAbortControllersignal tofetchand abort it on cleanup. - Relying on the client alone. The schema runs in the browser, so a user can bypass it. The server must validate again. A later chapter shows how to share one schema between both sides.
Exercise
A user submits the sign-up form. The schema passes, but the server replies with status 409 for the email. Which call shows the message under the email input and moves focus there? Then say what happens to that error if the user clicks submit again without changing anything.
Show answer
Call setError("email", { type: "server", message: "This email is already registered" }, { shouldFocus: true }) inside onSubmit and return. The message appears wherever errors.email.message is rendered. On the next submit, handleSubmit runs the resolver again. The resolver result replaces the errors object, so the server error is cleared. The schema still passes, onSubmit sends the request again, the server answers 409 again, and setError shows the error again.
Exercise
Your onSubmit contains await fetch("/api/sign-up", ...) with no try/catch, and the user goes offline. Which error is shown, and how do you fix it?
Show answer
No form error is shown. fetch rejects, the exception escapes onSubmit, and the user sees nothing. Wrap the request in try/catch and, in the catch block, call setError("root.serverError", { type: "network", message: "Could not reach the server. Check your connection." }). Render errors.root?.serverError?.message in the form.