Skip to content
jshacks.dev
APIs

Stream LLM tokens to browser

Stream LLM tokens to the browser by relaying a model's chunks as server-sent events and reading them with fetch on the client.

2 min read
Summarize in AI

A chat interface feels faster when the answer appears as it is written. The pattern is the same for any model: the server relays each chunk as an event and the browser appends it.

server.jsJavaScript
import { createServer } from 'node:http';

async function* tokens() {
  for (const word of ['The', ' answer', ' is', ' 42', '.']) {
    await new Promise((r) => setTimeout(r, 100));
    yield word;
  }
}

createServer(async (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
  });
  for await (const token of tokens()) {
    res.write(`data: ${JSON.stringify(token)}\n\n`);
  }
  res.end('data: [DONE]\n\n');
}).listen(3000);
client.jsJavaScript
const res = await fetch('/chat', { method: 'POST' });
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let text = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  for (const line of value.split('\n')) {
    if (!line.startsWith('data: ') || line === 'data: [DONE]') continue;
    text += JSON.parse(line.slice(6));
    console.log(text);
  }
}

The tokens() generator stands in for a model SDK's stream; swap it for the real iterator. The client uses fetch rather than EventSource because EventSource can only make GET requests and cannot send a body or an Authorization header.

A network chunk can end in the middle of a line, so a production client keeps a buffer and splits only on complete \n\n boundaries. Keep the API key on the server and stop the model call when the client disconnects.

Also inBrowser
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.