Skip to content
jshacks.dev
APIs

Stream LLM response with ReadableStream

Stream an LLM response with fetch and a ReadableStream reader, decode server-sent events chunk by chunk, and print tokens as they arrive in Node.js 24.

1 min read
Summarize in AI

Waiting for a full completion makes a chat feel slow. Setting stream: true makes the API send server-sent events, and response.body is a ReadableStream you can read as the bytes arrive.

stream.jsJavaScript
const res = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    'x-api-key': process.env.ANTHROPIC_API_KEY,
    'anthropic-version': '2023-06-01',
  },
  body: JSON.stringify({
    model: 'claude-sonnet-5-5',
    max_tokens: 256,
    stream: true,
    messages: [{ role: 'user', content: 'Say hello in three words.' }],
  }),
});

const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += value;
  const lines = buffer.split('\n');
  buffer = lines.pop();
  for (const line of lines) {
    if (!line.startsWith('data: ')) continue;
    const event = JSON.parse(line.slice(6));
    if (event.type === 'content_block_delta') process.stdout.write(event.delta.text);
  }
}
Text
Hello there, friend!

The model's wording will differ on your run. TextDecoderStream turns bytes into text, and the buffer keeps a half-received line until the next chunk completes it, because a network chunk can end in the middle of an event.

Parsing data: lines by hand is fine for a script. For a browser form or a production client, use the SDK, which also handles errors sent mid-stream. See the streaming guide.

Also inAsync
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
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

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.