Claude API Vercel Edge Function Example
Why Run Claude on Vercel Edge Functions
If you're building on Next.js or Vercel and want to call Claude without spinning up a traditional Node.js server, an Edge Function is the right tool. Edge Functions run close to the user on Vercel's global network, start in milliseconds, and are billed differently than serverless functions — which makes them a good fit for chat UIs, streaming completions, and low-latency API proxies.
The short answer to "how do I call the Claude API from a Vercel Edge Function": use the native fetch API (no SDK that depends on Node-only modules), set export const runtime = 'edge', read your API key from an environment variable, and stream the response back using the Web Streams API instead of buffering the full completion. The rest of this article walks through a working example, the edge runtime's specific constraints, and how to handle streaming and tool use correctly.
The Edge Runtime Constraints You Need to Know
Vercel Edge Functions run on a V8 isolate, not a full Node.js process. That means:
- No
fs, no raw TCP sockets, noBufferin some cases — anything that relies on Node-specific APIs will fail at build or runtime. - You must use
fetch,Request,Response, andReadableStream— all standard Web APIs. - Official SDKs that bundle Node-only dependencies may not work out of the box in the edge runtime. Calling the HTTP API directly with
fetchavoids this entirely and is the most portable approach. - Cold starts are near-instant, but execution time and memory are more constrained than a regular serverless function, so keep request/response handling lean.
This is why most working Claude-on-edge examples skip the SDK and talk to the API directly.
Basic Example: Calling Claude from a Vercel Edge Function
Here's a minimal route.ts in a Next.js App Router project that proxies a request to Claude and returns the response as JSON.
// app/api/chat/route.ts
export const runtime = 'edge';
export async function POST(req: Request) {
const { prompt } = 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: [{ role: 'user', content: prompt }],
}),
});
if (!response.ok) {
return new Response(await response.text(), { status: response.status });
}
const data = await response.json();
return Response.json(data);
}
This works because the whole function body only uses fetch, Request, and Response — all edge-compatible. No Node SDK, no filesystem, no incompatible imports.
If you'd rather not manage raw Anthropic auth, rate limits, and model routing yourself, a hosted API layer like SubToAPI wraps the same request shape behind a single sub_live_... key, which simplifies key rotation and usage tracking across environments. The call looks almost identical:
const response = 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,
messages: [{ role: 'user', content: prompt }],
}),
});
See the quickstart and messages reference for the full request schema.
Streaming Responses from the Edge
For chat interfaces, you almost always want to stream tokens back to the browser instead of waiting for the full completion. Edge Functions support this natively via ReadableStream, and Claude's API supports server-sent events when you pass stream: true.
export const runtime = 'edge';
export async function POST(req: Request) {
const { prompt } = 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-3-5-sonnet-20241022',
max_tokens: 1024,
stream: true,
messages: [{ role: 'user', content: prompt }],
}),
});
return new Response(upstream.body, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
}
Because the upstream response body is already a ReadableStream, you can pipe it straight through to the client without buffering — the Edge Function just forwards bytes as they arrive. On the frontend, read the stream with the EventSource-style pattern or a library that parses SSE chunks. Details on event formats are in the streaming guide.
Handling Tool Use in an Edge Function
Tool use (function calling) adds a round trip: Claude returns a tool_use block, your Edge Function executes the tool, and you send the result back as a tool_result message in a follow-up call. This fits naturally into the edge model since each step is a short, stateless fetch:
const toolResultResponse = 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,
messages: [
{ role: 'user', content: prompt },
{ role: 'assistant', content: toolUseBlock },
{ role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseBlock.id, content: toolOutput }] },
],
tools: [/* your tool definitions */],
}),
});
Keep tool execution itself edge-compatible too — if a tool calls an external API, that's a simple fetch; if it needs a database driver that requires Node, move that specific step to a regular serverless function and call it from the edge function. See the tools guide for schema details.
Environment Variables and Deployment
Set your API key in the Vercel dashboard under Settings → Environment Variables, scoped to Production, Preview, or Development as needed. Edge Functions read process.env.YOUR_KEY the same way serverless functions do — the restriction is on which runtime APIs you can use, not on environment variable access.
For local development, keep the key in .env.local and never commit it. If you're using SubToAPI, generate a key from the dashboard after signup and check pricing for Solo, Team, and Scale plans if you need shared seats across a team.
questions
Can I use the official Anthropic SDK in a Vercel Edge Function? Some SDK versions work fine, but any version bundling Node-only dependencies will fail to build on the edge runtime. Calling the REST API directly with fetch is the safest, most portable option and is what the examples above use.
Why does my Edge Function return no response when streaming? Usually because the response body was buffered (e.g., with await response.text()) before being returned. Pass the raw ReadableStream from the upstream fetch directly into your Response constructor instead.
Does Vercel's Edge Function timeout affect long Claude completions? Edge Functions have shorter execution limits than regular serverless functions. For long completions, stream the response so tokens arrive incrementally rather than waiting for the full generation to finish before responding.