Zod validation: I just need opinions on this, I'm a solo newbie...

I am adding Zod validations that I want to perform both client and server side. My approach was using server actions to submit forms, but this does not add validation to the actual api endpoints and forces me to use server actions instead of authClient .
The validation plugin is inactive so I thought it is better not to mess with it.
The solution to ditch validation inside server actions I am evaluating is modifying the api/auth/[...all] file

import { auth } from "@/lib/auth/auth"
import { toNextJsHandler } from "better-auth/next-js"
import { z } from "zod"

const signUpSchema = z.object({
  email: z.string().email("Invalid email format"),
  password: z.string().min(8, "Password must be at least 8 characters long"),
  name: z.string().min(1, "Name is required"),
  additionalField: z.string().min(1)
})

// Generate Next.js route handlers from Better Auth
const authHandlers = toNextJsHandler(auth)
export const { GET } = authHandlers

// Override POST to inject Zod validation
export async function POST(request: Request) {
  try {
    const clonedRequest = request.clone()
    const body = await request.json()
    const parsed = signUpSchema.safeParse(body)

    if (!parsed.success) {
      // Use new .format() (flatten is deprecated)
      return Response.json(
        {
          success: false,
          errors: parsed.error.format(), 
        },
        { status: 400 },
      )
    }

    return authHandlers.POST(clonedRequest)
  } catch (err) {
    return Response.json(
      { success: false, message: "Invalid request body" },
      { status: 400 },
    )
  }
}


Does this in fact validate all auth and authClient requests? Obviously I also need to add something like

if (request.url.endsWith("/auth/sign-up")) {
  // use the correct schema to validate
}



Does this seems right to you? Do you think there is a better approach to this?

Thank you for your attention!
Was this page helpful?