Skip to main content

Payload validation

A sign-up form whose request validates its own payload with zod. Submit it half filled: the fields show their errors and the counter of sent requests stays at zero. Fix the fields and the user is created.

intermediatevalidationformsuseSubmiterrors
import { useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useEffect, useState } from "react";
import { z } from "zod";

import { addUser, client, type NewUser } from "./api";

type Field = keyof NewUser;

/** Counts the requests that really started in the adapter, so you can see invalid ones never do. */
const useSentCount = () => {
const [sent, setSent] = useState(0);
useEffect(() => client.requestManager.events.onRequestStart(() => setSent((count) => count + 1)), []);
return sent;
};

export const App = () => {
const { submit, submitting, data, error } = useSubmit(addUser);
const [blocked, setBlocked] = useState(0);
const sent = useSentCount();

// The error type is the request `error` generic plus the global error, so it is narrowed before use.
const fieldErrors: Partial<Record<Field, string[]>> =
error instanceof z.ZodError ? z.flattenError(error).fieldErrors : {};
const otherError = error && !(error instanceof z.ZodError) ? error.message : null;

const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
// No checks here. The request validates its own payload, for this form and any other caller.
const response = await submit({
payload: {
firstName: String(form.get("firstName")),
email: String(form.get("email")),
age: form.get("age") === "" ? Number.NaN : Number(form.get("age")),
},
});
if (response.error instanceof z.ZodError) setBlocked((count) => count + 1);
};

const input = (name: Field, label: string, type = "text") => (
<label>
{label}
<input name={name} type={type} aria-invalid={fieldErrors[name] ? true : undefined} />
{fieldErrors[name] && <small>{fieldErrors[name][0]}</small>}
</label>
);

return (
<main className="container">
<hgroup>
<h1>Payload validation</h1>
<p>
The request checks its payload with zod before sending. Submit an invalid form: nothing leaves the browser.
</p>
</hgroup>
<div className="grid-2">
<article>
<form onSubmit={handleSubmit} noValidate>
{input("firstName", "First name")}
{input("email", "Email", "email")}
{input("age", "Age", "number")}
<button type="submit" aria-busy={submitting} disabled={submitting}>
Create user
</button>
</form>
{otherError && <p className="error">Request failed: {otherError}</p>}
{data && !error && (
<p>
<ins>Created</ins> user #{data.id}: {data.firstName}, {data.email}
</p>
)}
</article>
<article>
<h6>Requests</h6>
<p>
Stopped by validation: <strong>{blocked}</strong>
</p>
<p>
Sent to the server: <strong>{sent}</strong>
</p>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/payload-validation hyper-fetch-react-payload-validation && cd hyper-fetch-react-payload-validation && npm install && npm run dev
What it shows
  1. setRequestMapper runs the schema right before the request is sent.
  2. A throw ends the request: the ZodError comes back as error, and the fetch never starts.
  3. The parsed payload is sent, so zod transforms such as trim() apply to the body.
  4. The error generic types the ZodError, and instanceof narrows it for field errors.

How it works​

  1. api.ts defines NewUserSchema and derives the payload type from it with z.infer, so the rules and the type can't drift apart.

  2. addUser validates in a request mapper. The adapter runs it after the interceptors and before the fetch. It returns the request with the parsed payload:

    .setRequestMapper((request) => request.setPayload(NewUserSchema.parse(request.payload)));
  3. When parse throws, the adapter catches it and resolves the request with the error. send() and useSubmit do not throw, and nothing reaches the network.

  4. error: z.ZodError<NewUser> in the request generics adds the zod error to the global error type. App.tsx checks error instanceof z.ZodError and turns it into fieldErrors with z.flattenError(). Other failures, such as a network error, show as one message.

  5. The form has no checks of its own. Any caller of addUser, a script or another form, gets the same validation.

  6. useSentCount listens to client.requestManager.events.onRequestStart, which fires only when the adapter really starts a request. Invalid submits never move it.

When to use it
  • Forms whose payload must follow rules that the server checks again.
  • Requests sent from many places, where each caller would otherwise repeat the checks.
  • Expensive or rate-limited endpoints, where an invalid call costs money or quota.

Summary

A request mapper that calls schema.parse() keeps invalid payloads from being sent. The ZodError comes back as a typed error, ready to show next to each field.