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.
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.
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);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.