Zod is a Typescript library that helps us secure our API endpoints by validating the payloads sent from the client and also facilitating the typing of the payloads with Typescript.
Using Zod is the first line of defense to validate the data sent against our API: as a result, it's something we recommend you keep doing. It ensures we write safe, resilient, and valid code.
All Makerkit's API routes are secured with Zod: in this document, we want to explain the conventions used by the SaaS Boilerplate, and how to use it for your API endpoints.
When we write an API endpoint, we first define the schema of the payload:
function getBodySchema() {
return z.object({
displayName: z.string(),
email: z.string().email(),
});
}
This function represents the schema, which will validate the following interface:
interface Body {
displayName: string;
email: Email;
}
Now, let's write the body of the API handler that validates the body of the
function, which we expect to be equal to the Body
interface.
import { throwBadRequestException } from `~/core/http-exceptions`;
export async function POST(request: Request) {
try {
// we can safely use data with the interface Body
const body = await request.json();
const bodyResult = await getBodySchema().parseAsync(body);
const { displayName, email } = bodyResult.data;
return sendInvite({ displayName, email });
} catch(e) {
return throwBadRequestException();
}
}
You can also use safeParse
if you prefer not to throw an error when the
validation fails:
export async function POST(request: Request) {
const body = await request.json();
const result = await getBodySchema().parseAsync(body);
// we use result.success as a type guard
// when false, we throw an exception
if (!result.success) {
return throwBadRequestException();
}
// TS correctly infers result.data now
return sendInvite(result.data);
}
To learn more about validating data with Zod, we suggest you check out the Zod official documentation on GitHub.