TanStackT
TanStack•2mo ago•
10 replies
progressive-amaranth

Preventing raw Zod error exposure in createServerFn validation

Hi everyone! đź‘‹

I'm using createServerFn with .inputValidator() using a Zod schema. When the input validation fails, the server function throws the raw Zod error array to the client.

I would like to know if there is a recommended way to intercept this validation error to return a simplified message (e.g., just "Invalid UUID") or a custom error structure, instead of exposing the full Zod error object.

Example:

import { createServerFn } from '@tanstack/react-start'
import * as z from 'zod'

export const getClientBenefits = createServerFn({ method: 'GET' })
  .inputValidator(z.uuid())
  .handler(async ({ data: clientId }) => {
    return service.getBenefits(clientId)
  })



When I call this function with an invalid UUID, I receive this raw Zod error response:
{
    "t": 25,
    "i": 0,
    "s": {
        "message": {
            "t": 1,
            "s": "[\\n  {\\n    \\\"origin\\\": \\\"string\\\",\\n    \\\"code\\\": \\\"invalid_format\\\",\\n    \\\"format\\\": \\\"uuid\\\",\\n    \\\"pattern\\\": \\\"/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/\\\",\\n    \\\"path\\\": [],\\n    \\\"message\\\": \\\"Invalid UUID\\\"\\n  }\\n]"
        }
    },
    "c": "$TSR/Error"
}


I want to be able to return something cleaner, like: { "message": "Invalid UUID" } or just throw a standard HTTP error(Bad Request).

Is there a hook or middleware configuration to handle inputValidator failures?
image.png
Was this page helpful?