This documentation is for a legacy version of Next.js and Supabase (Lite). For the latest version, please visit the Next.js and Supabase V2 documentation

Validating the Next.js API inputs with Zod and Typescript

Zod is a library for validating data with awesome support for Typescript. Learn how to use it within your Makerkit project.

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 or a Server Action, 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 a Server Action that validates the body of the function, which we expect to be equal to the Body interface.

'use server';
export async function serverAction(
data: z.infer<
ReturnType<typeof getBodySchema>
>
) {
// we can safely use data with the interface Body
const bodyResult = await getBodySchema().parseAsync(data);
const { displayName, email } = bodyResult;
return sendInvite({ displayName, email });
}
function getBodySchema() {
return z.object({
displayName: z.string(),
email: z.string().email(),
});
}

You can also use safeParse if you prefer not to throw an error when the validation fails:

'use server';
export async function serverAction(
data: z.infer<
ReturnType<typeof getBodySchema>
>
) {
// we can safely use data with the interface Body
const bodyResult = await getBodySchema().safeParseAsync(data);
if (bodyResult.success === false) {
return bodyResult.error;
}
const { displayName, email } = bodyResult.data;
return sendInvite({ displayName, email });
}
function getBodySchema() {
return z.object({
displayName: z.string(),
email: z.string().email(),
});
}

The same applies to Route Handlers:

import { NextRequest } from "next/server";
export async function POST(
request: NextRequest
) {
const body = await request.json();
const bodyResult = await getBodySchema().safeParseAsync(body);
if (bodyResult.success === false) {
return bodyResult.error;
}
const { displayName, email } = bodyResult.data;
return sendInvite({ displayName, email });
}
function getBodySchema() {
return z.object({
displayName: z.string(),
email: z.string().email(),
});
}

To learn more about validating data with Zod, we suggest you check out the Zod official documentation on GitHub.