The short answer

#

Start a streaming request on the server inside a Route Handler, and return the stream as the response body. In the browser, call fetch(), read response.body chunk by chunk with a reader and a TextDecoder, and append the text to state as it arrives. The API key never leaves the server, and the user sees the first words within a second instead of staring at a spinner for the whole generation.


_18
// app/api/chat/route.ts
_18
import Anthropic from '@anthropic-ai/sdk';
_18
_18
const client = new Anthropic();
_18
_18
export async function POST(req: Request) {
_18
const { prompt } = await req.json();
_18
_18
const stream = client.messages.stream({
_18
model: 'claude-sonnet-5-5',
_18
max_tokens: 1024,
_18
messages: [{ role: 'user', content: prompt }],
_18
});
_18
_18
return new Response(stream.toReadableStream(), {
_18
headers: { 'Content-Type': 'application/x-ndjson; charset=utf-8' },
_18
});
_18
}

How it works

#

A model generates its answer one token at a time. If you wait for the whole message, the user waits for the whole generation: for a 500-word answer that can be ten seconds or more of nothing. Streaming sends each token to the browser as soon as it exists, so the time to first token (often under a second) is what the user feels, and the rest of the answer fills in while they read.

Three pieces make this work in Next.js. The Anthropic SDK's client.messages.stream() opens a streaming connection to the API and gives you events as they arrive. stream.toReadableStream() converts those events into a web ReadableStream of bytes, where each chunk is one event serialised as JSON followed by a newline. A Route Handler in the App Router returns a standard web Response, and a Response accepts a ReadableStream as its body, so Next.js forwards the bytes to the browser as they are produced rather than buffering them.

Because the stream carries whole events, not just text, the client has to pick out the text. Text arrives in content_block_delta events whose delta.type is text_delta. Everything else (message start, usage, stop reason) is still there if you want it.

How to do it

#

Read the stream on the client

response.body.getReader() gives you chunks of bytes. A chunk can end in the middle of a line, so keep a buffer and only parse complete lines.


_48
'use client';
_48
import { useRef, useState } from 'react';
_48
_48
export function Chat() {
_48
const [text, setText] = useState('');
_48
const abortRef = useRef<AbortController | null>(null);
_48
_48
async function ask(prompt: string) {
_48
setText('');
_48
abortRef.current = new AbortController();
_48
_48
const res = await fetch('/api/chat', {
_48
method: 'POST',
_48
headers: { 'Content-Type': 'application/json' },
_48
body: JSON.stringify({ prompt }),
_48
signal: abortRef.current.signal,
_48
});
_48
if (!res.ok || !res.body) throw new Error(`Request failed: ${res.status}`);
_48
_48
const reader = res.body.getReader();
_48
const decoder = new TextDecoder();
_48
let buffer = '';
_48
_48
while (true) {
_48
const { value, done } = await reader.read();
_48
if (done) break;
_48
buffer += decoder.decode(value, { stream: true });
_48
_48
const lines = buffer.split('\n');
_48
buffer = lines.pop() ?? '';
_48
for (const line of lines) {
_48
if (!line.trim()) continue;
_48
const event = JSON.parse(line);
_48
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
_48
setText((prev) => prev + event.delta.text);
_48
}
_48
}
_48
}
_48
}
_48
_48
return (
_48
<div>
_48
<button onClick={() => ask('Explain streaming in one paragraph')}>Ask</button>
_48
<button onClick={() => abortRef.current?.abort()}>Stop</button>
_48
<p>{text}</p>
_48
</div>
_48
);
_48
}

The { stream: true } option on decode() matters: a multi-byte character (an accented letter, an emoji) can be split across two chunks, and without it you get garbage at the seam.

Send plain text instead

If you would rather not parse JSON in the browser, build your own stream on the server and enqueue only the text. The client then appends every decoded chunk directly.


_22
export async function POST(req: Request) {
_22
const { prompt } = await req.json();
_22
const stream = client.messages.stream({
_22
model: 'claude-sonnet-5-5',
_22
max_tokens: 1024,
_22
messages: [{ role: 'user', content: prompt }],
_22
});
_22
_22
const encoder = new TextEncoder();
_22
const body = new ReadableStream({
_22
async start(controller) {
_22
for await (const event of stream) {
_22
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
_22
controller.enqueue(encoder.encode(event.delta.text));
_22
}
_22
}
_22
controller.close();
_22
},
_22
});
_22
_22
return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
_22
}

You lose the metadata (usage, stop reason) on the client, but you can still read it on the server with await stream.finalMessage() after the loop and log it there.

Let the user cancel

The AbortController in the client example cancels the fetch(). The browser closes the connection, Next.js aborts the request, and the SDK stops reading from the API. If you have your own server-side loop, you can also listen for req.signal and call stream.abort() so you stop paying for tokens the user will never see.


_10
req.signal.addEventListener('abort', () => stream.abort());

Keep the key on the server

new Anthropic() reads ANTHROPIC_API_KEY from the environment of the server process. Put it in .env.local, never prefix it with NEXT_PUBLIC_, and never import the SDK into a file marked 'use client'. The browser only ever talks to your Route Handler.

Runtime and duration

Use the Node.js runtime for this handler (it is the default). A long answer can take longer than your host's default function timeout, and when the function is killed the stream just ends mid-sentence. Raise the limit with a route segment config and check your host's maximum for your plan.


_10
export const runtime = 'nodejs';
_10
export const maxDuration = 60; // seconds

Common pitfalls

#
  • Forgetting { stream: true } on the decoder. Characters split across chunks become replacement symbols. Always pass it inside the read loop, then call decoder.decode() once more with no arguments at the end to flush.
  • Parsing partial lines. One reader.read() is not one event. Buffer until you see a newline, or JSON.parse will throw on a half-written object.
  • Setting state with the stale value. Use the functional form setText((prev) => prev + chunk). setText(text + chunk) inside the loop captures the value from the render that started the request.
  • Awaiting the whole stream on the server. If you call finalMessage() before returning the Response, you have buffered everything and the user gets no streaming benefit.
  • A proxy or CDN that buffers. Some reverse proxies hold the response until it completes. If it works locally and not in production, check the proxy's buffering settings before touching your code.
  • Not handling errors mid-stream. A rate limit or network error after the headers have been sent cannot change the status code. Catch errors in the server loop and enqueue a final marker or close the stream, and check res.ok on the client before reading.
#

quick question

Was this resource helpful?