Claude API Basics

Streaming Responses

Implement real-time streaming responses for better user experience in chat applications.

Why Stream Responses?

Instead of waiting for the entire response before displaying it, streaming shows text as it's generated — exactly like how ChatGPT and Claude.ai work.

Benefits:

  • Better perceived performance
  • Users can start reading immediately
  • Can cancel long responses early
  • Essential for chat applications

Streaming with the SDK

The Anthropic SDK provides a convenient stream() method that handles the SSE (Server-Sent Events) stream for you.

Server-Side Streaming

For web apps, you typically create a streaming endpoint on your backend and forward the stream to the frontend.

React Hook for Streaming

Use the useCallback and useState hooks to implement real-time streaming in your React components.

Example

typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Basic streaming
async function streamResponse(prompt: string) {
  const stream = await client.messages.stream({
    model: "claude-opus-4-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: prompt }],
  });

  for await (const chunk of stream) {
    if (
      chunk.type === "content_block_delta" &&
      chunk.delta.type === "text_delta"
    ) {
      process.stdout.write(chunk.delta.text);
    }
  }

  const finalMessage = await stream.finalMessage();
  console.log("\nTotal tokens:", finalMessage.usage);
}

// Next.js API Route with streaming
export async function POST(req: Request) {
  const { message } = await req.json();

  const stream = await client.messages.stream({
    model: "claude-opus-4-5",
    max_tokens: 2048,
    messages: [{ role: "user", content: message }],
  });

  // Return as ReadableStream for streaming to frontend
  const readableStream = new ReadableStream({
    async start(controller) {
      for await (const chunk of stream) {
        if (
          chunk.type === "content_block_delta" &&
          chunk.delta.type === "text_delta"
        ) {
          controller.enqueue(
            new TextEncoder().encode(chunk.delta.text)
          );
        }
      }
      controller.close();
    },
  });

  return new Response(readableStream, {
    headers: { "Content-Type": "text/plain; charset=utf-8" },
  });
}
Try it yourself — TYPESCRIPT