← Blog

Claude API Next.js App Router Setup Guide

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

Setting up the Claude API in a Next.js App Router project means creating a server-side route handler that holds your API key, calling the API from that route, and streaming or returning the response to your client components. You never call Claude directly from the browser — App Router's app/api/*/route.ts files are built exactly for this kind of server-only integration.

This guide walks through the full setup: project structure, environment variables, a working route handler, a client component that consumes it, and how to add streaming so responses render token-by-token instead of all at once.

Why App Router changes the setup

With the Pages Router, you'd put API logic in pages/api/.ts. App Router replaces that with app/api//route.ts files that export HTTP method handlers (GET, POST, etc.) directly. These run on the server by default, which is exactly where your Claude API key needs to live — it should never be exposed in client-side JavaScript or NEXT_PUBLIC_* environment variables.

The other App Router-specific detail is Server Components. Since most of your app's components are server-rendered by default, you could call Claude directly inside a Server Component for one-off, non-interactive use cases (like generating static copy at build time). But for anything interactive — a chat UI, a form that calls the model on submit — you still want a dedicated route handler that a Client Component can fetch() against.

Project structure

A minimal setup looks like this:

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

Step 1: Store your API key

Create .env.local in your project root:

ANTHROPIC_API_KEY=sk-ant-xxxxxxxx

Never prefix this with NEXT_PUBLIC_ — that prefix tells Next.js to bundle the value into client JavaScript, which would leak your key. Restart your dev server after adding or changing env vars.

Step 2: Create the route handler

// app/api/chat/route.ts
import { NextRequest, NextResponse } from "next/server";

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

  const response = 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,
      messages,
    }),
  });

  if (!response.ok) {
    const error = await response.text();
    return NextResponse.json({ error }, { status: response.status });
  }

  const data = await response.json();
  return NextResponse.json(data);
}

A few things that matter here:

Step 3: Call it from a Client Component

Route handlers are invisible to Server Components doing SSR, so interactive UI needs "use client" and a fetch call:

// app/chat/ChatForm.tsx
"use client";

import { useState } from "react";

export default function ChatForm() {
  const [input, setInput] = useState("");
  const [reply, setReply] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);

    const res = await fetch("/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        messages: [{ role: "user", content: input }],
      }),
    });

    const data = await res.json();
    setReply(data.content?.[0]?.text ?? "Error");
    setLoading(false);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Ask something..."
      />
      <button type="submit" disabled={loading}>
        {loading ? "Thinking..." : "Send"}
      </button>
      <p>{reply}</p>
    </form>
  );
}

Drop this into app/chat/page.tsx and you have a working request/response loop.

Adding streaming

For anything longer than a short answer, streaming makes a real UX difference. App Router route handlers support returning a ReadableStream, which pairs naturally with Claude's SSE streaming mode:

export async function POST(req: NextRequest) {
  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,
      messages,
      stream: true,
    }),
  });

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

On the client, read the stream with the ReadableStream reader API or a small SSE-parsing helper, and append each chunk to your UI state as it arrives.

Common setup mistakes

Simplifying the setup with SubToAPI

If you'd rather skip managing raw API keys, request signing, and usage tracking yourself, SubToAPI turns your existing Claude access into an HTTPS API with sub_live_... application keys, built-in streaming, tool use, and per-key usage metadata — all from one dashboard. The route handler above works the same way, just pointed at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY instead of x-api-key. Check the quickstart or the messages and streaming docs for the exact request shapes, and see /pricing for plan details. A free trial is available at /signup.

questions

Do I need a separate backend to use Claude in Next.js App Router? No. App Router's app/api/*/route.ts handlers are server-side by default and are sufficient as your backend — no separate Express or serverless project needed.

Can I call Claude directly from a Server Component instead of a route handler? Yes for static, non-interactive content generated at render time. For anything triggered by user input (forms, chat), use a route handler that a Client Component can call via fetch.

Why is my API key showing up in the browser bundle? You likely prefixed it with NEXT_PUBLIC_, which tells Next.js to inline it into client JavaScript. Remove that prefix and only read the key inside server-side route handlers.

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 →