Skip to main content

Overview

Protocol: HTTP with text/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
When NOT to Use SSE:
  • ❌ Client needs to send messages frequently (use WebSocket instead)
  • ❌ Binary data required (SSE is text-only)

How SSE Works

Key Characteristics:
  • 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

Response (streamed):

JavaScript Example

Browser (Fetch API)

Node.js (EventSource)

Python Example


SSE Format

Message Format

Rules:
  • 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

Choose SSE when:
  • You only need server → client communication
  • Building on existing HTTP infrastructure
  • Implementing AI chat streaming
  • Simple reconnection handling needed
Choose WebSocket when:
  • 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