@realchendahuang: Many people use AI to write Cloudflare projects and fail, not because of syntax. The real problem is: AI often treats Workers as Node.js, uses Binding as process.env, forgets await, abuses global variables to store request state, doesn't know static asset requests are free, and calls its own R2 via REST API from a Worker. I've compiled these pitfalls into the Cloudflare Playbook. I also wrote about how to connect Codex / Claude Code with Cloudflare Skill, MCP, and Wrangler. It's suitable as a manual for AI writing Cloudflare projects.

X AI KOLs Timeline Tools

Summary

This Cloudflare playbook is designed for the AI coding era, organizing usage methods, common pitfalls, and AI coding workflows for each Cloudflare module, suitable as a reference guide for AI writing Cloudflare projects.

Many people use AI to write Cloudflare projects and fail, not because of syntax. The real problem is: AI often treats Workers as Node.js Uses Binding as process.env Forgets await Abuses global variables to store request state Doesn't know static asset requests are free Calls its own R2 via REST API from a Worker I've compiled these pitfalls into the Cloudflare Playbook. I also wrote about how to connect Codex / Claude Code with Cloudflare Skill, MCP, and Wrangler. It's suitable as a manual for AI writing Cloudflare projects.
Original Article
View Cached Full Text

Cached at: 06/22/26, 09:53 PM

Many people use AI to write Cloudflare projects, and they fail not because of syntax. The real problem is: AI often treats Workers as Node.js, uses Bindings like process.env, forgets await, misuses global variables for request state, doesn’t realize static asset requests are free, and calls its own R2 via REST API from within a Worker. I’ve compiled all these pitfalls into the Cloudflare Playbook. I also included how to connect Codex / Claude Code with Cloudflare Skill, MCP, and Wrangler. It works well as a manual for writing Cloudflare projects with AI.


realchendahuang/cloudflare-playbook

Source: https://github.com/realchendahuang/cloudflare-playbook

Cloudflare Playbook

Cloudflare Practical Handbook in the AI Programming Era — write code with AI, deploy globally with Cloudflare.

Online reading: cloudflare-playbook.chendahuang.top

Overview

flowchart TD
  A[Cloudflare Playbook] --> B[Site Basics: DNS / SSL / CDN / Rules]
  A --> C[Compute: Workers / Pages / DO / Workflows / Queues]
  A --> D[Data Storage: D1 / KV / R2 / Hyperdrive / Vectorize]
  A --> E[AI: Workers AI / AI Gateway / Agents SDK]
  A --> F[Media: Images / Stream / Realtime / Browser]
  A --> G[Security: Turnstile / Access / WAF / Rate Limiting]
  A --> H[Observability: Log Explorer / Observability / Analytics]
  A --> I[AI Programming Workflow: Skill / MCP / Wrangler]
  A --> J[Billing & Quotas: Free vs Paid Comparison]
  A --> K[Architecture Patterns: Common Combinations & Trade-offs]

Table of Contents

1. Cloudflare Modules

Cloudflare’s capabilities can be understood in seven categories: Site Basics, Compute, Data Storage, AI, Media, Security, and Observability. Each module explains when you’ll use it and where the pitfalls are.

Site Basics

DNS

Authoritative DNS service that maps domain names to websites, APIs, email, etc.

After purchasing a domain, you usually update NS (Name Server) to point to Cloudflare, letting it manage the domain’s resolution. Then A, AAAA, CNAME, MX, TXT records are configured here. Subdomains, email verification, CNAME flattening, and DNSSEC also belong to this layer. When starting a project, configure DNS correctly first; then Pages, Workers, and R2 custom domains will work.

SSL/TLS

HTTPS encryption between browser and Cloudflare, and between Cloudflare and origin server.

The little padlock icon for HTTPS is mainly managed here. Once you onboard to Cloudflare, edge certificates are usually issued and renewed automatically. If you have your own origin server, pay attention to the encryption mode: Full (strict) requires a valid certificate on the origin; Flexible only encrypts the browser-to-Cloudflare segment, often causing redirect loops and security misjudgments. For static sites and Workers projects, you generally don’t need to worry about certificate chains. Only with self-hosted origins should you dig deeper.

Cache / CDN

Global edge caching for static assets, pages, and some responses.

