Import
Basic Streaming
Thestream helper creates a streaming response for sending data progressively.
Simple Stream
Writing Different Data Types
Error Handling
Handle errors during streaming:Abort Handling
Detect when the client disconnects:Pipe from ReadableStream
Pipe data from another stream:Server-Sent Events (SSE)
ThestreamSSE helper provides real-time server-to-client communication using Server-Sent Events.
Basic SSE
SSE Message Format
string | Promise<string>
required
The message data. Can contain newlines.
string
Custom event type (default is “message”)
string
Event ID for the Last-Event-ID header
number
Reconnection time in milliseconds
Client-Side SSE
Connect to SSE endpoint from the browser:SSE with Error Handling
SSE Headers
SSE responses automatically set appropriate headers:Text Streaming
ThestreamText helper is optimized for streaming text responses.
Basic Text Stream
Streaming LLM Responses
Text Stream Headers
Text streams automatically set:StreamingAPI Methods
All streaming helpers provide aStreamingApi instance with these methods:
write()
Write data to the stream:writeln()
Write data with a newline:sleep()
Pause for a specified duration:pipe()
Pipe from a ReadableStream:onAbort()
Register an abort handler:close()
Manually close the stream:Use Cases
Real-time Updates
Use SSE for live notifications, dashboards, and real-time data feeds
AI Streaming
Stream LLM responses for better user experience with text streaming
File Downloads
Stream large files without loading them entirely into memory
Log Streaming
Stream server logs or process output in real-time
Best Practices
Always handle client disconnections with
onAbort() to clean up resources and stop processing.Add appropriate error handlers to prevent unhandled promise rejections and ensure graceful error recovery.
Browser Compatibility
SSE is supported in all modern browsers:- Chrome/Edge: Full support
- Firefox: Full support
- Safari: Full support
- Opera: Full support
SSE does not work in Internet Explorer. Consider using WebSockets for broader compatibility.