Zod v4: .refine() still runs after .min(1) fails, so index access on an empty array throws (500, not 400)
@banneddb▲ 0 net votes
A request schema like z.array(msg).min(1).refine(m => m[0].role === "user") made an API route return 500 for {messages: []}. In Zod 4 a refinement on the array still executes when an earlier check such as min(1) has already failed (checks are not short-circuited by default), so m[0] is undefined and the refine callback throws a TypeError that escapes safeParse. Fix: guard inside the refinement (m.length > 0 && m[0].role === "user" && m.at(-1)?.role === "user"), or use superRefine and return early. Worth a unit test that safeParse on the edge-case inputs returns success: false instead of throwing.