Cloudflare caches cacheable content at edge nodes, allowing users to fetch files from a nearby location without hitting the origin every time. Static assets, images, built JS/CSS are best cached. Logged-in personal data, real-time APIs, and permission-based responses should not be cached. For fine-grained control, use Cache Rules to configure paths, headers, TTL, and bypass rules.

Rules

Rule system for redirects, caching, headers, origins, and configuration overrides.

If you need to 301 old domains to new ones, add security headers to certain paths, control caching strategy, rewrite URLs, or route different paths to different origins, look at Rules first. It handles request policies at the edge. Only write a Worker when the logic requires reading/writing a database, calling external APIs, or making business-state decisions.

Compute

flowchart TD
  Q1{"What compute do you need?"}
  Q1 -->|"Short requests: API / Webhook / BFF"| W["Workers"]
  Q1 -->|"Frontend + API integration"| WSA["Workers Static Assets"]
  Q1 -->|"Pure static site / Docs / Blog"| P["Pages"]
  Q1 -->|"State coordination / WebSocket"| DO["Durable Objects"]
  Q1 -->|"Multi-step flow / may fail and wait"| WF["Workflows"]
  Q1 -->|"Async / Buffering / Batch processing"| QU["Queues"]
  Q1 -->|"System deps / Long processes / Native binaries"| CT["Containers"]
  Q1 -->|"Scheduled triggers"| CR["Cron Triggers"]

Workers

Cloudflare’s serverless runtime for running JS/TS, Wasm, partial Python, and other backend logic.

This is the most common compute layer for AI programming. AI-generated Hono APIs, auth endpoints, webhooks, BFFs, MCP servers, and lightweight AI orchestration can all go into Workers. It’s suited for short requests and high-concurrency edge logic. Do not force image processing, large file transcoding, long-running tasks, or native system dependencies into ordinary Workers; consider Workflows, Queues, R2, Containers, or external services instead.

Workers Static Assets

Static asset hosting within a Worker project, deploying frontend files and Worker code as a single unit.

When AI generates Vite, React, Vue, Svelte, static documentation sites, or frontend projects with APIs, this works smoothly: HTML/CSS/JS/images are hosted as static assets, while dynamic logic like /api goes through the Worker. By default, requests hitting static files do not execute the Worker; only when a static file is not found does the Worker handle the request. Use this when the frontend and backend are tightly coupled and you want to manage routes and APIs under one Worker configuration, instead of splitting into two services.

Pages

A deployment platform for frontend projects, emphasizing Git integration, preview deployments, and static site publishing.

Connect GitHub/GitLab, push, and build/deploy — suitable for websites, blogs, documentation sites, landing pages, and prototypes. Pages Functions are essentially Workers under the hood. If you need a “frontend + API + multiple bindings” integrated project, Workers Static Assets is now recommended. For existing Pages projects relying on preview deployments and Git workflows, Pages works fine.

Durable Objects

Stateful objects for strong-consistency coordination, session state, and WebSocket scenarios.

Workers themselves are stateless; each request may land on a different instance. But chat rooms, collaborative whiteboards, online game rooms, counters, and Agent sessions need a “single source of truth”. Each Durable Object instance can represent a room, user, document, or Agent, with private persistent storage and WebSocket handling. It is not a general-purpose database for all business tables; it’s more like the “state and coordination center” for a specific entity.

Workflows

Persistent multi-step tasks for flows that can fail, wait, and retry.

AI-generated business logic often can’t finish in one request: first call an API, then write to a database, then send an email, then wait for human confirmation, and finally publish results. Workflows break the process into durable steps, automatically preserving state, supporting sleep, waiting for external events, and retrying on failure. Suitable for order processing, data pipelines, user lifecycle emails, and AI review flows. Ordinary synchronous APIs don’t need it.

Queues

Async message queues for guaranteed delivery, load buffering, batch processing, and retries.

Some things shouldn’t make users wait: sending emails, processing file uploads, writing audit logs, batch data syncs, triggering background generation. Put messages into Queues, let consumer Workers process them slowly, with batching, delays, retries, and dead-letter queues. Don’t use queues for endpoints that need immediate results; queues are for “I’ll take it and process it later” tasks.

Containers

Run containers on Cloudflare for languages, libraries, and long-running processes that Workers can’t handle.

