When it comes to consuming streaming responses in the browser, especially from Server-Sent Events (SSE), two main approaches emerge:
- Using the native
EventSourceAPI - Using
fetchwith an async generator to manually parse the stream
Letβs break down the differences and when to use each.
π Quick Comparison
| Feature | EventSource | fetch + Async Generator |
|---|---|---|
| HTTP Method | GET only | β Supports POST, PUT |
| Custom Headers | β Limited | β Full control |
| Streaming Support | β Yes | β Yes |
| LLM API Friendly | β No | β Yes |
| Reconnection | β Auto | β Manual |
| Binary Support | β No | β Yes |
| Browser Support | β | β (modern browsers) |
| Node.js Use | β | β (with polyfills) |
π§ When to Use What?
β
Use EventSource if:
- Your server supports only GET-based SSE
- You need auto-reconnect
- Youβre building a simple real-time dashboard
const es = new EventSource('/events'); es.onmessage = (e) => console.log(e.data); β
Use fetch + async generator if:
- You're working with LLM APIs that require POST or auth headers
- You want fine-grained control over stream parsing
async function* streamSSE(response) { const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop(); // Incomplete line for (const line of lines) { if (line.startsWith('data: ')) yield line.slice(6); } } } π Summary
| Use Case | Best Approach |
|---|---|
| Authenticated LLM streaming | fetch + async generator |
| Lightweight real-time updates | EventSource |
Top comments (0)