← LearnClaude API · Setup

Claude TypeScript SDK: Streaming Responses Tutorial

To stream Claude responses with the TypeScript SDK, install `@anthropic-ai/sdk` via npm, initialize the client with your API key, and use the `.stream()` method to receive text tokens as they arrive. Call `.finalMessage()` after the stream closes to get the complete message object including usage statistics.

The Claude TypeScript SDK makes streaming responses straightforward: install the @anthropic-ai/sdk package, call .stream() instead of .create(), and iterate over incoming text chunks in real time. This tutorial walks you through every step — from installation to handling edge cases — so you can build a responsive chat or writing interface without wrestling with raw server-sent events.

What Is the Claude TypeScript SDK and Why Use It for Streaming?

Anthropic's official TypeScript SDK is a client library that wraps the Claude Messages API, giving you idiomatic TypeScript interfaces, strong type safety, automatic retry logic with exponential backoff, and built-in streaming support via server-sent events — all without writing raw HTTP plumbing yourself. It is available as @anthropic-ai/sdk on npm and is designed for both Node.js and browser environments.

Streaming is the difference between a user staring at a blank screen for several seconds and watching words appear immediately. The SDK's streaming helpers also accumulate events into a final message object, so you get usage statistics without manually reassembling the event stream. You can read the full streaming documentation in the official streaming messages guide.

How Do You Set Up the TypeScript SDK Before Streaming?

  1. Get an API key. Obtain one from console.anthropic.com under the API Keys section.
  2. Set the environment variable. Export your key so the SDK can find it automatically:
    export ANTHROPIC_API_KEY=sk-ant-...
  3. Install the package.
    npm install @anthropic-ai/sdk
  4. Initialize the client. The client reads ANTHROPIC_API_KEY from the environment automatically:
    import Anthropic from '@anthropic-ai/sdk';
    const client = new Anthropic();

That's the entire setup. No extra configuration files are required for basic usage. See the Client SDKs reference for the full list of initialization options.

How Do You Stream a Response with the TypeScript SDK?

The core pattern uses the .stream() method. Here is a complete, working example that streams a response token-by-token and then retrieves the final message object:

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

async function main() {
  const stream = await client.messages.stream({
    model: 'claude-sonnet-4-5-20250929',
    max_tokens: 512,
    messages: [
      { role: 'user', content: 'Explain quantum entanglement in simple terms.' }
    ],
  });

  // Print each text chunk as it arrives
  for await (const chunk of stream.textStream) {
    process.stdout.write(chunk);
  }

  // Retrieve the fully accumulated message with usage stats
  const finalMessage = await stream.finalMessage();
  console.log('\n\nStop reason:', finalMessage.stop_reason);
  console.log('Input tokens:', finalMessage.usage.input_tokens);
  console.log('Output tokens:', finalMessage.usage.output_tokens);
}

main();

Key points about this pattern:

  • stream.textStream is an async iterable that yields each text chunk as it arrives from the API.
  • stream.finalMessage() waits for the stream to close and returns the complete, accumulated message — including stop reason and token usage — without you having to manually stitch events together.
  • The SDK handles reconnection and event assembly automatically, so a mid-stream network hiccup does not leave you with a truncated response.

How Do You Verify the Stream Completed Successfully?

Always check the stop_reason on the final message before treating the response as complete. A value of end_turn means Claude finished naturally. Other values — such as tool_use or max_tokens — indicate the response is not yet final and your application needs to take further action (execute a tool, increase the token budget, etc.).

const finalMessage = await stream.finalMessage();

if (finalMessage.stop_reason === 'end_turn') {
  console.log('Response complete.');
} else if (finalMessage.stop_reason === 'tool_use') {
  // Extract tool_use blocks and execute them
  console.log('Claude wants to use a tool — handle it before continuing.');
} else {
  console.log('Unexpected stop reason:', finalMessage.stop_reason);
}

What Are the Most Common Streaming Pitfalls and How Do You Fix Them?

Stream stops mid-response

If you implement raw SSE handling instead of using the SDK's .stream() helper, you are responsible for reconnection and event assembly. The fix is simple: use the SDK's built-in streaming context — call .finalMessage() after the stream closes to get the fully accumulated message. These helpers handle reconnection and event assembly automatically.

API key not found at runtime

