Users Pricing

articles

Home Articles Streaming Responses From Claude in a Web App – MindStick
Streaming Responses From Claude in a Web App

Streaming Responses From Claude in a Web App

Yash Bajpai 78 28 Nov 2026

Waiting ten seconds for a complete answer feels slow. Watching the first words appear within a second and the rest flow in feels fast, even when the total time is identical. That is why every major AI chat interface streams its responses.

Streaming also has a practical benefit: long responses can take long enough to hit network timeouts if you wait for the whole thing. Anthropic recommends streaming for long outputs for exactly this reason.

This article explains how streaming works in the Claude API and how to relay it safely from your server to a browser, with examples in Python and notes for .NET developers.

How Claude streaming works

When you set stream to true in a Messages API request, or use the SDK's streaming helper, the API returns a stream of server-sent events (SSE) instead of one JSON response. Each event describes part of the response as it is generated.

The main event types are:

- message_start: the message begins, with metadata such as the model and initial usage.
- content_block_start: a new content block begins, such as a text block or a tool use block.
- content_block_delta: a piece of content arrives. For text, this is a text delta with the next chunk of words. For tool use, it is partial JSON for the tool input. For extended thinking, it is a thinking delta.
- content_block_stop: the content block is complete.
- message_delta: top-level changes near the end, including the stop reason and final output token usage.
- message_stop: the message is complete.
- ping: keep-alive events you can ignore.
- error: an error occurred mid-stream, such as an overloaded error.

The SDKs parse these events for you, so you rarely handle raw SSE yourself unless you call the HTTP API directly.

Streaming in Python with the SDK

The simplest way to stream text is the SDK's stream helper, which yields text chunks:

import anthropic
client = anthropic.Anthropic()

with client.messages.stream(model="claude-sonnet-5-5", matokens=1024,
messages=[{"role": "user", "content": "Explain DNS briefly."}]) as stream:
for chunk in stream.text_stream:
print(chunk, end="", flush=True)
final = stream.get_final_message()
print(final.usage)

The helper also gives you the complete final message at the end, including usage figures and stop reason, which you should log.

The architecture for a web app

Never call the Claude API directly from the browser. That would expose your API key to anyone who opens the developer tools. Instead:

1. The browser sends the user's message to your server.
2. Your server authenticates the user, applies limits and calls Claude with streaming.
3. Your server forwards text chunks to the browser as they arrive.
4. The browser appends chunks to the page.

Your server is a relay that adds security, logging, rate limiting and business logic.

A Python relay with FastAPI

FastAPI's streaming response makes the relay short. This example forwards plain text chunks; many applications instead send small JSON events so they can include metadata.

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app, client = FastAPI(), anthropic.AsyncAnthropic()

@app.post("/chat")
async def chat(body: dict):
async def gen():
async with client.messages.stream(model="claude-sonnet-5-5",
matokens=1024, messages=body["messages"]) as s:
async for text in s.text_stream:
yield text
return StreamingResponse(gen(), media_type="text/plain")

In production, validate the incoming messages, check the user's session and quota, cap the message length and do not pass arbitrary client-supplied parameters such as model or max tokens straight through.

Reading the stream in the browser

Modern browsers can read a streamed response body incrementally using the Fetch API. You call fetch with a POST request, get a reader from the response body, decode each chunk with a text decoder and append it to the chat bubble.

The flow in plain terms:

1. Send a POST request to your chat endpoint with the conversation as JSON.
2. Get a reader from the response body.
3. Loop: read a chunk, decode it as text, append it to the message element.
4. Stop when the reader reports it is done.

Because the standard EventSource interface only supports GET requests, many apps use fetch with a readable stream as described, which supports POST bodies. Libraries such as the Vercel AI SDK wrap this pattern for React and other frameworks if you prefer not to write it yourself.

Rendering safely

Claude often responds with markdown. If you render it as HTML, run it through a markdown renderer with sanitisation enabled, so that any HTML in the model's output cannot run scripts in your page. Treat model output as untrusted content, just like user input.

