Cloudflare Integration Guide
What is an edge platform?
Code at the nearest PoP, behind one anycast IP.
"The edge" means your code executes in the data centre closest to each request instead of a fixed origin region. Cloudflare runs every service on every server in every PoP behind one anycast IP, so there is no region to choose — the network routes to the nearest node (hundreds of cities, 405+ Tbps, ~50 ms to 95% of users). Workers boot in ~0 ms via V8 isolates rather than containers, and reach storage through in-process bindings on `env` (D1, KV, R2, Durable Objects, Queues). The trade-offs to design around: a tight CPU budget (10 ms Free, 30 s default on Paid), KV is eventually consistent, and D1 / Durable Objects keep data in one location — pick it near your users (Cloudflare has PoPs in Nairobi and Mombasa), and when you would rather run near an existing Postgres than near the user, use Smart Placement plus Hyperdrive.
The five building blocks
Workers run the code; D1, KV and R2 hold the data. Tap a card to dig in.
Why R2 has zero egress fees
Egress is data leaving the provider out to the internet — every file your users download. Traditional clouds bill it per gigabyte on top of storage, so at scale the bandwidth bill dwarfs storage and quietly locks your data in (moving or serving it gets expensive — known as “data gravity”). Cloudflare charges $0 for egress because it already runs a global network with huge peering — bandwidth isn’t a metered resale cost for them, and dropping egress fees is a deliberate move to break that lock-in.
Same bytes, same users. On R2 you still pay for storage and operations — but moving the data out to the internet is $90/mo cheaper here, and the gap only widens with traffic. (S3 figure is the first-tier rate; it tiers down at scale — R2 stays $0.)
It’s exactly why this dashboard serves its tech thumbnails from R2 (thumbs.codeamanilabs.org) — shipping images to a data-conscious East-African audience costs nothing to egress.
██████╗██╗ ██████╗ ██╗ ██╗██████╗ ███████╗██╗ █████╗ ██████╗ ███████╗
██╔════╝██║ ██╔═══██╗██║ ██║██╔══██╗██╔════╝██║ ██╔══██╗██╔══██╗██╔════╝
██║ ██║ ██║ ██║██║ ██║██║ ██║█████╗ ██║ ███████║██████╔╝█████╗
██║ ██║ ██║ ██║██║ ██║██║ ██║██╔══╝ ██║ ██╔══██║██╔══██╗██╔══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║ ███████╗██║ ██║██║ ██║███████╗
╚═════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝Cloudflare Integration Guide
Focus: Building and deploying Workers (with static assets, D1, KV, R2, Durable Objects, Queues) using Wrangler, and driving the Cloudflare account from coding agents through the Cloudflare API MCP server. For private media in R2 (presigned URLs, access control) see the separate
cloudflare-r2/guide. For the 1.1.1.1 public DNS resolver (DNS over HTTPS, Families, Android Private DNS) seecloudflare-1-1-1-1/.
Overview
Cloudflare's developer platform runs your code in Workers — V8 isolates on Cloudflare's network — and hands it in-process bindings to storage: D1 (SQLite), KV (key-value), R2 (object storage, no egress fees), Durable Objects (stateful coordination), Queues, Hyperdrive (pooled Postgres/MySQL), Workers AI, and Vectorize. A Worker can also serve a site's static assets, which is how full-stack apps are deployed today; Pages still works but new framework guides target Workers.
Pinned versions (npm, verified 2026-10-17): wrangler 4.151.1 (needs Node.js
≥ 22), @cloudflare/workers-types 5.20261016.1, create-cloudflare 2.74.0,
vinext 1.2.1 (beta). @cloudflare/next-on-pages is deprecated (use vinext or
OpenNext), and @cloudflare/mcp-server-cloudflare is the legacy local MCP server.
Where Cloudflare fits at codeAmani: Vercel is the primary app host. Reach for
Cloudflare when you need R2 (the thumbs.codeamanilabs.org CDN), an edge API or webhook
receiver, Durable Objects / Queues, or a cheap global static site.
Official Documentation
Every docs page is available as markdown at
<page-url>index.md, and each product has anllms.txtindex (e.g. https://developers.cloudflare.com/workers/llms.txt).
MCP server (agents)
Cloudflare's API MCP server at https://mcp.cloudflare.com/mcp is, in Cloudflare's
words, "the only MCP server you need". It covers the whole Cloudflare API (2,500+
endpoints — DNS, Workers, R2, Zero Trust, and everything else) plus the developer docs,
through three tools:
| Tool | What it does |
|---|---|
search() | Find API endpoints in a typed representation of the OpenAPI spec |
execute() | Run model-written JavaScript against the Cloudflare API client in a sandboxed Dynamic Worker |
docs() | Search the Cloudflare developer docs |
This "Code Mode" design costs about 1,000 tokens of tool definitions, versus ~1.17M if every endpoint were its own tool.
# Claude Code — OAuth on first use; you choose which permissions the agent gets
claude mcp add --transport http cloudflare-api https://mcp.cloudflare.com/mcp
# Or install the Cloudflare Skills plugin (MCP servers + skills + slash commands)
# /plugin marketplace add cloudflare/skills
# Other agents (Codex, OpenCode, Cursor, Pi): npx skills add https://github.com/cloudflare/skillsCI / automation: create a scoped Cloudflare API token (user or account token) and send
it as Authorization: Bearer <token>. It comes from the CI secret store, never the repo.
Optional product servers
| Server | Endpoint |
|---|---|
| Documentation | https://docs.mcp.cloudflare.com/mcp |
| Container (sandbox dev environment) | https://containers.mcp.cloudflare.com/mcp |
| Browser Run (fetch, markdown, screenshots) | https://browser.mcp.cloudflare.com/mcp |
| Digital Experience Monitoring | https://dex.mcp.cloudflare.com/mcp |
| Cloudflare One CASB | https://casb.mcp.cloudflare.com/mcp |
| Agents SDK docs | https://agents.cloudflare.com/mcp |
Use Streamable HTTP at /mcp. Old /sse URLs are aliases for the same handler; the
deprecated HTTP+SSE transport is gone, so clients forced to SSE must switch.
The per-product Workers Bindings, Builds, Observability, Radar, AI Gateway, Logpush, and GraphQL servers that earlier versions of this guide listed are no longer in Cloudflare's catalog. An existing config pointing at them may still connect, but move to the API server — it covers the same operations through
execute().
Security: the agent acts with whatever permissions you grant at OAuth or in the token.
Grant the narrowest set (e.g. Workers Scripts Edit + R2 Edit for one account), keep
per-call approval on for execute(), and never give a token with DNS or Zero Trust write
access to an unattended job unless that job needs it.
Wrangler
Install and authenticate
npm install -D wrangler # per project (preferred); Wrangler 4 needs Node.js >= 22
npx wrangler login # interactive OAuth
npx wrangler whoami
# CI: export CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID from the secret storeKey commands
# New project (Worker, or full-stack app with --framework)
npm create cloudflare@latest my-worker
npm create cloudflare@latest -- my-app --framework=next
npx wrangler dev # local dev (bindings simulated locally)
npx wrangler types # generate Env types from wrangler.jsonc
npx wrangler deploy # deploy
npx wrangler deploy --dry-run --outdir bundled/ # check bundle size without deploying
npx wrangler versions upload # upload a version without routing traffic
npx wrangler versions deploy # gradual rollout between versions
npx wrangler rollback # roll back to the previous version
npx wrangler tail # live logs
# Secrets (the human types the value at the prompt)
npx wrangler secret put STRIPE_WEBHOOK_SECRET
npx wrangler secret bulk secrets.json # up to 100 at once
npx wrangler secret list # names only
# D1
npx wrangler d1 create app-db
npx wrangler d1 migrations create app-db add_users
npx wrangler d1 migrations apply app-db --local
npx wrangler d1 migrations apply app-db --remote
# KV — space-separated subcommands; --remote to hit production
npx wrangler kv namespace create CACHE
npx wrangler kv key put --binding=CACHE "greeting" "hello" --remote
# R2 — without --remote, object commands only touch local storage
npx wrangler r2 bucket create my-bucket
npx wrangler r2 object put my-bucket/path/file.webp --file ./file.webp --content-type image/webp --remote
# Queues
npx wrangler queues create jobsWorker quickstart
Cloudflare recommends wrangler.jsonc for new projects; some newer Wrangler features
only work with a JSON config.
// wrangler.jsonc
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "codeamani-api",
"main": "src/index.ts",
// Set to today's date when you start; bump deliberately after reading the flag changelog.
"compatibility_date": "2026-10-17",
"observability": { "enabled": true, "head_sampling_rate": 1 },
"d1_databases": [{ "binding": "DB", "database_name": "app-db" }],
"kv_namespaces": [{ "binding": "CACHE" }],
"secrets": { "required": ["STRIPE_WEBHOOK_SECRET"] }
}Leaving out database_id / id uses automatic provisioning: wrangler deploy creates
the D1 database and KV namespace (prefixed with the Worker name) on first deploy. It works
for KV, R2, D1, Queues and a few newer products. secrets.required makes deploy fail if a
secret is missing, and feeds wrangler types.
// src/index.ts — run `npx wrangler types` first; it writes worker-configuration.d.ts with Env
export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/users") {
const { results } = await env.DB
.prepare("SELECT id, email FROM users ORDER BY created_at DESC LIMIT ?")
.bind(10)
.all();
return Response.json(results);
}
if (url.pathname === "/health") return Response.json({ ok: true });
return new Response("Not Found", { status: 404 });
},
} satisfies ExportedHandler<Env>;Node.js compatibility is on by default for compatibility_date 2026-08-04 or later
(nodejs_compat and nodejs_compat_v2 are implied), so node:crypto, node:buffer and
npm packages that use them work with no flag. Older dates still need
"compatibility_flags": ["nodejs_compat"].
Bindings reference
A binding is an in-process handle on env — no network hop, no API token. Prefer
bindings over the REST API inside Workers.
| Resource | wrangler.jsonc key | Type on env |
|---|---|---|
| KV | kv_namespaces: [{ binding, id? }] | KVNamespace |
| R2 | r2_buckets: [{ binding, bucket_name? }] | R2Bucket |
| D1 | d1_databases: [{ binding, database_name, database_id? }] | D1Database |
| Durable Objects | durable_objects.bindings: [{ name, class_name }] + migrations | DurableObjectNamespace |
| Queues (producer) | queues.producers: [{ binding, queue }] | Queue<T> |
| Queues (consumer) | queues.consumers: [{ queue, max_batch_size, dead_letter_queue }] | queue() handler |
| Hyperdrive | hyperdrive: [{ binding, id }] | Hyperdrive |
| Static assets | assets: { directory, binding?, run_worker_first? } | Fetcher (if binding set) |
| Secrets Store | secrets_store_secrets: [...] | secret binding |
? = optional because Wrangler can auto-provision it.
{
"durable_objects": { "bindings": [{ "name": "ROOMS", "class_name": "Room" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }],
"queues": {
"producers": [{ "binding": "JOBS", "queue": "jobs" }],
"consumers": [{ "queue": "jobs", "max_batch_size": 10, "dead_letter_queue": "jobs-dlq" }]
},
"hyperdrive": [{ "binding": "PG", "id": "<hyperdrive-config-id>" }]
}- Durable Objects — strongly consistent per-object state and coordination (rate
limits, rooms, counters). New namespaces must use the SQLite backend
(
new_sqlite_classes); creating key-value-backed namespaces is no longer allowed. - Queues — move slow work off the request path; failed messages land in the
dead_letter_queueaftermax_retries. - Hyperdrive — pools and caches connections to an existing Postgres/MySQL (Supabase, Neon) so a Worker doesn't exhaust connections.
- KV is eventually consistent (changes can take up to ~60 s to appear everywhere). Use D1 or a Durable Object when you need read-your-writes.
Static assets and full-stack apps
A Worker serves files from assets.directory. By default assets are matched first and
the Worker runs only when no file matches — the reverse of Pages, which ran Functions first.
{
"name": "my-site",
"main": "src/worker.ts", // omit for a purely static site
"compatibility_date": "2026-10-17",
"assets": {
"directory": "./dist",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/*"] // or true for every request
}
}Static asset limits: 20,000 files per version on Free, 100,000 on Paid (Wrangler ≥ 4.34); 25 MiB per file.
Next.js on Workers
Cloudflare's recommended path is now vinext — a Vite plugin that reimplements the
Next.js API surface for Workers (App and Pages Router, RSC, Server Actions, ISR,
middleware.ts/proxy.ts). It is in beta, and targets Next.js 16.
npx vinext check # compatibility report for an existing app
npx vinext init # non-destructive; `next dev` keeps working
npm run dev:vinext && npm run build:vinext
npx @vinext/cloudflare deploy
# New app: npm create cloudflare@latest -- my-next-app --framework=nextServer code reads bindings with import { env } from "cloudflare:workers". Existing
OpenNext (@opennextjs/cloudflare) apps remain supported; @cloudflare/next-on-pages is
deprecated.
codeAmani default: Next.js apps stay on Vercel. Move one to Workers only with a reason (cost, R2/Durable Object locality) and after
vinext checkpasses.
Pages (existing projects)
Pages projects keep working: wrangler pages deploy dist/ --project-name my-site, with
file-based functions/ routes and _routes.json. If a route mysteriously skips your
Function, check _routes.json — an unmatched path is served as a static asset. To migrate a
Pages project to Workers, follow the migration guide linked above (assets.directory, and
wrangler pages functions build for a functions/ folder).
Secrets and environment variables
# Wrangler / CI auth (from the secret store; never committed)
CLOUDFLARE_API_TOKEN=... # scoped token: dash.cloudflare.com → My Profile → API Tokens
CLOUDFLARE_ACCOUNT_ID=... # identifier, not a secret- Runtime secrets →
wrangler secret put <NAME>(orsecret bulk); read asenv.<NAME>. Non-secret config →varsinwrangler.jsonc. - Local dev →
.dev.vars(or.env) next towrangler.jsonc; gitignore it. - Account-wide secrets shared across Workers → Secrets Store (open beta),
secrets_store_secretsbinding. - Env vars and secrets are limited to 5 KB each.
Webhook receiver on a Worker (Stripe)
// src/index.ts — Stripe signature check with Web Crypto
import Stripe from "stripe";
export default {
async fetch(request, env): Promise<Response> {
if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
const stripe = new Stripe(env.STRIPE_SECRET_KEY);
const body = await request.text();
let event: Stripe.Event;
try {
event = await stripe.webhooks.constructEventAsync(
body,
request.headers.get("stripe-signature") ?? "",
env.STRIPE_WEBHOOK_SECRET,
undefined,
Stripe.createSubtleCryptoProvider(),
);
} catch {
return new Response("bad signature", { status: 400 });
}
// Idempotency: D1 primary key on the event id turns a retry into a no-op.
const { meta } = await env.DB
.prepare("INSERT INTO stripe_events (id, type) VALUES (?, ?) ON CONFLICT (id) DO NOTHING")
.bind(event.id, event.type)
.run();
if (meta.changes === 0) return Response.json({ received: true, duplicate: true });
await env.JOBS.send({ eventId: event.id, type: event.type }); // process off the request path
return Response.json({ received: true });
},
} satisfies ExportedHandler<Env>;R2: buckets, tokens, and public serving
Bucket names are lowercase letters, numbers and hyphens.
npx wrangler r2 bucket create my-bucket
npx wrangler r2 bucket listS3-compatible credentials (for the AWS SDK, boto3, rclone; Wrangler doesn't need them):
Dashboard → R2 → Manage API Tokens → Account API token (survives a user leaving —
best for automation) → permission Object Read & Write (or Object Read only, Admin Read &
Write, Admin Read only) → Apply to specific buckets only. The secret is shown once.
Endpoint: https://<ACCOUNT_ID>.r2.cloudflarestorage.com. From any Cloudflare API token,
Access Key ID = the token's id and Secret Access Key = the SHA-256 of the token value.
Public serving: connect a custom domain (the zone must be on Cloudflare — this is how
thumbs.codeamanilabs.org works) or enable the r2.dev URL (rate-limited; for testing).
Both make every object world-readable. For private files, follow cloudflare-r2/.
Credentials for agent automation
| Credential | Create at | Scope | Automates |
|---|---|---|---|
| Account ID | dashboard URL / Overview | identifier | API + S3 endpoint |
| Zone ID | domain → Overview | identifier | DNS API calls for the zone |
| Scoped API token | My Profile → API Tokens (or Account API Tokens) | only the permissions needed | Wrangler in CI, API MCP in CI |
| R2 S3 token | R2 → Manage API Tokens | Object Read & Write, bucket-scoped | object uploads via S3 API |
| DNS token | API Tokens → Custom | Zone → DNS → Edit (+ Zone → Read) | DNS records, R2 custom domains |
OAuth (wrangler login / MCP) | browser | your user's permissions, as granted | local work |
| Global API Key | My Profile → API Tokens | everything (legacy) | avoid — local CLI only, never apps/CI/repos |
Rules learned the hard way:
- Prefer account tokens for unattended jobs; always scope R2 tokens to buckets.
- The API MCP server can change DNS if you grant DNS permissions — grant them only for DNS tasks. (The old Workers Bindings server couldn't; that's no longer the limit.)
wrangler r2 object putneeds--remote, or it silently writes to local storage.- Legacy KV REST routes are dead.
/accounts/{id}/workers/namespaces/*stopped working on 2026-10-15. Use/accounts/{id}/storage/kv/namespaces/*— same parameters and responses.
Agent automation
Hook: remind to deploy after Worker edits
Hooks receive the tool call as JSON on stdin (there is no $CLAUDE_FILE_PATH
variable). .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path // empty' | grep -qE '(src/|wrangler\\.jsonc)' && echo 'Worker changed: run npx wrangler types && npx wrangler deploy --dry-run' || true"
}
]
}
]
}
}GitHub Actions deploy
# .github/workflows/cloudflare.yml
name: Deploy Worker
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: "22" }
- run: npm ci
- name: D1 migrations
run: npx wrangler d1 migrations apply app-db --remote
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
- name: Deploy
uses: cloudflare/wrangler-action@v4
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}wrangler-action@v4 installs Wrangler 4 by default; pin a version with wranglerVersion.
Pin the action to a commit SHA for supply-chain hygiene (see supply-chain/).
Common use cases
| Use case | Approach |
|---|---|
| Edge API / webhook receiver | Worker + D1 for idempotency + Queue for slow work |
| Global cache | KV binding (eventually consistent) |
| Static or SPA site | Worker with assets.directory |
| Public image/asset CDN | R2 + custom domain |
| Private user files | R2 + presigned URLs (cloudflare-r2/) |
| Rate limiting, rooms, counters | Durable Object (SQLite) |
| Query Supabase/Neon from a Worker | Hyperdrive binding |
| DNS changes | DNS-scoped token or API MCP with DNS permission |
Troubleshooting
| Issue | Fix |
|---|---|
| Wrangler won't start / engine error | Wrangler 4 needs Node.js 22+ |
| Worker too large | Limit is 64 MiB uncompressed on both plans (no gzip limit). Check with wrangler deploy --dry-run --outdir bundled/; move data to KV/R2/D1 or split with service bindings |
| Exceeded CPU time (Error 1102) | Free = 10 ms; Paid default 30 s, raise limits.cpu_ms up to 5 min, or offload to Queues |
| Error 1027 on Free | 100,000 requests/day used up (resets 00:00 UTC) |
r2 object put "worked" but object missing | Add --remote |
| KV API calls 404 since mid-October | Legacy /workers/namespaces/ route — switch to /storage/kv/namespaces/ |
kv:namespace errors | Use spaces: wrangler kv namespace ... |
API route returns the SPA's index.html | Assets win by default — add the path to run_worker_first |
| Pages Function never runs | Path excluded by _routes.json |
| KV stale reads | Eventually consistent — use D1 or a Durable Object |
| New Durable Object deploy rejected | Use a new_sqlite_classes migration |
codeAmani notes
- Hosting split: Next.js apps on Vercel; Cloudflare for R2, edge APIs, webhook receivers, Durable Objects and static sites. Domains are on Porkbun — a zone must be on Cloudflare before R2 custom domains or Workers routes can use it.
- Secrets:
CLOUDFLARE_API_TOKENand R2 S3 keys live in the Hazina vault; runtime secrets go in viawrangler secret puttyped by the human. The Global API Key used by the/add-techthumbnail script stays in the local credentials file — never in CI, an app, or a commit. - Payments: Stripe webhooks on a Worker verify with
constructEventAsync+createSubtleCryptoProvider()and dedupe onevent.id. Kenya-targeted M-Pesa callbacks fit the same shape: validate the callback, dedupe onCheckoutRequestID, enqueue. - AI routing: Workers AI and AI Gateway are available, but Claude stays primary per the routing policy; call Anthropic from server code with the key in a secret.
- East Africa: Cloudflare has edge locations in Nairobi and Mombasa, so Workers and
cached R2 objects are served close to Kenyan users. Zero-egress R2 plus small, cacheable
assets is the cheapest way to serve 2G/3G audiences. D1 and Durable Objects store data in
one location — pick it deliberately (
wrangler d1 create --location <hint>or--jurisdiction; a Durable ObjectlocationHint), because a database far from Nairobi adds that round trip to every query.