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