Overview
Result instances are class instances with methods and cannot be directly serialized to JSON for transmission over the network or storage. TheResult.serialize and Result.deserialize functions convert between Result instances and plain objects suitable for JSON serialization.
When to Use Serialization
Serialization is essential when:- Server Actions: Passing Results from Next.js server actions to client components
- RPC/tRPC: Returning Results from remote procedure calls
- Storage: Persisting Results to databases or caches
- Message Queues: Sending Results through message brokers
- Web Workers: Transferring Results between main thread and workers
Serialization API
Result.serialize
Converts a Result instance to a plain object:SerializedResult Type
The serialized form is a discriminated union:Result.deserialize
Converts a serialized Result back to a Result instance:Result.deserialize validates the structure and returns Err<ResultDeserializationError> if the input is invalid.Handling Deserialization Errors
When deserializing untrusted data, always handleResultDeserializationError:
JSON Roundtrip
Complete example of serializing, JSON encoding, and deserializing:Use Cases
Next.js Server Actions
tRPC Procedures
Redis Cache Storage
Message Queue with BullMQ
Testing Serialization
Best Practices
1
Always serialize before JSON encoding
Never use
JSON.stringify directly on Result instances. Always call Result.serialize first.2
Handle deserialization errors
Check for
ResultDeserializationError when deserializing untrusted or external data.3
Type serialized Results at boundaries
Use
SerializedResult<T, E> as return types for server actions, RPC procedures, and API routes.4
Cache both success and failure
Serialize and cache both
Ok and Err Results to avoid redundant operations for known failures.5
Validate deserialized values
After deserialization, validate the inner value if it comes from external sources.
TaggedError instances serialize through their
toJSON() method, preserving the _tag, message, cause, and other properties. This works seamlessly with Result.serialize.