Overview
Protocol: HTTP withtext/event-stream content type
Communication: Unidirectional (Server → Client)
Endpoint: https://api.petstoreapi.com/v1/chat/completions
When to Use SSE:
- ✅ Real-time AI chat streaming responses
- ✅ Live progress updates
- ✅ Server push notifications
- ✅ One-way communication is sufficient
- ❌ Client needs to send messages frequently (use WebSocket instead)
- ❌ Binary data required (SSE is text-only)
How SSE Works
- Built on standard HTTP (no new infrastructure needed)
- Automatic reconnection handling
- Text-based, easy to debug
- One-way server → client communication
Quick Start
cURL Example
JavaScript Example
Browser (Fetch API)
Node.js (EventSource)
Python Example
SSE Format
Message Format
- Each message starts with
data: - Messages are separated by blank lines
- End of stream is marked with
data: [DONE]
Event Fields
data: The actual data (required)event: Event type (optional, defaults to ‘message’)id: Event ID for reconnection (optional)retry: Reconnection delay in milliseconds (optional)
Advanced Usage
Custom Event Types
Reconnection Handling
EventSource automatically reconnects on connection loss:Abort Controller
Comparison with Alternatives
| Feature | SSE | WebSocket | Polling |
|---|---|---|---|
| Direction | Server → Client | Bidirectional | Client → Server |
| Overhead | Low | Very Low | High |
| Reconnection | Automatic | Manual | N/A |
| Browser Support | Excellent | Excellent | Universal |
| Text Support | ✅ | ✅ | ✅ |
| Binary Support | ❌ | ✅ | ❌ |
| Infrastructure | HTTP | WebSocket Server | HTTP |
- You only need server → client communication
- Building on existing HTTP infrastructure
- Implementing AI chat streaming
- Simple reconnection handling needed
- You need bidirectional communication
- Low latency is critical
- Binary data transmission needed
Error Handling
Best Practices
1. Buffer Display
Don’t update the UI for every character. Buffer small amounts:2. Handle Stream Errors
3. Cleanup Resources
Troubleshooting
No Events Received
- Check network connection
- Verify authentication token
- Confirm server supports streaming
- Check browser console for errors
Connection Drops
- SSE auto-reconnects by default
- Implement exponential backoff if needed:
High Memory Usage
- Process and discard events promptly
- Don’t accumulate entire stream in memory
- Use streaming parsers for large payloads
Interactive Documentation
- API Specification: OpenAPI 3.2
- Live Demo: Swagger UI
- Protocol Overview: All Protocols
Related Resources
- WebSocket Guide - For bidirectional communication
- Quick Start Guide
- Authentication Guide