Overview
While Express Zod API is optimized for JSON APIs, it fully supports serving non-JSON responses such as images, PDFs, or other binary files. This is accomplished through customResultHandler configurations.
Setting MIME Types
To configure a non-JSON response, specify the MIME type in yourResultHandler:
Response Schemas
For non-JSON responses, use appropriate schemas in your documentation:z.string()- For text contentz.base64()- For base64-encoded dataez.buffer()- For binary data (recommended for files)
File Streaming
Streaming files is more efficient than loading them entirely into memory:Complete Streaming Example
File Sending (In-Memory)
For smaller files, you can send them directly without streaming:HEAD Request Support
Support HEAD requests to provide content length without sending the body:PDF Downloads
CSV Export
Multiple MIME Types
Support content negotiation with multiple MIME types:Image Responses with Compression
When serving images with compression enabled:Best Practices
Use Streaming for Large Files
Use Streaming for Large Files
Always use file streaming for large files to avoid loading the entire file into memory. This improves performance and reduces memory usage.
Set Appropriate MIME Types
Set Appropriate MIME Types
Always set the correct MIME type for your responses. This helps clients handle the content appropriately.
Handle Errors Gracefully
Handle Errors Gracefully
Always check if the file exists and handle errors appropriately before attempting to send or stream it.
Use Appropriate Schemas
Use Appropriate Schemas
Use
ez.buffer() for binary data, z.string() for text, and z.base64() for base64-encoded content in your output schemas.Related Topics
- Response Customization - Creating custom result handlers
- File Uploads - Handling file uploads
- Configuration - Enabling compression