useSSEStream is a hook for implementing real-time streaming using Server-Sent Events (SSE). It features auto-reconnection, type-safe event handlers, and is ideal for AI chat streaming and file upload progress.
Core Features
Real-time Streaming
SSE basedUnidirectional server push
Auto-reconnection
Connection drop handlingConfigurable retry
Type Safety
Typed event handlersAuto-completion support
Auto-generated
Generated in servicesReady to use immediately
What is SSE?
Server-Sent Events (SSE) is a standard for servers to push data to clients in real-time over HTTP.SSE vs WebSocket
| Feature | SSE | WebSocket |
|---|---|---|
| Direction | Unidirectional (Server β Client) | Bidirectional |
| Protocol | HTTP | ws:// |
| Connection | Auto-reconnects | Manual handling needed |
| Use case | News feeds, progress, logs | Chat, games, collaboration |
When to use SSE
- AI chat streaming
- File upload progress
- Real-time log monitoring
- Stock price updates
- Server notifications
Basic Usage
Type Definition
First, define the event types the server will send.Hook Usage
- endpoint: SSE API path
- params: Parameters to send to server
- eventHandlers: Handler for each event type
- options: Connection options (enabled, retry, retryInterval)
Backend Implementation
Generator Function Pattern
Use generator functions in the backend to send SSE events.- Use
async function*(generator function) yieldobject witheventanddataevent: Event type (must match frontend type definition)data: Event payload
Error Handling
Real-world Examples
AI Chat Streaming
File Upload Progress
Real-time Log Monitoring
Options
enabled
Control connection activation/deactivation.- Wait for user input before connecting
- Enable based on authentication state
- Conditional connection based on page state
retry
Number of reconnection attempts on connection drop.3
retryInterval
Interval between reconnection attempts (milliseconds).3000 (3 seconds)
Return Values
status
Current connection state.error
Error message (available when status is βerrorβ).reconnect
Function to manually reconnect.Auto-reconnection
useSSEStream automatically reconnects on connection drops.
Reconnection Flow
- Connection drops β
statusbecomes βerrorβ - Wait
retryInterval - Retry connection
- Repeat up to
retrytimes - On final failure β Stay in βerrorβ state
Reconnection State Display
Cautions
1. Event Handler Stability
Event handlers are managed withuseRef internally, so frequent recreation doesnβt cause reconnections.
2. Parameter Changes
Whenparams changes, connection is dropped and reconnected.
3. enabled Changes
Whenenabled changes from false β true, connects; from true β false, disconnects.
Troubleshooting
Connection Fails
Causes:- Backend SSE endpoint not implemented
- Incorrect endpoint path
- CORS issues
- Check backend generator function implementation
- Verify endpoint path
- Configure CORS headers (backend must allow SSE)
No Events Received Despite Connection
Cause: Event type mismatch Solution:Too Many Reconnections
Cause: Backend keeps rejecting connections Solution:- Check backend error logs
- Reduce
retrycount - Increase
retryInterval
Related Documentation
- Using Services - API call methods
- TanStack Query Integration - Cache management
- AI Agents - AI SDK integration