Function validateBody

  • Validate the body in a request with a Zod schema. Throws an exception if the body does not match the schema. You can use ExceptionWrapper to automatically catch the exception and send it to the client.

    Type Parameters

    • T extends ZodType<any, ZodTypeDef, any>

    Parameters

    • request: Pick<NextRequest, "json">

      The next/server#NextRequest object to validate the body for

    • schema: T

      The Zod schema to validate the body against

    Returns Promise<z.infer<T>>

    The validated body

    import { validateBody } from 'next-api-utils';
    import { z } from 'zod';

    export const POST = (request) => {
    const body = validateBody(request, z.object({ foo: z.string() }));
    };

    InvalidBodyException Thrown if the body failed validation