Overview
Express Zod API supports real-time data streaming using Server-Sent Events (SSE). This lightweight alternative to WebSockets enables your server to push updates to clients over a standard HTTP connection.For bidirectional communication, consider Zod Sockets, a companion library for WebSocket support.
What are Server-Sent Events?
Server-Sent Events provide:- Unidirectional server-to-client communication
- Automatic reconnection
- Event-based message delivery
- Built-in browser support via
EventSource - Lower overhead than WebSockets for one-way streaming
Creating an Event Stream
UseEventStreamFactory to create streaming endpoints:
Multiple Event Types
Define multiple event types in a single stream:Client-Side Consumption
Consume SSE streams using the nativeEventSource API:
React Example
Connection Lifecycle
Manage the connection lifecycle with provided helpers:isClosed()
Check if the client has disconnected:
signal (AbortSignal)
Use the abort signal for cleanup and cancellation:
With Middleware
Add authentication and other middlewares to event streams:Real-World Examples
Live Metrics Dashboard
Progress Tracking
Log Streaming
Error Handling
Handle errors in event streams:Routing
Add SSE endpoints to your routing:Generated Client Support
TheIntegration generator creates a Subscription class for type-safe SSE consumption:
Best Practices
Check connection status
Check connection status
Always check
isClosed() before emitting events to avoid errors when the client has disconnected.Use abort signals
Use abort signals
Register cleanup logic with the
signal to release resources when clients disconnect.Validate event data
Validate event data
Define strict Zod schemas for your events—the framework validates all emitted data automatically.
Handle backpressure
Handle backpressure
Don’t emit events faster than clients can consume them. Use appropriate intervals or queue mechanisms.
Set reasonable timeouts
Set reasonable timeouts
Consider implementing heartbeat/ping events to detect stale connections.
Test disconnect scenarios
Test disconnect scenarios
Test how your handlers behave when clients disconnect unexpectedly.
Limitations
- SSE is one-way (server to client only)
- Limited to text-based data (JSON strings)
- Some proxies and firewalls may interfere
- Maximum of 6 concurrent connections per domain in browsers
- No binary data support (use base64 encoding if needed)
Comparison with WebSockets
| Feature | SSE | WebSockets |
|---|---|---|
| Direction | Server → Client | Bidirectional |
| Protocol | HTTP | WS/WSS |
| Reconnection | Automatic | Manual |
| Browser Support | Good | Excellent |
| Overhead | Lower | Higher |
| Binary Data | No | Yes |
| Use Case | Live feeds, notifications | Chat, gaming, collaboration |
Next Steps
- Learn about Authentication for secure streams
- Explore Express Middleware for rate limiting
- See Zod Sockets for WebSocket support