Ensure ANTHROPIC_API_KEY is exported in the shell where the process runs, not just defined in a config file. Verify with echo $ANTHROPIC_API_KEY. You can also pass it explicitly — new Anthropic({ apiKey: '...' }) — but never hard-code it in committed code.

Rate limit errors under concurrent load

Both SDKs retry on rate-limit errors automatically with exponential backoff by default. For very high concurrency, limit the number of simultaneous requests using a concurrency-limiting queue. Check your organization's tier limits in the console if you consistently hit them. More detail is available in Anthropic's rate limits guide.

Unexpected billing when using a Claude subscription

If you have a Pro, Max, Team, or Enterprise subscription and have ANTHROPIC_API_KEY set in your environment, the SDK will use pay-as-you-go API billing instead of your plan credits. Unset the variable when you want to authenticate via your subscription.

When Should You Use Streaming vs. a Standard API Call?

Scenario Use Streaming (.stream()) Use Standard (.create())
Chat or writing interface ✅ Show tokens as they arrive ❌ User waits for full response
Background batch processing ❌ Unnecessary overhead ✅ Simpler, no stream management
Latency-sensitive pipelines ✅ First token arrives faster ❌ Full round-trip before any output
Need usage stats immediately .finalMessage() includes usage ✅ Response object includes usage
Large-volume independent requests ❌ Not ideal ✅ Consider Batch API for cost savings

What Else Can the TypeScript SDK Do Beyond Streaming?

Streaming is one capability among many. The same @anthropic-ai/sdk package also supports:

  • Tool use and function calling — Define tools in the SDK's schema format; when Claude returns a tool_use block, execute the function and feed results back in a follow-up message.
  • Vision and document analysis — Pass base64-encoded images as content blocks using the SDK's typed content block constructors to ensure correct payload formatting.
  • MCP integration — Use the SDK's in-process MCP server helpers to expose custom tools to Claude without running a separate service.
  • Beta features — Access experimental capabilities through the beta namespace on the client.

The TypeScript SDK's strong type definitions catch parameter mistakes at compile time, which is especially valuable for complex message shapes and tool schemas — a concrete advantage over raw HTTP calls.

Is the TypeScript SDK Worth Using Over Raw HTTP Requests?

For almost every production use case, yes. Raw HTTP is appropriate when you are debugging the exact wire format of a request, integrating from a language without an official SDK, or when adding any dependency is a hard constraint. In every other situation, the SDK's automatic retries, type safety, streaming helpers, and idiomatic async patterns save significant development time and reduce the surface area for bugs. The SDK is open-source and actively maintained on GitHub, so you can inspect its behavior whenever needed.

Frequently asked questions

How do I install the Claude TypeScript SDK?

Run `npm install @anthropic-ai/sdk` in your project directory, then set the `ANTHROPIC_API_KEY` environment variable. The client reads the key automatically when you call `new Anthropic()`.

What method do I use to stream responses in the TypeScript SDK?

Use `client.messages.stream()` instead of `client.messages.create()`. Iterate over `stream.textStream` to receive chunks as they arrive, then call `stream.finalMessage()` after the stream closes to get the complete message with usage statistics.

How do I get token usage data when streaming?

Call `stream.finalMessage()` after the stream finishes. This returns the fully accumulated message object, including `usage.input_tokens` and `usage.output_tokens`, without you having to manually reassemble stream events.

Why does my stream stop mid-response?

If you are handling raw server-sent events manually, network interruptions can truncate the response. Use the SDK's built-in `.stream()` helper instead — it handles reconnection and event assembly automatically.

Can I use the TypeScript SDK in a browser environment?

Yes. The `@anthropic-ai/sdk` package is designed for both Node.js and browser environments, though you should never expose your API key in client-side code.

What is the difference between `.stream()` and the Batch API?

Use `.stream()` for real-time, latency-sensitive responses where you want to display output as it arrives. Use the Batch API when processing large volumes of independent requests that do not need immediate responses — it processes requests asynchronously and offers a cost discount.

Go deeper

SDKs (Python, TypeScript) is one of 85 features in Claude Master — the independent, continuously updated manual with worked examples, the pitfalls, and the workflows that put Claude to work.

Get Claude Master — founding price

Independent product. Not affiliated with or endorsed by Anthropic. "Claude" is a trademark of Anthropic, used here only to describe the subject of this guide.