Skip to main content

Overview

The .pipe() method allows you to chain two schemas together, where the output of the first schema becomes the input of the second. This is useful for multi-stage validation and transformation pipelines.

Signature

ZodType
required
The schema to pipe into. Its input type must match the output type of the source schema.
Returns: ZodPipe<A, B> where A is the source schema and B is the target schema

Basic Usage

String to Number Pipeline

The most common use case is converting and validating data in stages:

Async Transformations

Pipes work with async transformations:

Advanced Patterns

Multi-Stage Validation

Use pipes to validate at different stages of transformation:

Conditional Pipelines

Combine pipes with refinements for conditional logic:

Refinement Before Transformation

Validate before transforming to prevent invalid transformations:

Error Handling

Non-Fatal Errors

By default, refinement errors are non-fatal and allow subsequent checks:

Fatal Errors

Use abort: true to stop validation on error:

Bidirectional Validation

Encoding and Decoding

Pipes support both forward (decode) and reverse (encode) operations:

Transform Encoding Errors

Unidirectional transforms cannot be encoded:

Type Safety

Pipes maintain type safety throughout the chain:

Type Mismatch Errors

TypeScript will catch type mismatches between piped schemas:

Comparison with Transform

Common Patterns

String Preprocessing

Clean and validate string input:

JSON Parsing

Parse and validate JSON strings:

Date Normalization

Form Value Processing

Best Practices

Validate early

Place validation as early as possible in the pipeline to catch errors before expensive transformations.

Use meaningful error messages

Add custom error messages at each stage to help identify where validation failed.

Consider performance

Each pipe stage adds overhead. For simple cases, a single transform might be more efficient.

Type safety first

Let TypeScript guide you - if types don’t match, add explicit transforms to bridge the gap.

Error Examples

Type Mismatch

Validation Failure

See Also