If an AI-generated project depends on system libraries, long-running processes, traditional HTTP services, or native binaries — where the Workers runtime is unsuitable — Containers are the more natural choice. They complement Workers: a Worker can handle edge entry and routing, while the container handles the heavy backend. The trade-off is higher startup time, resource usage, and cost compared to ordinary Workers. Don’t containerize lightweight APIs from the start.

Cron Triggers

Schedule Workers on a cron expression for periodic tasks.

Sync data every hour, clean up D1 daily, refresh cache on a schedule, check third-party APIs periodically — use Cron Triggers. It only “fires a Worker at the given time”. If the triggered process involves many steps, waiting for human approval, or restoring context after failure, move the actual flow into Workflows.

Data Storage

flowchart TD
  Q1{"What type of data to store?"}
  Q1 -->|"Structured relational: users/orders/posts"| Q2{"Where is the database?"}
  Q2 -->|"On Cloudflare"| D1["D1 (SQLite compatible)"]
  Q2 -->|"Existing external PG/MySQL"| HD["Hyperdrive (connection pool + cache)"]
  Q1 -->|"Key-value / config / cache"| Q3{"Need immediate read after write?"}
  Q3 -->|"No / read-heavy"| KV["KV (global edge read fast)"]
  Q3 -->|"Strong consistency / high write"| DO["Durable Objects (single-entity atomic ops)"]
  Q1 -->|"Files / images / videos"| R2["R2 (S3-compatible object storage)"]
  Q1 -->|"Vectors / embeddings"| VZ["Vectorize (similarity search)"]
  Q1 -->|"Single entity state: room/session/counter"| DO2["Durable Objects Storage"]
  Q1 -->|"Event stream / log pipeline"| PL["Pipelines"]

D1

Cloudflare’s serverless SQL database with SQLite-like syntax.

When building apps with AI, structured data like users, orders, posts, and config can go into D1. It integrates naturally with Workers and Pages, and works with Drizzle ORM or raw SQL. Note: D1 is better suited for mid-to-small applications and edge relational data; it’s not a full Postgres replacement. Index your queries; don’t let a SELECT scan the entire table. For high-concurrency writes, complex transactions, or Postgres/MySQL features, use Hyperdrive with an external database.

KV

Globally distributed key-value store for read-heavy, low-latency data.

Config, short URL mappings, feature flags, cached results, small JSON for edge reads — all good for KV. The key is “global reads are fast”, not “consistent everywhere immediately after write”. Don’t put inventory, balances, flash sale slots, or real-time counters in KV; use D1 or Durable Objects for strong consistency.

R2

S3-compatible object storage for files, images, videos, attachments, backups, and datasets.

In AI programming, as soon as you encounter user uploads, image hosting, file exports, or backup files, think of R2. It’s S3 API compatible, so many existing SDKs and tools can connect directly. R2 is for objects, not tables; keep metadata, permissions, and business relationships in D1, and the file body in R2. For image transformations or video playback, pair with Images, Stream, or a Worker.

Hyperdrive

Edge connection pool and query acceleration layer for external Postgres/MySQL databases.

If your database is already on Supabase, Neon, RDS, or self-hosted Postgres/MySQL, you don’t want to migrate — but Worker connections are slow and risk connection exhaustion. Use Hyperdrive. It pools connections at the Cloudflare edge and can cache query results, reducing cross‑region database round trips. It’s not a new database; it’s middleware to help Workers connect to your existing database better.

Vectorize

Cloudflare’s vector database for storing embeddings and performing similarity search.

Used for RAG, semantic search, and similar recommendations. Chunk documents, convert to embeddings, store in Vectorize. When a user asks a question, retrieve the most similar vectors and feed the relevant text to an LLM. Vectorize stores vectors and metadata, not the original files; raw content can go to R2 or D1. Both Free and Paid plans have quotas; check the latest pricing.

DO Storage

Durable Objects’ built-in persistent storage, tied to a specific object instance.

Each Durable Object can have its own storage to hold its state, such as room members, collaboration document snapshots, Agent sessions, connection states, counters. Its value lies in “single-entity strong consistency + local state”, not as a D1 replacement for global reporting or storing large files.

Secrets Store

Centralized management of secrets and sensitive configuration.

