Claude API Next.js Server Actions Integration
Why Server Actions are a good fit for Claude
Server Actions let you call Claude directly from a form submission or a client component event handler, without writing a separate /api/chat route. The function runs on the server, your API key never ships to the browser, and you get a typed, direct call path between your UI and the model. For most Claude-powered features in a Next.js app — a comment summarizer, a support widget, a content generator — this removes a layer of boilerplate that the Pages Router or a standalone Express server would require.
The short answer to "how do I integrate the Claude API with Next.js Server Actions": mark a function 'use server', call Claude's messages endpoint from inside it with fetch, and return the result (or stream it) to the client component that invoked the action. Below is the full pattern, including streaming, error handling, and how an API gateway like SubToAPI changes the setup slightly.
Basic setup: a non-streaming Server Action
Create a server-only file for your Claude calls:
// app/actions/claude.js
'use server'
export async function askClaude(prompt) {
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: [{ role: 'user', content: prompt }],
}),
})
if (!res.ok) {
throw new Error(`Claude request failed: ${res.status}`)
}
const data = await res.json()
return data.content[0].text
}
Call it from a client component wrapped in a form:
// app/components/AskForm.jsx
'use client'
import { useState } from 'react'
import { askClaude } from '../actions/claude'
export default function AskForm() {
const [answer, setAnswer] = useState('')
const [pending, setPending] = useState(false)
async function handleSubmit(formData) {
setPending(true)
const result = await askClaude(formData.get('prompt'))
setAnswer(result)
setPending(false)
}
return (
<form action={handleSubmit}>
<textarea name="prompt" required />
<button disabled={pending}>{pending ? 'Thinking…' : 'Ask'}</button>
<p>{answer}</p>
</form>
)
}
This works because Server Actions run exclusively on the server — the ANTHROPIC_API_KEY env var is never exposed to the client bundle. That's the main security win over calling the model directly from client-side JavaScript.
Streaming responses from a Server Action
Server Actions can't stream a raw SSE response the way an API route can, but you can return an async iterable or use a ReadableStream consumed on the client via a fetch to a route handler, or — more commonly for Server Actions specifically — use createStreamableValue-style patterns from the AI SDK, or fall back to a route handler for the actual token stream while the Server Action triggers it.
The pragmatic approach most teams use: keep the Server Action for form submission and validation, but do the actual Claude streaming through a Route Handler (app/api/chat/route.js) that the client calls with fetch and reads via ReadableStream. Server Actions and streaming don't compose cleanly yet in plain React/Next.js without a helper library, so don't force it — use the Server Action for mutations (saving the prompt, checking auth, rate limiting) and a Route Handler for the token stream itself.
If you're using the Vercel AI SDK, its streamText plus useChat hook handles this split for you, and it works whether you're calling Anthropic directly or through SubToAPI's endpoint, since both expose an Anthropic-compatible /v1/messages shape.
Error handling and retries
Server Actions throw errors that Next.js surfaces through error boundaries, but for a chat-style UI you usually want to catch the error inside the action and return a structured result instead:
'use server'
export async function askClaude(prompt) {
try {
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: [{ role: 'user', content: prompt }],
}),
})
if (res.status === 429) {
return { ok: false, error: 'rate_limited' }
}
if (!res.ok) {
return { ok: false, error: 'upstream_error' }
}
const data = await res.json()
return { ok: true, text: data.content[0].text }
} catch {
return { ok: false, error: 'network_error' }
}
}
This pattern — return a tagged result instead of throwing — keeps your client component's error UI simple and avoids triggering Next.js's generic error boundary for things that are really just "the model was rate-limited, try again."
Using SubToAPI instead of calling Anthropic directly
If your app already uses a Claude subscription through your team rather than a pay-per-token Anthropic API key, SubToAPI turns that access into a standard HTTPS API with sub_live_... keys, so the Server Action code above barely changes — swap the host and header:
'use server'
export async function askClaude(prompt) {
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-5',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }],
}),
})
const data = await res.json()
return data.content[0].text
}
This is useful when multiple developers on a team each have their own Claude access but you want one API key, one usage dashboard, and seat-based billing instead of juggling individual Anthropic keys across environments. Streaming, tool use, and usage metadata work the same way they do against Anthropic's API directly — see the quickstart, messages, streaming, and tools docs for the exact request shapes. Plans start at €9/seat on the Solo tier with a free trial at signup; full tier breakdown is on the pricing page.
Keeping the key server-side
Whichever host you call, the rule for Server Actions is the same: never read the Anthropic or SubToAPI key in a 'use client' file, and never pass it as a prop or embed it in a form field. Store it in .env.local (and your deployment platform's secret store), reference it only inside files marked 'use server', and double-check your bundle doesn't accidentally inline it by searching your build output for the key prefix before shipping.
questions
Can I stream Claude's response directly from a Server Action? Not cleanly with plain React today — Server Actions return a single resolved value or require a streaming helper. Most teams trigger the action for validation/logging and stream tokens through a separate Route Handler, or use the Vercel AI SDK, which handles this split automatically.
Do I need an API route at all if I'm using Server Actions? For simple request/response calls, no — a Server Action calling fetch against Claude's /v1/messages endpoint is enough. You only need a Route Handler when you want true token-by-token streaming to the browser.
Is it safe to call Claude from a Server Action without a backend server? Yes. Server Actions execute on Next.js's server runtime, so your API key stays server-side the same way it would in a traditional API route — it's just a different entry point into the same server environment.