Matt Pocock: createHandler with zod

This is the original Tweet that Matt Pocock’s.

In every codebase where I need an API, I always end up writing some version of this function. It lets you automatically handle 400 validation using Zod, and automatically infers the types based on the schema passed in.

Image
1.2K
Reply

He wrapped next api route handler with Zod.

I think that’s a really good idea!

First, the above function is just a typescript declaration.

It’s not implemented function.

With createHandler , we can implement POST or PATCH method with req.body validation.

Declare createHandler

declare function createHandler<T extends z.ZodType>(
	schema: T,
	handler: (
		req: Omit<NextApiRequest, keyof z.output<T>> &
			z.output<T>,
		res: NextApiResponse
	) => void | Promise<void>
)

In the above code, we can see Omit.

That Omit is omitting schema’s key property in NextApiRequest.

Declare the schema

const schema = z.object({
	body: z.object({
		id: z.string()
	})
})

So above schema’s key is body , and it will be omitted in next handler’s NextApiRequest which will be req.

Declare the handler

export const handler = createHandler(schema, (req) => {
	req.body.id;
})

← Go home