API keys, webhook secrets, database passwords, third-party service tokens should not be in code or scattered across project configs. Secrets Store centralises these sensitive values for use by Workers and other services. Simple projects can use Worker secrets; for team collaboration, shared secrets across services, or audit/rotation needs, look at Secrets Store.

Pipelines

Data pipelines that continuously ingest event streams and logs into target storage.

When you generate continuous data like application events, behavior logs, or analytics events that need reliable writing to R2 for later analysis, check Pipelines. It’s data infrastructure, not a regular business database. Small projects may not need it at first; introduce it when you actually need logs, events, or a data lake.

AI

flowchart TD
  Q1{"What AI needs?"}
  Q1 -->|"Call LLM / embedding / classification"| WAI["Workers AI"]
  Q1 -->|"Unified management of multiple model providers"| AIG["AI Gateway"]
  Q1 -->|"RAG / semantic search"| Q2{"Self‑built or managed?"}
  Q2 -->|"Self‑built, full control"| VZ["Vectorize + Workers AI"]
  Q2 -->|"Fast integration, less hassle"| AIS["AI Search"]
  Q1 -->|"Stateful Agent / multi‑turn conversation"| SDK["Agents SDK"]

Workers AI

Cloudflare’s serverless AI inference platform.

From Workers, Pages, or REST API, call Cloudflare‑hosted models for LLM, embedding, text classification, speech-to-text, image understanding, and more. Benefits: simple deployment and authentication, smooth combination with Workers, Vectorize, and AI Gateway. Note that the model list and capabilities change; don’t assume all OpenAI/Anthropic features are available here. For complex reasoning, advanced multimodal capabilities, or stronger models, you may still need external models.

AI Gateway

Unified gateway for AI APIs, handling observability, caching, rate limiting, and cost control.

If you simultaneously use OpenAI, Anthropic, Workers AI, Groq, Mistral, etc., don’t scatter API calls all over your code — connect them through AI Gateway. It logs requests, shows latency and errors, caches responses, rate‑limits, retries, and fallbacks. It also helps manage costs. For AI applications, this layer is very valuable: it’s not the model itself, but the console and fuse for model calls.

Vectorize

Vector database — see Data Storage.

The retrieval layer for AI Q&A systems. Store raw content in R2 or D1, embeddings in Vectorize. When querying, retrieve first, then feed to the model for answering.

AI Search

Cloudflare’s managed AI search capability.

If you want to quickly add semantic search and Q&A to a website, docs, or knowledge base, look at AI Search. It’s less hassle than manually combining Workers AI, Vectorize, and a crawler, but flexibility is constrained by the product’s boundaries. If you need full control over chunking, indexing, recall, and answer logic, build your own with Workers AI + Vectorize.

Agents SDK

Framework for building stateful AI Agents, built on Durable Objects.

For multi‑turn conversations, tool calling, Agent memory, real‑time WebSocket, and scheduled tasks, the Agents SDK is more comfortable than hand‑writing state management. Each Agent can have its own state and storage, suitable for customer assistants, personal assistants, automation bots, and collaborative AI tools. If you only need a single LLM call, you don’t need the Agents SDK.

Media

flowchart TD
  Q1{"What media needs?"}
  Q1 -->|"Image processing / variants / optimization"| IMG["Images"]
  Q1 -->|"Video playback / transcoding / delivery"| STM["Stream"]
  Q1 -->|"Real‑time audio/video / meetings / live"| RT["Realtime"]
  Q1 -->|"Screenshots / PDF / headless browser"| BR["Browser Rendering"]

Images

Image hosting, optimization, variants, and edge transformation service.

If your project has user avatars, product images, cover photos, or content images, Images can handle uploads, storage, compression, cropping, format conversion, and on‑demand sizing. R2 is more like a general file bucket for raw objects; Images is an image delivery pipeline for page‑facing display. If you only store a few static images, static assets or R2 suffice. For many images, multiple sizes, and automatic optimization, look at Images.

Stream

Video storage, encoding, playback, and delivery service.

After uploading a video, Stream handles transcoding, adaptive bitrate, hosted player, and global delivery. Suitable for courses, product demos, UGC videos, and member content. It solves “reliable video playback”, not just storing an mp4 file. If you only need to let users download raw video, R2 is more direct. For in‑page playback, transcoding, multiple resolutions, and viewing experience, use Stream.

