Stream Claude API responses in Node.js using @anthropic-ai/sdk. Print tokens as they arrive with the streaming helper or raw event stream.
The @anthropic-ai/sdk streaming helper handles SSE parsing automatically.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const stream = await client.messages.stream({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a function that parses CSV in JavaScript." }]
});
for await (const chunk of stream) {
if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
process.stdout.write(chunk.delta.text);
}
}
console.log();
const stream = client.messages.stream({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain closures in JavaScript." }]
});
stream.on("text", (text) => process.stdout.write(text));
const finalMsg = await stream.finalMessage();
console.log(`
Used ${finalMsg.usage.output_tokens} output tokens.`);
import express from "express";
import Anthropic from "@anthropic-ai/sdk";
const app = express();
app.use(express.json());
const client = new Anthropic();
app.post("/stream", async (req, res) => {
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked");
const stream = await client.messages.stream({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: req.body.prompt }]
});
for await (const chunk of stream) {
if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
res.write(chunk.delta.text);
}
}
res.end();
});
app.listen(3000);
See the Python streaming example for server-side Python usage. For tool use with streaming, see the Node.js tool use example.