Claude API Cloudflare Workers Deployment Guide
Deploying a Claude API Integration on Cloudflare Workers
If you're trying to run Claude API calls from Cloudflare Workers, the short answer is: it works well, but you need to handle three things specifically — storing your API key as a secret (not an environment variable in your code), passing through streaming responses correctly, and staying within Workers' CPU time limits on the free tier.
This guide walks through a working deployment from scratch: project setup, secret management, a Worker that calls Claude's Messages API, streaming support, and the pitfalls that trip people up when they move from a Node.js server to Workers' edge runtime.
Why Cloudflare Workers for Claude API apps
Workers run on Cloudflare's edge, so requests to your API hit a server close to the user before forwarding to Claude. For a chat widget, a documentation assistant, or a lightweight API proxy, this cuts latency compared to a single-region origin server. Workers also have no cold-start penalty the way some serverless platforms do, and the free tier is generous enough for prototypes.
The trade-off: Workers don't give you a full Node.js environment. No native fs, limited npm compatibility, and a strict CPU time budget (10ms on the free plan, up to 50ms on paid plans, though wall-clock time for I/O like waiting on Claude's response doesn't count against that limit).
Prerequisites
- A Cloudflare account and the
wranglerCLI (npm install -g wrangler) - An Anthropic API key, or a SubToAPI key if you want a single HTTPS endpoint with built-in usage tracking across team members — get one at /signup
- Node.js installed locally for
wrangler dev
Step 1: Initialize the project
wrangler init claude-worker
cd claude-worker
Choose "Hello World" Worker and TypeScript or JavaScript — both work the same way for this guide.
Step 2: Store your API key as a secret
Never hardcode the key or put it in wrangler.toml under plain vars. Use Wrangler secrets, which are encrypted and only exposed to your Worker at runtime:
wrangler secret put ANTHROPIC_API_KEY
Paste your key when prompted. If you're using SubToAPI instead of calling Anthropic directly, store your sub_live_... key the same way:
wrangler secret put SUBTOAPI_KEY
Step 3: Write the Worker
A minimal Worker that proxies a chat request to Claude:
export default {
async fetch(request, env) {
if (request.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
const { messages } = await request.json();
const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages,
}),
});
return new Response(upstream.body, {
status: upstream.status,
headers: { "Content-Type": "application/json" },
});
},
};
This sends the request straight through and pipes the upstream body back to the client without buffering it in memory — important when you later switch to streaming. See /docs/messages for the full request/response schema.
Step 4: Add CORS headers
If your Worker is called from a browser-based frontend on a different origin, you'll need to handle preflight requests:
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
export default {
async fetch(request, env) {
if (request.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
// ... rest of the handler, adding corsHeaders to every Response
},
};
Lock Access-Control-Allow-Origin down to your actual domain in production.
Step 5: Support streaming responses
Streaming matters for anything chat-like — users expect tokens to appear incrementally rather than waiting for the full response. Workers support this natively since Response accepts a ReadableStream, and the upstream body from fetch is already one:
export default {
async fetch(request, env) {
const { messages } = await request.json();
const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages,
}),
});
return new Response(upstream.body, {
status: upstream.status,
headers: {
"Content-Type": "text/event-stream",
...corsHeaders,
},
});
},
};
No buffering, no reassembly — the Server-Sent Events stream flows from Claude through your Worker to the client as-is. Details on event types and chunk format are in /docs/streaming.
Step 6: Deploy
wrangler deploy
Wrangler prints a *.workers.dev URL. Point your frontend at it, or attach a custom domain via the Cloudflare dashboard's "Triggers" tab on your Worker.
Common pitfalls
- Treating env vars as secrets. Anything under
[vars]inwrangler.tomlis committed to your repo in plain text. API keys always go throughwrangler secret put. - CPU time vs wall-clock time confusion. Waiting on Claude's response doesn't burn CPU time, but any JSON parsing, token counting, or text transformation you do on the full response body does. Keep post-processing minimal, or do it client-side.
- Buffering streamed responses. If you read the stream into a string with something like
await upstream.text()before returning it, you lose the point of streaming and increase memory use. Pass theReadableStreamthrough directly. - Forgetting tool use passthrough. If your Worker supports Claude's tool calling, make sure you're forwarding the full
tool_useandtool_resultblocks unmodified — see /docs/tools for the expected shapes. - Rate limits per Worker instance, not per request. Cloudflare can spin up many isolates concurrently; if you're hitting Claude's or SubToAPI's rate limits under load, add a queue or batch requests rather than fanning out.
If you're running a team and want per-member usage visibility without building your own metering layer, SubToAPI's dashboard tracks requests and token usage per API key automatically — useful when several developers are hitting the same Worker from different environments. Plans start at €9/month; see /pricing for the full breakdown, or check /docs/quickstart to get a key working in a few minutes.
questions
Does Cloudflare Workers support Claude's streaming responses out of the box? Yes. Workers' Response object accepts a ReadableStream, and the body from a fetch call to Claude's streaming endpoint is already one, so you can pass it straight through without buffering.
Can I call the Anthropic API directly from a Worker without a backend server? Yes, Workers can call any HTTPS endpoint, including Claude's Messages API directly or through a proxy like SubToAPI. You don't need a traditional server — the Worker itself is the backend.
Why am I hitting CPU time limits even though my Worker just proxies requests? CPU time only counts active computation, not time waiting on fetch. If you're hitting limits, it's usually from parsing or transforming the full response body — switch to streaming the body through unmodified instead of buffering and reprocessing it.