Validating payloads is necessary to ensure your API endpoints receive the expected data. To validate the API, we use Zod.
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 payload 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.
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`;
function inviteMemberHandler(
req: NextApiRequest,
res: NextApiResponse,
) {
try {
// we can safely use data with the interface Body
const schema = getBodySchema();
const { displayName, email } = schema.parse(req.body);
return sendInvite({ displayName, email });
} catch(e) {
return throwBadRequestException(res);
}
}
export default function apiHandler() {
const handler = withPipe(
withMethodsGuard(['POST']),
withAuthedUser,
inviteMemberHandler,
);
// manage exceptions
return withExceptionFilter(req, res)(handler);
}
I encourage you to never skip the validation step when writing your API endpoints.