Rendering markdown incrementally can cause flicker as partial syntax arrives. Common approaches are to re-render the accumulated text on each chunk, which is simple and usually fast enough, or to throttle rendering to a few times per second.

Streaming in ASP.NET Core

For .NET developers, the same relay pattern applies. Anthropic provides an official C# SDK, and there are also community libraries. In ASP.NET Core, you can write chunks directly to the response body and flush after each chunk, or return an async enumerable from a minimal API endpoint. Set the content type appropriately, disable response buffering for that endpoint, and make sure any reverse proxy in front of the app does not buffer the response.

A note on IIS and proxies

If you host behind IIS, Nginx or a load balancer, buffering is the most common reason streaming appears not to work. The server sends chunks, but the proxy collects the whole response before passing it on. Check settings for response buffering and compression on the proxy, and for SSE responses consider disabling dynamic compression for that route. On Nginx, the X-Accel-Buffering response header set to no is a common fix.

Handling errors mid-stream

Streams can fail after they start. The API may send an error event, for example if the service becomes overloaded, or the network connection may drop.

Good handling includes:

- catching exceptions in the server generator and sending a clear error marker to the client
- showing the user a friendly message and a retry button
- keeping the partial response visible rather than erasing it
- logging the request ID and the error type

Because the SDK's automatic retries apply to the initial request, an error after streaming begins usually needs to be handled by your application.

Cancellation

Users often stop a response midway, either by clicking a stop button or navigating away. When the browser cancels the fetch, your server should detect the disconnect and close the stream to Claude. That stops generation and avoids paying for output nobody reads.

In FastAPI and most async frameworks, a client disconnect raises a cancellation inside the generator; make sure the async context manager exits cleanly so the upstream stream is closed.

Streaming with tool use

When Claude calls tools, the stream contains tool use content blocks whose input arrives as partial JSON deltas. The SDK accumulates these for you, and the final message contains the complete tool input. A typical chat UI shows a status such as "Looking up your order" while the tool runs, then streams the final answer from the follow-up request.

Streaming with extended thinking

If you enable extended thinking, the stream includes thinking deltas before the text. You can show a "thinking" indicator, display a summary of the reasoning if your product calls for it, or simply hide it and start displaying when text deltas begin.

Performance tips

- Keep time to first token low with shorter prompts, prompt caching and the right model size.
- Send a quick acknowledgement to the UI immediately, such as a typing indicator, before the first token arrives.
- Avoid heavy processing per chunk on the server.
- Use HTTP/2 or keep-alive connections where possible.
- Monitor end-to-end latency, not just API latency.

Logging and usage tracking

Streaming does not remove the need to track tokens. The final message delta includes output token usage, and the SDK's final message gives complete usage. Log model, input tokens, output tokens, cache usage, latency, stop reason and request ID for every request.

Key takeaways

- Streaming makes responses feel faster and avoids timeouts on long outputs.
- The Claude API streams server-sent events such as content block deltas and message stops.
- Always relay through your own server, never from the browser with your key.
- Read the stream in the browser with fetch and a reader, and render markdown safely.
- Watch out for proxy buffering on IIS, Nginx and load balancers.
- Handle mid-stream errors and user cancellation properly.

Streaming is a small amount of extra engineering for a large improvement in user experience. Once your relay is in place, every Claude feature in your app benefits.

Related articles on MindStick

- Getting Started With the Claude API, A Complete Developer Guide
- Reducing Latency in Claude-Powered Applications
- Hosting an AI Chatbot on Windows Server and IIS
- Tool Use in Claude, Letting the Model Call Your Functions

SDK interfaces, event types and hosting configurations change over time. Check Anthropic's streaming documentation and your web server's documentation for current details.


Yash Bajpai

MATLAB Developer at Wipro

Hi, I am Yash. I work as a MATLAB Developer at Wipro, Bhopal and my work is mostly about MATLAB and Simulink models for control systems. Before this I spent 3 years at Accenture. I studied B.Tech in Computer Science from the Indian Institute of Technology Kanpur. Weekends are for playing cricket.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md