zod safeparse

Zod safeParse

Use Zod safeParse to validate unknown data without throwing, narrow success and error results in TypeScript, and choose safeParseAsync when validation is asynchronous.

Open the JSON to Zod converter

Quick answer: what does Zod safeParse do?

`safeParse` validates the same schema as `parse`, but it returns a result object instead of throwing on validation failure. Use it when invalid input is expected and your code should branch into success or error handling. The official result shape is a discriminated union: success includes parsed data, failure includes a ZodError.

Basic safeParse example

Call `schema.safeParse(input)` on unknown data, then check `result.success` before reading either `result.data` or `result.error`.

import { z } from "zod";

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
});

const result = UserSchema.safeParse(payload);

if (!result.success) {
  return { ok: false, issues: result.error.issues };
}

return { ok: true, user: result.data };

safeParse return type in TypeScript

The safeParse return type is a discriminated union. Once your code checks `result.success`, TypeScript knows which branch contains parsed data and which branch contains a ZodError.

const result = UserSchema.safeParse(payload);

if (result.success) {
  result.data.email.toLowerCase();
} else {
  result.error.flatten().fieldErrors;
}

Handle safeParse errors

Use `error.flatten()` when forms or API clients need a stable field map. Use `error.issues` when logs, nested paths, or issue codes matter.

const result = CreateUserSchema.safeParse(body);

if (!result.success) {
  return Response.json(
    { error: "Invalid request body", fieldErrors: result.error.flatten().fieldErrors },
    { status: 400 },
  );
}

safeParse vs parse

Use `safeParse` for request bodies, forms, route handlers, server actions, and UI states where invalid data is a normal branch. Use `parse` when invalid data should throw and be handled by a central error layer.

  • `safeParse` returns success or error data.
  • `parse` returns typed data or throws a ZodError.
  • Both methods run the same schema validation rules.

safeParseAsync

Use `safeParseAsync` when the schema has asynchronous refinements or transforms. It keeps the same result shape as safeParse, but returns a promise.

const InviteSchema = z.object({
  email: z.string().email(),
}).refine(async (value) => {
  return await canInviteEmail(value.email);
}, "Email cannot receive invites");

const result = await InviteSchema.safeParseAsync(payload);

Where safeParse fits after generating schemas

A generated Zod schema still needs a failure strategy. After using JSON to Zod or TypeScript to Zod, place `safeParse` at the boundary that receives unknown input and keep parsed data inside the success branch.

API and form safeParse examples

Use the same branching pattern in route handlers, server actions, forms, and fetch wrappers. The important rule is that unknown data should become typed data only after the success branch.

const result = SignupSchema.safeParse(formValues);

if (!result.success) {
  return {
    ok: false,
    fieldErrors: result.error.flatten().fieldErrors,
  };
}

await createAccount(result.data);

Zod safeParse result states

StateReturn shapeUse it for
Success`{ success: true, data }`Continue with typed data after TypeScript narrows the result.
Failure`{ success: false, error }`Return field errors, API 400 responses, form messages, logs, or fallback UI.
Async success or failure`await schema.safeParseAsync(input)`Run async refinements or transforms without wrapping validation in try/catch.

Use FrameworkKit to generate the starter code, then review the output before shipping it in production.

Generate with the JSON to Zod schema generator

Zod validation resources

JSON to Zod converter

Convert sample payloads into copy-ready Zod schemas and inferred TypeScript types in the browser.

JSON to Zod schema examples

Open realistic API and product payload examples before adapting the JSON to Zod schema output.

TypeScript to Zod Converter

Convert TypeScript interfaces and type aliases into Zod schemas when the source shape already lives in code.

Zod to JSON Schema Converter

Use the canonical online converter when an existing Zod schema needs JSON Schema, AJV, or OpenAPI output.

Validate API responses with Zod

Validate API responses, request bodies, and fetch boundaries with Zod schemas in TypeScript.

Zod parse vs safeParse

Choose between parse, safeParse, parseAsync, and safeParseAsync for TypeScript validation flows.

Zod safeParse error messages

Format safeParse failures, field errors, and API validation responses in TypeScript.

Zod refine vs superRefine

Add custom validation, async checks, and field-level error paths after generating a starter schema.

Zod nativeEnum in Zod 4

Migrate z.nativeEnum patterns to z.enum, validate TypeScript enums, and avoid enum value mistakes.

Use JSON to Zod for form validation

Start from a submitted form payload, then add business rules such as email, length, and enum checks.

Zod to JSON Schema for OpenAPI

Publish Zod API schemas as OpenAPI-compatible contracts when teams need portable documentation.

Zod vs JSON Schema

Choose between TypeScript-first runtime validation and portable schema contracts.

Zod vs Yup vs Valibot

Compare TypeScript validation libraries for API boundaries, forms, server actions, and bundle tradeoffs.

FAQ

Does safeParse throw?

No. Validation failures return `{ success: false, error }`. Unexpected runtime errors outside validation can still throw like normal JavaScript.

What is the Zod safeParse return type?

It is a discriminated union with a success branch containing parsed data and a failure branch containing a ZodError.

When should I use safeParse in Zod?

Use safeParse for user input, form submissions, API request bodies, server actions, route handlers, and other recoverable validation flows.

When should I use safeParseAsync?

Use safeParseAsync when your schema contains async refinements, transforms, or checks that return promises.

Is safeParse better than parse?

Neither is universally better. safeParse is better for controlled error responses; parse is better when invalid data should throw and be handled centrally.

Related tools