← Blog

Claude API Next.js App Router Setup Guide

2026-11-20 · 4 min read · SubToAPI Team

Setting up the Claude API in a Next.js App Router project means creating a server-side route handler that calls the API, keeping your key off the client, and streaming the response back to a React component. This guide walks through the full setup: project structure, environment variables, the route handler itself, and a client component that renders streamed tokens as they arrive.

The two things people usually get stuck on are (1) where to put the API call so the key never ships to the browser, and (2) how to stream the response through a Next.js route handler without buffering the whole reply first. Both are solved the same way: a route.ts file under app/api/, and the Web Streams API that Next.js route handlers support natively.

Project structure

A minimal setup looks like this:

app/
  api/
    chat/
      route.ts
  chat/
    page.tsx
.env.local

The route handler lives server-side only. The page under app/chat is a client component that talks to /api/chat, never directly to Anthropic or any provider.

Environment variables

Create .env.local at the project root:

ANTHROPIC_API_KEY=sk-ant-...

Next.js only exposes variables prefixed with NEXT_PUBLIC_ to the browser, so leaving off that prefix keeps this key server-only by default — but it's still worth double-checking you never import it into a "use client" file, since a typo in your import chain is a common way keys leak into client bundles.

If you're using SubToAPI instead of calling the provider directly, the variable name changes but the pattern is identical:

SUBTOAPI_KEY=sub_live_...

The route handler

Here's a route handler that accepts a POST with a message array and streams the response:

// app/api/chat/route.ts
export const runtime = "nodejs";

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

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

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

This forwards the upstream SSE stream directly to the client without buffering — Next.js route handlers support passing a ReadableStream straight through as the Response body, which is what upstream.body is.

If you're using SubToAPI, the only change is the endpoint and header:

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

Full request/response shapes are in the docs and the streaming guide if you want to see how tool calls and usage metadata show up in the stream.

The client component

// app/chat/page.tsx
"use client";
import { useState } from "react";

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

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

    const reader = res.body!.getReader();
    const decoder = new TextDecoder();
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      setOutput((prev) => prev + decoder.decode(value));
    }
  }

  return (
    <div>
      <textarea value={input} onChange={(e) => setInput(e.target.value)} />
      <button onClick={send}>Send</button>
      <pre>{output}</pre>
    </div>
  );
}

This is intentionally bare — in production you'd parse the SSE data: lines into individual text deltas rather than dumping raw chunks into the DOM, but the plumbing (fetch → route handler → stream → UI) is correct and doesn't change once you add that parsing layer.

Common mistakes in this setup

Calling the API from a Server Component instead of a route handler. Server Components can fetch data, but they render once and don't support token-by-token streaming back to the browser the way a route handler + client component does. Use a Server Component for a static first message; use a route handler for anything the user types.

Forgetting export const runtime = "nodejs". On the Edge runtime, some streaming behavior and header handling differs. If you hit odd truncation issues, confirm which runtime the route is actually running on.

Setting max_tokens too low and silently truncating output. This isn't a Next.js issue specifically, but it's the most common "why does my app cut off mid-sentence" bug reported in setups like this.

Not handling rate limits or key rotation. Direct Anthropic integration means you're on your own for retry logic, usage tracking per user, and team key management. If you want that handled, SubToAPI sits behind the same /v1/messages style request shape and adds a dashboard for keys, streaming, and usage — the quickstart covers the swap in under five minutes, and plans start at €9/month with a free trial at signup.

Adding tool use

If your app needs Claude to call functions (database lookups, search, calculators), the request body gets a tools array and the response includes tool_use blocks your route handler needs to detect and act on before sending a follow-up request. The tool use docs show the schema format; the App Router setup itself doesn't change — you're still POSTing from the same route handler, just handling a different block type in the response stream.

questions

Do I need a backend server, or can I call Claude directly from the client? Don't call it from the client. API keys in client-side code are exposed in the browser's network tab and bundle. Always proxy through a Next.js route handler.

Can I use Server Actions instead of a route handler? Server Actions work for non-streaming requests, but streaming token-by-token output back to a client component is more straightforward with a route handler returning a ReadableStream.

What's the fastest way to get this running without managing provider keys and billing myself? Swap the fetch target to https://api.subtoapi.app/v1/messages with a sub_live_... key — see pricing for plan details and the quickstart for the full setup.

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 →