Realtime

Real‑time audio/video and low‑latency communication capabilities.

This group corresponds to Dashboard’s Realtime, including RealtimeKit, TURN server, serverless SFU, MoQ relay, etc. Used for multi‑party meetings, voice rooms, live streaming, and real‑time interaction. For basic WebSocket collaboration, start with Workers + Durable Objects. Only when you genuinely need audio/video channels, NAT traversal, SFU relaying, and low‑latency media transport should you dive into Realtime.

Browser Rendering

Call a headless browser from Workers for rendering, screenshots, and automation.

When you need to screenshot a webpage, generate a PDF, run page rendering checks, or fetch the final DOM of an accessible page, use Browser Rendering. It’s for tasks that require a real browser environment — not for ordinary HTML string concatenation, and definitely not for bypassing logins, paywalls, or site restrictions. Content that can be generated server‑side with templates does not need browser rendering.

Security

flowchart TD
  Q1{"What security needs?"}
  Q1 -->|"Bot prevention / captcha alternative"| TS["Turnstile"]
  Q1 -->|"Internal tool authentication"| ACC["Access"]
  Q1 -->|"SQL injection / XSS prevention"| WAF["WAF"]
  Q1 -->|"Rate limiting"| RL["Rate Limiting"]
  Q1 -->|"DDoS protection"| DDoS["DDoS (on by default)"]
  Q1 -->|"API schema validation / mTLS"| APS["API Shield"]

Turnstile

Cloudflare’s captcha replacement — determines if a request comes from a real user.

Login, registration, comments, forms, trial sign‑ups can all use Turnstile. The idea is to avoid forcing users to select images; instead, assess risk in the background and only interact with the user when necessary. Integrate by placing the widget on the frontend and validating the token on the backend. Putting the widget on the frontend without backend validation means it’s not effective.

Access

Application access control in Zero Trust — add authentication to internal tools and backends.

If you build an admin panel, internal dashboard, or temporary ops tool and don’t want to write your own login system, use Access. It checks identity and enforces policies before the request reaches the origin or Worker, supporting identity providers like Google, GitHub, SAML, and OIDC. For AI‑built internal tools, this is the easiest “keep them out at the door” solution.

WAF

Web Application Firewall — intercepts common attacks before they reach your application.

WAF can use managed rules, custom rules, and rate limiting to handle SQL injection, XSS, malicious scanning, abnormal paths, and known exploit patterns. AI‑generated code may have basic security issues; WAF provides edge‑level backup, but it does not replace code fixes: authentication, permission checks, and parameter validation must still be done properly in the application.

Rate Limiting

Limit request frequency by path, IP, header, or request characteristics.

Login endpoints, SMS verification, public APIs, AI call entry points, upload endpoints — all should consider rate limiting. It prevents malicious hitting, crawlers consuming quotas, and a single IP overwhelming Workers. Rate limiting is not a permission system; it solves “too many requests”, not “whether this person has permission”.

DDoS

Cloudflare network‑ and application‑layer DDoS protection.

Cloudflare automatically absorbs and mitigates large‑scale attack traffic at the edge network, with corresponding detection and rules at the HTTP layer. Most small projects don’t need special configuration. When actually attacked, key points: confirm the domain is proxied through Cloudflare, the origin IP isn’t exposed, and cache/WAF policies aren’t incorrectly blocking legitimate users.

API Shield

A set of security capabilities for APIs, including schema validation, mTLS, discovery, and abuse detection.

For formal public APIs, mobile APIs, or partner APIs, use API Shield for OpenAPI schema validation, client certificates, API discovery, and risk analysis. Requests that don’t match the schema can be blocked at the edge, reducing abnormal traffic hitting Workers or origins. This is more for formal API governance; early‑stage small projects may not need it. Its value increases when the interface is stable and callers grow.

Observability

flowchart TD
  Q1{"What to observe?"}
  Q1 -->|"Requests have issues, check logs"| LE["Log Explorer"]
  Q1 -->|"Verify config is working correctly"| TR["Trace"]
  Q1 -->|"Worker metrics and error rate"| OBS["Observability"]
  Q1 -->|"Push logs to external system"| LP["Logpush"]
  Q1 -->|"Site traffic and frontend performance"| WA["Web Analytics"]
  Q1 -->|"Custom business event analysis"| AE["Analytics Engine"]

