← Blog

How to Stream Claude Responses in Next.js

2026-11-10 · 5 min read · SubToAPI Team

Streaming Claude responses in Next.js means setting up a Route Handler that proxies a streaming request to Claude's API and pipes the response back to the browser as a ReadableStream, then consuming that stream on the client with fetch and a TextDecoder loop (or a hook like useChat). This gives you token-by-token output in the UI instead of waiting for the full response to finish generating.

The tricky part isn't calling Claude — it's getting the streaming data through Next.js correctly, on both the App Router and the client side, without buffering the whole response or breaking on edge runtimes. Below is a complete, working setup for the App Router (Next.js 13+), plus the client-side consumption code and common pitfalls.

Why streaming matters for Claude in Next.js

Claude responses, especially longer ones, can take several seconds to generate in full. Without streaming, your UI just shows a spinner the entire time. With streaming, you render partial text as it arrives, which makes the app feel instant even though total generation time is unchanged. This is standard for chat UIs, coding assistants, and any tool where users expect to see output forming in real time.

Setting up the Route Handler

In the App Router, streaming lives in a Route Handler under app/api/.../route.ts. The handler needs to:

  1. Call Claude's API with streaming enabled.
  2. Convert the response into a ReadableStream.
  3. Return that stream directly in the Response object.
// app/api/chat/route.js
export const runtime = "edge"; // optional, but recommended for streaming

export async function POST(req) {
  const { messages } = await req.json();

  const upstream = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2023-06-01",
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      stream: true,
      messages,
    }),
  });

  return new Response(upstream.body, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
    },
  });
}

The key detail: you're not reading upstream.body into memory and re-serializing it. You pass the raw body stream straight through. This avoids buffering and keeps latency low.

If you're using SubToAPI instead of calling Anthropic directly — useful when you want API keys scoped per application, usage metadata, or team billing without managing Anthropic credentials yourself — the handler looks almost identical, just pointed at a different endpoint:

export async function POST(req) {
  const { messages } = await req.json();

  const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      stream: true,
      messages,
    }),
  });

  return new Response(upstream.body, {
    headers: { "Content-Type": "text/event-stream" },
  });
}

Details on request shape and streaming event formats are in the docs and the streaming guide.

Consuming the stream on the client

On the client, you fetch the route handler and read the response body as a stream, decoding chunks as they arrive:

"use client";
import { useState } from "react";

export default function Chat() {
  const [output, setOutput] = useState("");

  async function sendMessage(text) {
    setOutput("");
    const res = await fetch("/api/chat", {
      method: "POST",
      body: JSON.stringify({
        messages: [{ role: "user", content: text }],
      }),
    });

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

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value, { stream: true });
      setOutput((prev) => prev + parseChunk(chunk));
    }
  }

  return <div>{output}</div>;
}

The raw chunks will be in SSE format (event: content_block_delta, data: {...}), so parseChunk needs to extract the text delta from each data: line and ignore control events. If you're calling Claude directly, the event names and payload shapes are documented in Anthropic's streaming spec; if you're going through SubToAPI, the same event structure is preserved so your parsing logic doesn't change — see the messages docs for the exact field names.

Common pitfalls

Buffering by the platform. Some hosting setups (certain reverse proxies, older Vercel configs) buffer responses before sending them to the client, which defeats streaming entirely. Using the edge runtime in your Route Handler avoids most of this because edge functions are designed for streaming by default. If you're on the Node.js runtime, make sure nothing in your middleware chain is awaiting the full body before responding.

Forgetting stream: true in the Claude request. Without it, Claude's API returns the full response in one shot, and your "streaming" handler just passes through a single chunk — functionally no different from a normal request.

Not handling partial JSON. SSE chunks can arrive split mid-line if the network is slow. A naive JSON.parse on each chunk will throw. Buffer incomplete lines and only parse once you have a full data: {...}\n\n block.

Mixing up Server Components and Route Handlers. Streaming output to a React Server Component directly (via Suspense and async generators) is a different pattern than the fetch-based approach above, and the two don't combine cleanly. For a chat-style UI with user input, the Route Handler + client fetch pattern is simpler and more predictable.

When to reach for a managed layer

If you're building this once for a side project, calling Claude directly from your Route Handler is fine. If you're shipping it in a product with multiple environments, team members, or need per-application API keys and usage breakdowns without building that tooling yourself, a layer like SubToAPI handles key management, streaming, and usage metadata so your Next.js code stays focused on the UI. Plans start at €9/month with a free trial — see pricing or jump straight to the quickstart if you want to wire it up in the next ten minutes.

questions

Does streaming work with the Next.js Pages Router too? Yes, using res.write() in an API route and keeping the connection open, but it's more manual. The App Router's Route Handlers with ReadableStream support are the cleaner approach for new projects.

Can I stream Claude responses from a Server Component directly? Not practically for interactive chat — Server Components render once per request and don't support the incremental client-side updates a text input + streaming reply needs. Use a Route Handler plus client-side fetch instead.

Why does my stream show up all at once instead of incrementally? Usually a buffering issue: either stream: true is missing from the Claude request, you're on a runtime/proxy that buffers responses, or you're awaiting res.text() instead of reading the stream chunk by chunk on the client.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →