---
title: "How do I stream an LLM response to the browser in Next.js?"
description: "Return the SDK's ReadableStream from a Route Handler, read it on the client with fetch and getReader, and append text to state as each chunk arrives."
url: https://www.danny.engineering/answer/ai/how-do-i-stream-an-llm-response-to-the-browser-in-nextjs
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:34:00.000Z
tags: ["AI"]
---

# How do I stream an LLM response to the browser in Next.js?

## 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.


```typescript
// app/api/chat/route.ts
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

export async function POST(req: Request) {
  const { prompt } = await req.json();

  const stream = client.messages.stream({
    model: 'claude-sonnet-5-5',
    max_tokens: 1024,
    messages: [{ role: 'user', content: prompt }],
  });

  return new Response(stream.toReadableStream(), {
    headers: { 'Content-Type': 'application/x-ndjson; charset=utf-8' },
  });
}
```


## 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.


```typescript
'use client';
import { useRef, useState } from 'react';

export function Chat() {
  const [text, setText] = useState('');
  const abortRef = useRef<AbortController | null>(null);

  async function ask(prompt: string) {
    setText('');
    abortRef.current = new AbortController();

    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt }),
      signal: abortRef.current.signal,
    });
    if (!res.ok || !res.body) throw new Error(`Request failed: ${res.status}`);

    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      const lines = buffer.split('\n');
      buffer = lines.pop() ?? '';
      for (const line of lines) {
        if (!line.trim()) continue;
        const event = JSON.parse(line);
        if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
          setText((prev) => prev + event.delta.text);
        }
      }
    }
  }

  return (
    <div>
      <button onClick={() => ask('Explain streaming in one paragraph')}>Ask</button>
      <button onClick={() => abortRef.current?.abort()}>Stop</button>
      <p>{text}</p>
    </div>
  );
}
```


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.


```typescript
export async function POST(req: Request) {
  const { prompt } = await req.json();
  const stream = client.messages.stream({
    model: 'claude-sonnet-5-5',
    max_tokens: 1024,
    messages: [{ role: 'user', content: prompt }],
  });

  const encoder = new TextEncoder();
  const body = new ReadableStream({
    async start(controller) {
      for await (const event of stream) {
        if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
          controller.enqueue(encoder.encode(event.delta.text));
        }
      }
      controller.close();
    },
  });

  return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
}
```


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.


```typescript
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.


```typescript
export const runtime = 'nodejs';
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.

## Related reading

- [Route Handlers in the Next.js App Router](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [Route segment config, including maxDuration](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config)
- [ReadableStream on MDN](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
- [Streaming Messages in the Claude docs](https://platform.claude.com/docs/en/build-with-claude/streaming)