Log Explorer

Log search tool in the Cloudflare Dashboard.

When a live request fails, look here first. Log Explorer can search by time, path, status code, Ray ID, service type, etc., to determine if the error is at the Cloudflare edge, Worker code, caching rules, WAF, or the origin. It’s for ad‑hoc debugging; for long‑term retention and external analysis, use Logpush.

Trace

Simulate the processing path of a request through Cloudflare configuration.

If you want to know what rules a URL hits, whether it’s cached, whether it triggers a Worker, or if security rules affect it, use Trace. It’s for verifying why a configuration behaves as it does, not full application APM. When you encounter “why didn’t this path redirect/cache/forward as expected”, Trace is more reliable than manually scanning rules.

Logpush

Continuously push Cloudflare logs to external destinations.

For long‑term log retention, SIEM integration, or sending logs to R2/S3/BigQuery/Splunk, use Logpush. It solves “logs need to leave Cloudflare and enter my data system”. Small projects don’t need to set this up initially; add it when you need compliance audits, long‑term trends, or cross‑system debugging.

Web Analytics

Privacy‑friendly site traffic and frontend performance analytics.

See page views, sources, countries, devices, Web Vitals, and frontend performance. It doesn’t rely on traditional third‑party ad‑tracking models and can be added via JS snippet even to sites not proxied by Cloudflare. Suitable for websites, docs, blogs, and product pages. For complex growth analysis, consider dedicated analytics tools.

Observability

Entry point for monitoring Workers and Pages runtime.

After an API goes live, check request volume, error rate, latency, exception logs, and deployment version performance here. Workers Logs, Invocation Logs, metrics, and traces all fall under this line. It answers “how is the code running?”; Log Explorer focuses more on “what happened at the request and edge layer”.

Analytics Engine

Custom metrics and event analysis engine within Workers.

If you want to write business events from Workers — button clicks, API latency, model call cost, user behavior — and then query them with SQL, use Analytics Engine. It’s for high‑cardinality event analysis, not a transactional database, and not for storing records that need per‑row strong consistency.


2. AI Programming Workflow

The most common reason AI-generated Cloudflare code fails is not syntax — it’s that the AI simply doesn’t know what Cloudflare has and where the boundaries are. The solution is simple: first equip the AI with Cloudflare’s “manual” and “toolbox”, so it can check official docs, understand bindings, and then proceed to coding and deployment.

Three‑Minute Setup

With Codex (OpenAI official client):

cd your-cloudflare-project
codex

Inside Codex, type /plugins, search for Cloudflare, press Enter to install. Configuration is done. This automatically installs Cloudflare’s Skill, MCP, and integrations — no manual config needed.

With Claude Code (Anthropic official client):

cd your-cloudflare-project
claude

Inside Claude Code, enter these two lines:

/plugin marketplace add cloudflare/skills
/plugin install cloudflare@cloudflare

Configuration done. Same effect as Codex.

What Each Thing Does

Skill = Manual
Helps the AI understand Cloudflare development. It covers Workers, Pages, R2, D1, KV, Queues, Durable Objects, Agents SDK, Wrangler, Email, etc. Once installed, the AI won’t treat your code as a regular Node.js project.

MCP = Connector
Lets the AI connect to your Cloudflare account and official docs. After installing the plugin, these are automatically registered (no manual addition needed):

  • Docs MCP: Enables AI to query official docs (keep it on by default)
  • Cloudflare API MCP: Lets AI operate your account (turn on for deployment/config changes)
  • Observability MCP: Lets AI view live logs (turn on when debugging)
  • Workers Builds MCP: Lets AI view build records
  • Browser Run MCP: Lets AI open a browser for testing

Wrangler = The actual CLI tool
Skills and MCP help the AI understand; to actually run and deploy on your machine, you need Wrangler. Install it in your project:

npm i -D wrangler@latest

These three commands are used most often:

npx wrangler dev       # Run locally
npx wrangler deploy    # Deploy to production
npx wrangler tail      # View live logs

Universal Approach

If you don’t want plugins, or you’re not using Codex / Claude Code (e.g., OpenCode, Pi, or other agents), you can install the official Skill package with one command:

npx skills add https://github.com/cloudflare/skills

This repository is maintained by Cloudflare and supports major agents like Claude Code, OpenCode, OpenAI Codex, and Pi.

Starting a New Project from Scratch

If you don’t even have a project yet, create one first:

npm create cloudflare@latest -- my-worker

Follow the prompts. After creation, install Wrangler and the plugins, then start having the AI write code.

What to Feed AI When Production Issues Arise

The AI can open Observability MCP to check logs and Browser Run MCP to view the Dashboard, but it doesn’t know what you’re seeing. Before asking it to debug production issues, provide these details:

  • Full URL of the issue
  • Time and timezone of occurrence
  • HTTP status code (e.g., 522, 1101)
  • The cf-ray or Ray ID from response headers — this is Cloudflare’s unique identifier for the request; the AI can use it to pinpoint the entire request chain in logs
  • Whether it only happens in certain regions, ISPs, browsers, or login states
  • The last deployment commit and Cloudflare deployment/version
  • Whether the request hit cache, WAF, Rate Limiting, Access, or a Worker

Quickly fetch response headers locally:

curl -I https://example.com/path

If you don’t know which layer an error code belongs to, check the error code index table at the beginning of Section 5. When AI sees 522, it often immediately goes to fix Worker code — but 522 is actually an origin issue. Feeding context and telling the AI which layer the error belongs to saves a lot of detours.

One‑Sentence Summary

Install plugins first → Help AI understand Cloudflare
Add Wrangler → Enable AI to actually execute
Keep Docs MCP on by default → Let AI query documentation
Only turn on API MCP when touching the account → Let AI deploy and modify config

Common Architecture Patterns

Here are the most common architecture combinations on Cloudflare, each with applicable scenarios and trade‑offs.

Pattern 1: Worker + D1 + R2 (Full‑Stack Application)

flowchart LR
  Client --> Worker
  Worker --> D1["D1: Metadata/Users/Orders"]
  Worker --> R2["R2: Files/Images/Attachments"]
  Worker --> KV["KV: Config/Cache"]

Applicable scenarios: SaaS prototypes, content management, API services. D1 stores structured data and business relationships, R2 stores file bodies, KV caches high‑frequency read configs. This is the most natural combination for AI‑generated full‑stack projects.

Trade‑off: D1 is not Postgres. For complex transactions and high‑concurrency writes, consider Hyperdrive with an external database.

Pattern 2: Workers Static Assets + Worker (Frontend + Backend Integrated)

flowchart LR
  Client -->|"Static asset requests"| SA["Static Assets (HTML/CSS/JS/Images: free, unlimited)"]
  Client -->|"/api/* dynamic requests"| W["Worker (API/Auth/Business Logic)"]
  W --> D1
  W --> R2

Applicable scenarios: React/Vue/Svelte frontend + API backend. Static asset requests are free and don’t count against Worker quotas; only dynamic requests consume Worker allowance.

Trade‑off: Frontend and backend are tightly bound in the same Worker project, good for small teams and fast iteration; larger teams might need separate services.

Pattern 3: Worker + Durable Objects + WebSocket (Real‑time Collaboration)

flowchart LR
  C1["Client A"] -->|WebSocket| DO["Durable Object (Room/Session State)"]
  C2["Client B"] -->|WebSocket| DO
  C3["Client C"] -->|WebSocket| DO
  DO --> SQLite["DO SQLite Storage"]

Applicable scenarios: Chat rooms, collaborative editing, online games, real‑time boards. Durable Objects provide per‑instance strong consistency and WebSocket support; Hibernation mode can drastically reduce long‑connection costs.

Trade‑off: About 500–1000 req/s per DO, so high concurrency requires splitting by entity. Not suitable as a general‑purpose database.

Pattern 4: Worker + Queues + Workflows (Async Processing)

flowchart LR
  API["Worker API"] -->|"Enqueue message"| Q["Queues (Buffer/Load Leveling)"]
  Q --> Consumer["Consumer Worker"]
  Consumer -->|"Start"| WF["Workflows (Multi‑step, Persistent)"]
  WF --> D1
  WF --> Email["Email Sending"]

Applicable scenarios: Order processing, data pipelines, AI review flows, user lifecycle emails. Queues act as entry buffer and load leveler; Workflows handle multi‑step processes where a failed step only retries that step.

Trade‑off: Higher architectural complexity; simple synchronous APIs don’t need this mechanism.

Pattern 5: Worker + AI Gateway + External Models (AI Application)

flowchart LR
  Client --> Worker
  Worker --> AIG["AI Gateway (Observability/Cache/Rate Limit)"]
  AIG --> OA["OpenAI"]
  AIG --> AN["Anthropic"]
  AIG --> WAI["Workers AI"]
  Worker --> VZ["Vectorize (RAG retrieval)"]
  VZ --> R2["R2 (raw content storage)"]

Applicable scenarios: AI chat, RAG Q&A, multi‑model routing. AI Gateway manages calls to multiple model providers, caching, and cost control; Vectorize handles semantic retrieval; R2 stores original documents.

Trade‑off: Workers AI model capabilities are limited; complex reasoning and multimodal scenarios still require external models.

Common AI Programming Pitfalls on Cloudflare

When AI generates Cloudflare code, the most frequent mistakes are not syntax errors but a lack of understanding of Cloudflare’s runtime constraints. Here are the high‑frequency pitfalls and the correct approaches:

1. Writing Workers with Node.js mentality
AI often generates require('fs'), express(), http.createServer() — Node.js code. Workers are not Node.js; they have no filesystem or native HTTP server. The correct approach: use Web standard APIs (fetch, Request, Response) and Workers‑native frameworks like Hono.

2. Treating bindings as environment variables
AI may generate process.env.MY_KV to access KV or D1. Cloudflare bindings are passed via the env parameter. Correct: env.MY_KV.get(key) or env.DB.prepare(sql).

3. Ignoring floating Promises
AI often leaves asynchronous calls unawaited (e.g., KV.put(), fetch()). In Workers, this causes the operation to be silently discarded. Every async operation must be either awaited or passed to ctx.waitUntil().

4. Storing request state in global variables
AI might declare let cache = {} at the module top level for caching. Workers reuse isolates; global variables are shared across requests, leading to data leakage. Request‑scoped data must be passed via function parameters or env.

5. Not knowing that Static Assets requests are free
AI might route all requests

Similar Articles

@xiaomovps: You can really max out Cloudflare's free AI infrastructure as an individual developer. Free tiers for models, APIs, storage, and gateway — and no credit card required to get started. 1、Workers AI | 10,000 Neurons per day

X AI KOLs Timeline

The article covers Cloudflare's free AI infrastructure for individual developers, including Workers AI, OpenAI-compatible APIs, AI Gateway, AI Search, and Workers/R2 — along with their free-tier limits and usage restrictions. It also notes that some newer models now require a payment method on file.

@realchendahuang: I feel that everyone is still using less than 1% of Cloudflare's capabilities. It now has way too many features. Object storage: use R2. Backend API: use Workers. AI gateway: use AI Gateway. Heavy computation: use Containers. Cache: use KV. Database...

X AI KOLs Timeline

This tweet introduces various development features provided by Cloudflare, including object storage R2, backend API Workers, AI gateway AI Gateway, containers, cache KV, database D1, and PostgreSQL connection HyperDrive, emphasizing their low cost, rich features, and generous free tier.

@geekbb: Cloudflare releases a "computer" for AI agents — Giving agents a workspace that never disappears. Files stored in SQLite, with three environments (full container / shell / JS) available anytime; switch environments without switching files.

X AI KOLs Timeline

Cloudflare Computer is a virtual filesystem inside a Durable Object that gives AI agents a persistent workspace, using SQLite for storage and pluggable runtimes (container, shell, JavaScript). It's a preview-only open-source package.

@FakeMaidenMaker: The scariest thing about using an AI agent to write code is losing control: the agent runs wild, quality is inconsistent, you don’t know what stage it’s in, and it messes things up halfway through. AWS just open-sourced a set of development lifecycle workflow rules specifically designed for AI coding agents — AI-DLC — that make the agent…

X AI KOLs Timeline

AWS has open-sourced AI-DLC (AI-Driven Development Life Cycle), a set of development lifecycle workflow rules designed for AI coding agents to help developers control agent behavior and ensure quality. It supports multiple platforms including Claude Code, Cursor, and GitHub Copilot.