Claude API Next.js App Router Integration Guide
Integrating the Claude API into a Next.js App Router project means wiring up a server-side route handler that calls Anthropic's API (or a compatible gateway), then consuming that endpoint from client or server components. The App Router's conventions — route handlers in app/api/*/route.ts, server actions, and streaming responses via ReadableStream — map cleanly onto how LLM APIs work, but there are a few gotchas specific to Next.js: edge vs. node runtimes, environment variable scoping, and how you stream tokens back to the browser without blocking the render.
This guide walks through a working setup: a route handler that proxies requests to Claude, a streaming implementation that works with the App Router's response model, and a client component that renders tokens as they arrive. It also covers where things typically break — timeouts, runtime mismatches, and key exposure — so you don't have to debug them yourself.
Why the App Router Changes the Integration Pattern
If you're coming from the Pages Router or a plain Express backend, the main differences are:
- Route handlers replace API routes. Instead of
pages/api/chat.ts, you writeapp/api/chat/route.tsexportingPOST,GET, etc. - Streaming is native. You can return a
Responsebacked by aReadableStreamdirectly, no need for manualres.write()hacks. - Runtime matters. You choose
edgeornodejsper route viaexport const runtime. Streaming works on both, but the edge runtime has stricter limits (no raw TCP sockets, smaller memory). - Server Components can't call client-only hooks. If you want live token-by-token rendering, you need a client component consuming the stream — the server component just kicks off the request.
Setting Up the Route Handler
Create a route handler that holds your API key server-side and forwards the request. Never call the Claude API directly from a client component — the key would end up in the browser bundle.
// app/api/chat/route.ts
export const runtime = "nodejs"; // or "edge" if your provider supports it
export async function POST(req: Request) {
const { messages } = await req.json();
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-sonnet-4",
max_tokens: 1024,
stream: true,
messages,
}),
});
return new Response(upstream.body, {
headers: { "Content-Type": "text/event-stream" },
});
}
Store the key in .env.local as SUBTOAPI_KEY=sub_live_... and never prefix it with NEXT_PUBLIC_ — that prefix exposes it to the browser bundle, which defeats the point of a server-side proxy.
Streaming to the Client
The route handler above just passes the upstream stream through. On the client, use the Fetch API with a ReadableStream reader rather than EventSource, since EventSource only supports GET requests and you need POST to send the conversation payload.
"use client";
import { useState } from "react";
export function Chat() {
const [output, setOutput] = useState("");
async function send(prompt: string) {
setOutput("");
const res = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ messages: [{ role: "user", content: prompt }] }),
});
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>
<button onClick={() => send("Explain the App Router in two sentences")}>
Ask Claude
</button>
<p>{output}</p>
</div>
);
}
This renders tokens as they arrive instead of waiting for the full response, which matters a lot for perceived latency in chat UIs. For a deeper look at parsing SSE chunks correctly (including partial JSON frames), see /docs/streaming.
Using Server Actions Instead of a Route Handler
If you don't need streaming and just want a single request/response cycle — summarizing a form submission, classifying text, generating a short reply — a server action is simpler than a route handler:
// app/actions.ts
"use server";
export async function askClaude(prompt: string) {
const res = 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-sonnet-4",
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
}),
});
return res.json();
}
Call this directly from a form's action prop or from a client component via startTransition. No route handler, no manual fetch boilerplate — Next.js handles the serialization.
Why Go Through a Gateway Instead of Anthropic Directly
You can point the fetch calls above straight at Anthropic's API if you already have a direct API key. The reason to add a layer like SubToAPI in front is operational, not functional: it turns your existing Claude access into a standard HTTPS API with sub_live_... application keys, so you can issue a separate key per environment (dev, staging, production) or per team member without sharing your root credentials, and get usage metadata per key without building that tracking yourself. For a Next.js app with multiple contributors or multiple deployed environments, that separation avoids the common mistake of one shared key leaking into a client bundle or a public repo. Setup follows the same request shape shown above — check /docs/quickstart for the full flow and /docs/messages for the request/response schema.
Common Issues When Deploying
- Edge runtime timeouts. Some hosting platforms cap edge function duration tightly. If responses take longer than that, switch the route to
export const runtime = "nodejs". - Buffering by a CDN or proxy. If tokens arrive all at once instead of incrementally, something between your server and the browser is buffering the stream — check reverse proxy configuration, not your route handler code.
- Forgetting
await req.json()before reading headers. Route handlers in the App Router use the standardRequestobject, so body parsing is async and must happen before you can readmessages.
Questions
Can I call the Claude API directly from a Next.js client component? No — doing so exposes your API key in the browser bundle. Always proxy through a route handler or server action so the key stays server-side.
Should I use edge or nodejs runtime for streaming Claude responses? Either works for streaming, but nodejs is more forgiving with longer response times and fewer platform-specific limits. Use edge only if your host's edge runtime supports the duration you need.
Do I need a separate backend for Claude integration in Next.js? No. Route handlers and server actions in the App Router are sufficient — they run server-side within your Next.js deployment, so no separate backend service is required.