Streaming LLM Responses to the Browser with Server-Sent Events

Stream tokens from an LLM API to users in real time: provider streaming, SSE endpoints in Node.js and Python, frontend rendering, cancellation and pitfalls.

Published December 1, 2026

A model might take ten seconds to generate a full answer, but it starts producing tokens within a second. Streaming those tokens to the user as they arrive makes AI features feel dramatically faster. Server-Sent Events (SSE) is the simplest way to push a stream of text from your server to the browser.

The concept

Model APIs support streaming by returning a sequence of small events (deltas) instead of one final response. Your backend reads that stream and forwards text deltas to the browser. SSE fits perfectly: it is a long-lived HTTP response with Content-Type text/event-stream where the server writes lines like "data: ...\n\n" and the browser receives each event.

In the browser, EventSource handles GET-based SSE with automatic reconnection, but chat requests usually need POST bodies, so many apps use fetch() and read the response body stream directly. Important details: disable proxy buffering, send periodic heartbeats on long streams, stop generation when the user cancels, and record final token usage when the stream ends.

The streaming path

BrowserYour serverLLM APIPOST /api/chatrequest with stream=truedelta "The"data: "The"delta " answer…"data: " answer…"event: done
Tokens flow through your server as they are generated.

Transport options

OptionDirectionNotes
SSE (text/event-stream)Server → clientSimple, HTTP-friendly, ideal for token streams
fetch + ReadableStreamServer → clientWorks with POST; parse SSE or raw text yourself
WebSocketBidirectionalUseful for voice/realtime; more infrastructure
PollingClient pullsSimple but laggy and wasteful

Why streaming matters

Non-streaming (time to see anything)≈9 sStreaming (time to first token)≈0.8 s
Illustrative perceived latency for a long answer.

Practical examples

Node.js (Express) SSE endpoint

Forward deltas and end cleanly; abort upstream if the client leaves.

app.post('/api/chat', async (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache',
                       'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' })
  const controller = new AbortController()
  req.on('close', () => controller.abort())
  const stream = await client.chat.completions.create(
    { model: MODEL, messages: req.body.messages, stream: true }, { signal: controller.signal })
  for await (const chunk of stream) {
    const text = chunk.choices[0]?.delta?.content
    if (text) res.write(`data: ${JSON.stringify(text)}\n\n`)
  }
  res.write('event: done\ndata: {}\n\n'); res.end()
})

Browser: read a POST stream with fetch

Parse SSE lines incrementally.

const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' },
                                       body: JSON.stringify({ messages }), signal: abort.signal })
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader()
let buf = ''
for (;;) {
  const { value, done } = await reader.read(); if (done) break
  buf += value
  const events = buf.split('\n\n'); buf = events.pop()
  for (const e of events) if (e.startsWith('data: ')) output.textContent += JSON.parse(e.slice(6))
}

NGINX: disable buffering for the stream route

Otherwise users see everything at once at the end.

location /api/chat {
    proxy_pass http://app;
    proxy_buffering off;
    proxy_read_timeout 300s;
}

Common mistakes

  • Proxies or compression middleware buffering the stream.
  • Not aborting the upstream request when the user cancels, paying for unused tokens.
  • Rendering markdown on every token without throttling, freezing the UI.
  • Forgetting to record usage at the end of the stream.

Key takeaways

  • Streaming cuts perceived latency to time-to-first-token.
  • SSE is the simplest server → browser stream.
  • Use fetch streams for POST requests; EventSource for GET.
  • Disable buffering, handle cancellation and track usage.

FAQ

Does streaming cost more?

No, token pricing is the same; cancelling early can even save money.

Can I stream structured JSON?

Yes, with partial JSON parsing; many apps stream text and parse structured fields once complete.

How do I stream through serverless platforms?

Use platforms and runtimes that support streaming responses, such as edge or streaming-enabled functions.

More AI articles