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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/payload-validation hyper-fetch-react-payload-validation && cd hyper-fetch-react-payload-validation && npm install && npm run devsetRequestMapperruns the schema right before the request is sent.- A throw ends the request: the
ZodErrorcomes back aserror, and the fetch never starts. - The parsed payload is sent, so zod transforms such as
trim()apply to the body. - The
errorgeneric types theZodError, andinstanceofnarrows it for field errors.
How it works
-
api.tsdefinesNewUserSchemaand derives the payload type from it withz.infer, so the rules and the type can't drift apart. -
addUservalidates 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))); -
When
parsethrows, the adapter catches it and resolves the request with the error.send()anduseSubmitdo not throw, and nothing reaches the network. -
error: z.ZodError<NewUser>in the request generics adds the zod error to the global error type.App.tsxcheckserror instanceof z.ZodErrorand turns it intofieldErrorswithz.flattenError(). Other failures, such as a network error, show as one message. -
The form has no checks of its own. Any caller of
addUser, a script or another form, gets the same validation. -
useSentCountlistens toclient.requestManager.events.onRequestStart, which fires only when the adapter really starts a request. Invalid submits never move 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.
Related
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.
