Claude API Next.js Integration Guide
Integrating Claude into a Next.js app means calling the Anthropic Messages API from a server context (API route, route handler, or server action), never from the browser, and then rendering the response — usually streamed — into your UI. The core pattern is the same whether you're on the Pages Router or the App Router: keep your API key server-side, build a route that proxies the request, and stream tokens back to the client as they arrive.
This guide walks through both router styles, shows a working streaming example, and covers the production details people usually hit second: rate limits, timeouts, and key management across environments.
Where Claude calls belong in a Next.js app
Next.js gives you several places to put a Claude call. Pick based on how you need to use it:
- Route Handlers (
app/api/*/route.ts) — best default for chat endpoints, streaming responses, or anything called from client components. - Server Actions — good for form-style interactions (summarize this text, generate this description) where you don't need manual streaming control.
- getServerSideProps / API routes (Pages Router) — same idea, older syntax, still fully supported.
In all three cases, the API key lives in an environment variable on the server and is never shipped to the client bundle.
# .env.local
ANTHROPIC_API_KEY=sk-ant-xxxxx
Basic Route Handler (App Router)
// app/api/chat/route.js
export async function POST(req) {
const { messages } = await req.json();
const res = 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-sonnet-4-5',
max_tokens: 1024,
messages,
}),
});
const data = await res.json();
return Response.json(data);
}
Call it from a client component with a plain fetch to /api/chat. This works, but for anything conversational you'll want streaming — waiting for the full response feels slow once replies get longer than a sentence or two.
Streaming responses into the client
Claude supports server-sent events when you pass stream: true. Next.js Route Handlers can return a ReadableStream directly, which plays nicely with the browser's fetch streaming API or libraries like the Vercel AI SDK.
// app/api/chat/route.js
export async function POST(req) {
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-sonnet-4-5',
max_tokens: 1024,
stream: true,
messages,
}),
});
return new Response(upstream.body, {
headers: { 'content-type': 'text/event-stream' },
});
}
On the client, read the stream chunk by chunk and append content_block_delta events to your message state. If you're using the Vercel AI SDK, it has adapters that parse this format for you and expose a useChat hook that handles the UI state entirely.
Server Actions for one-shot calls
If you don't need token-by-token streaming — generating a product description, rewriting a paragraph, classifying input — a Server Action is simpler than a route:
// app/actions.js
'use server';
export async function generateSummary(text) {
const res = 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-sonnet-4-5',
max_tokens: 500,
messages: [{ role: 'user', content: `Summarize: ${text}` }],
}),
});
const data = await res.json();
return data.content[0].text;
}
Call it directly from a form's action prop with no client-side fetch code at all.
Handling timeouts and function duration
Next.js route handlers deployed on serverless platforms have execution time limits (often 10–60 seconds on default tiers, longer on paid plans or Edge runtime). Long Claude generations can hit this ceiling if you're waiting for the full non-streamed response. Two fixes:
- Switch to streaming so the connection stays active and returns partial output immediately.
- Set
runtime = 'edge'in your route file if your platform supports longer Edge execution for streamed responses.
export const runtime = 'edge';
Managing keys across environments
A common pain point: you want one Anthropic key for local dev, a separate one for staging, and tight usage visibility in production — but Anthropic's console doesn't give you per-environment metering or team-level spend breakdowns out of the box.
This is where a layer like SubToAPI helps if you're already on a Claude subscription. It turns your existing access into a standard HTTPS API with its own sub_live_... keys, so you can issue a separate key per environment or per team member, see usage per key in a dashboard, and swap keys without touching Anthropic's console. The request shape is unchanged — same JSON body, same streaming format — so the Route Handler code above works by pointing at https://api.subtoapi.app/v1/messages and swapping the header to Authorization: Bearer $SUBTOAPI_KEY. Check the quickstart and streaming docs for the exact request/response shapes.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
}'
Adding tool use in Next.js
If your app needs Claude to call functions — looking up data, running calculations, hitting internal APIs — define tools in the request body and handle the tool_use content block on the server before sending a follow-up message with the result. This fits naturally into a Route Handler loop: receive the response, check stop_reason, execute the tool, append the result, call again. See the tool use docs for the schema details, or messages docs for the full request reference.
questions
Do I need a backend API route, or can I call Claude directly from a Next.js client component? Always route through the server. Calling Claude directly from the browser exposes your API key in client-side JavaScript, which is a security risk and a violation of most API terms.
Should I use streaming or a single JSON response for a Next.js chat UI? Use streaming for anything conversational — it reduces perceived latency and avoids serverless timeout issues on longer generations. Non-streaming is fine for short, one-shot tasks like classification or short rewrites.
Can I use the Vercel AI SDK with Claude in Next.js? Yes, it has built-in adapters for Anthropic-format streaming responses and a useChat hook that manages message state, making it faster to wire up than hand-rolling the stream parser.