Overview

parsePayload is a helper function to parse the payload with Zod schema and the request body. It's also throw an error if the payload is invalid. This will help you to handle the payload in a type-safe way.

How to Use

You need to use it in the route handler. Here's an example of how to use it:

route.ts

import { parsePayload } from '@/lib/server/payload' import { NextRequest } from 'next/server' import { z } from 'zod' export const POST = async (req: NextRequest) => { const body = parsePayload( z.object({ name: z.string(), age: z.number(), email: z.string().email(), }), await req.json() ) // Handle the error if (body instanceof Error) { return NextResponse.json({ error: body.message }, { status: 400 }) } // Use the type-safe payload console.log(body.name, body.age, body.email) }

References