Skip to content
bits
Ship an agent to the edge · Lesson 1 of 8

From script to endpoint

Tutor:

In Your first agent loop, the agent ran on your laptop with your API key in a .env file. That's fine for you. To let anyone else use it, it needs two things: a URL, and a place to run where the key never leaves the server.

That place is a Cloudflare Worker: a small TypeScript function that Cloudflare runs on its network, close to whoever calls it. A request comes in, your fetch handler runs, a response goes out. The free plan covers 100,000 requests a day (as of October 2026).

Here's the smallest useful one: a POST endpoint that forwards a question to Claude and returns the answer.

import Anthropic from "@anthropic-ai/sdk";
export default {
async fetch(request, env): Promise<Response> {
if (request.method !== "POST") {
return new Response("POST a JSON body: { question }", { status: 405 });
}
const { question } = await request.json<{ question?: unknown }>();
if (typeof question !== "string" || question.length > 2000) {
return new Response("question must be a string under 2,000 characters", { status: 400 });
}
const client = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY });
const res = await client.messages.create({
model: "claude-haiku-5-5",
max_tokens: 1024,
output_config: { effort: "low" }, // chat-sized answers
messages: [{ role: "user", content: question }],
});
const answer = res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
return Response.json({ answer, usage: res.usage });
},
} satisfies ExportedHandler<Env>;
TypeScriptUTF-8● lines 12–17: the Claude call
Tutor:

For local runs with npx wrangler dev, the key goes in a .dev.vars file next to the config:

# Local only. Add .dev.vars to .gitignore.
ANTHROPIC_API_KEY=sk-ant-…
PropertiesUTF-8
Tutor:

src/index.ts is the Worker. wrangler.jsonc tells Wrangler, Cloudflare's CLI, what to deploy; secrets.required makes a deploy fail loudly if the key is missing. The Env type comes from running npx wrangler types, so env.ANTHROPIC_API_KEY is typed without you writing an interface.

The handler checks its input before spending a token: a public URL gets called by things that aren't your app.

Tutor:

For the deployed Worker, the key goes in as an encrypted secret, not in the config file:

OUTPUT
wrangler secret put ANTHROPIC_API_KEY
# example output
✔ Enter a secret value: …
✨ Success! Uploaded the secret
Tutor:

wrangler secret put creates and deploys a new version straight away. Then npx wrangler deploy uploads your code and prints your workers.dev URL. As of October 2026 Cloudflare also has a new cf CLI in beta; this course sticks to Wrangler, which the Agents docs use.

quick check+20 neurons
Tutor:

Where should the Anthropic API key live for the deployed Worker?

    Type your answer or tap an option · Enter checks

    quick check+20 neurons
    Tutor:

    Why does the handler check question before calling Claude?

      Type your answer or tap an option · Enter checks