Skip to content
Go back

EventSource vs Async Generator - What to Use for LLM Streaming?

Published:  at  08:30 AM

When it comes to consuming streaming responses in the browser, especially from Server-Sent Events (SSE), two main approaches emerge:

Let’s break down the differences and when to use each.


πŸ” Quick Comparison

FeatureEventSourcefetch + Async Generator
HTTP MethodGET 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:

const es = new EventSource('/events');
es.onmessage = (e) => console.log(e.data);

βœ… Use fetch + async generator if:

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 CaseBest Approach
Authenticated LLM streamingfetch + async generator
Lightweight real-time updatesEventSource

Suggest Changes

Previous Post
How Async Generators Work with SSE in JavaScript
Next Post
How to get a free AWS SSL certificate for your service.