Cloudflare Integration Guide

Technology: cloudflare · Category: hosting · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/cloudflare

Insight:

Cloudflare is the edge platform — Workers, D1, KV, Durable Objects, and R2 (which serves this dashboard's thumbnails). R2 has zero egress fees, making it the cheap choice for serving images/assets to a bandwidth-constrained African audience. Keep API tokens scoped and server-side.

 ██████╗██╗      ██████╗ ██╗   ██╗██████╗ ███████╗██╗      █████╗ ██████╗ ███████╗
██╔════╝██║     ██╔═══██╗██║   ██║██╔══██╗██╔════╝██║     ██╔══██╗██╔══██╗██╔════╝
██║     ██║     ██║   ██║██║   ██║██║  ██║█████╗  ██║     ███████║██████╔╝█████╗
██║     ██║     ██║   ██║██║   ██║██║  ██║██╔══╝  ██║     ██╔══██║██╔══██╗██╔══╝
╚██████╗███████╗╚██████╔╝╚██████╔╝██████╔╝██║     ███████╗██║  ██║██║  ██║███████╗
 ╚═════╝╚══════╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝

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) see cloudflare-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.

flowchart LR
  U["User request"] --> E["Cloudflare edge"]
  E --> A["Static assets<br/>served first"]
  E --> W["Worker<br/>fetch handler"]
  W --> D1["D1<br/>SQLite"]
  W --> KV["KV<br/>key-value cache"]
  W --> R2["R2<br/>object storage"]
  W --> DO["Durable Object<br/>stateful"]
  A --> RESP["Response"]
  W --> RESP

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

Resource URL
Workers https://developers.cloudflare.com/workers/
Wrangler configuration (bindings) https://developers.cloudflare.com/workers/wrangler/configuration/
Wrangler commands https://developers.cloudflare.com/workers/wrangler/commands/
Workers limits https://developers.cloudflare.com/workers/platform/limits/
Workers pricing https://developers.cloudflare.com/workers/platform/pricing/
Static assets https://developers.cloudflare.com/workers/static-assets/
Migrate from Pages to Workers https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/
Next.js on Workers (vinext) https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/
Compatibility flags https://developers.cloudflare.com/workers/configuration/compatibility-flags/
Cloudflare's MCP servers https://developers.cloudflare.com/agents/model-context-protocol/cloudflare/servers-for-cloudflare/
Agent setup (Claude Code) https://developers.cloudflare.com/agent-setup/claude-code/
D1 / R2 https://developers.cloudflare.com/d1/ · https://developers.cloudflare.com/r2/

Every docs page is available as markdown at <page-url>index.md, and each product has an llms.txt index (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/skills

CI / 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 store

Key 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 jobs

Worker 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>" }]
}

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=next

Server 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 check passes.

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

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 list

S3-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:


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

Official docs: