useSSEStream is a hook for managing real-time data streaming via Server-Sent Events (SSE). It provides auto-reconnection, type-safe event handlers, and connection state tracking.
Core Features
Real-time Streaming
Server to clientUnidirectional real-time data
Auto-reconnection
Automatic retry on failureConfigurable count/interval
Type Safety
Per-event type definitionGeneric-based
Connection State
isConnected, error trackingUI feedback ready
What is SSE?
Server-Sent Events is a technology for unidirectional real-time data transmission from server to client.WebSocket vs SSE
When to use SSE
- Server-to-client only data push
- AI response streaming (ChatGPT style)
- Real-time log monitoring
- File upload/processing progress
- Server event notifications
Basic Usage
Import
useSSEStream is defined in sonamu.shared.ts, which is generated during project scaffolding. services.generated.ts auto-generates wrapper functions for each @stream API, using useSSEStream internally.Type Definition
Basic Usage
API Reference
useSSEStream
Parameters
url
The SSE endpoint URL.params
Object to be sent as URL query parameters.handlers
Handler functions for each event type.end: When the server explicitly signals stream terminationmessage: Default message when no event type is specified
options
Return Value (SSEStreamState)
Practical Examples
AI Response Streaming
File Upload Progress
Real-time Log Monitoring
Backend Implementation
SSE endpoints are created using the@stream decorator and ctx.createSSE().
Basic SSE API
publish Format
For detailed SSE endpoint implementation, see Creating SSE Endpoints.
Advanced Features
Conditional Connection
Dynamic Parameters
Manual Reconnection
Multiple Streams
Cautions
1. EventSource Limit
- HTTP/1.1 limits to 6 concurrent connections per domain
- Avoid opening too many SSE connections simultaneously
2. Memory Management
Donβt accumulate streaming data indefinitely.3. Error Handling
4. Component Unmount
Connections are automatically closed when the component unmounts.Troubleshooting
SSE Not Connecting
Cause: CORS configuration or endpoint error Solution:Reconnection Keeps Failing
Cause: Backend server is down or network issue Solution: Adjustretry and retryInterval, or display an error UI.
Data Not Parsing
Cause: Server sending non-JSON format Solution: Usesse.publish('eventName', jsonObject) format on the backend.
Related Documentation
- Creating SSE Endpoints - Backend implementation
- Using Services - API calls