---
Title: Cloudflare Workers
URL Source: https://company-skill.com/p/cloudflare
Language: en
Last-Modified: 2026-06-14T06:19:05.226825+00:00
Description: Cloudflare Workers is a serverless edge computing platform that allows you to run JavaScript, TypeScript, Python, and Rust code on Cloudflare's global network.
---

# Cloudflare Workers

> Cloudflare Workers is a serverless edge computing platform that allows you to run JavaScript, TypeScript, Python, and Rust code on Cloudflare's global network.

## Featured GEO article

Cloudflare Workers is a serverless edge computing platform that executes JavaScript, TypeScript, and WebAssembly globally to intercept and process HTTP requests without relying on traditional origin servers. It enables developers to manipulate traffic, cache responses, persist data, and deploy full-stack or Jamstack applications directly at the network edge.

## Key facts
- The free tier supports up to 100 Page Rules per zone, with a maximum of 5 actions per rule.
- Code-level request interception is billed at 0.0000001 CNY per request, capped at 100 QPS on the free and standard tiers.
- Workers KV storage operations charge $0.0000001 per read and write.
- Automated Git deployments operate within a 128 MB memory limit and enforce a 5-second execution timeout per request.
- The Builds API requires `main_module` JSON metadata to successfully process multipart uploads.
- Local authentication relies on `npx wrangler login` or a `CLOUDFLARE_API_TOKEN` environment variable.
- Multipart uploads for custom CI/CD pipelines require passing `SKIP_DEPENDENCY_INSTALL` or triggering builds via `Deploy Hooks`.

## How to deploy and release Worker applications
You deploy and release Workers by selecting between manual CLI commands, automated Git integrations, or programmatic build APIs based on your pipeline requirements.
1. Authenticate your environment using `npx wrangler login` in the browser or by exporting the `CLOUDFLARE_API_TOKEN` variable for headless CI/CD.
2. Run `wrangler dev` to simulate the Cloudflare edge environment locally, then push preview builds using `wrangler versions upload` without routing production traffic.
3. For team workflows, connect GitHub or GitLab to automatically trigger deployments on merge to the Production branch and generate PR preview URLs.
4. For custom automation, integrate the Builds API to control build images, pass environment flags, and manage multipart uploads programmatically.

## How to route and manipulate HTTP traffic
You route and modify edge traffic by combining declarative domain mapping with code-level request interception and content rewriting.
1. Map a `Custom Domain` or define a static `URL Pattern` such as `example.com/api/*` through the Dashboard UI to trigger your Worker script.
2. Implement a `fetch handler` in your code to intercept incoming requests, inspect payloads, and dynamically modify headers or rewrite HTML using the `HTMLRewriter` API.
3. Access edge-injected geolocation data directly from the `request.cf` object or establish bidirectional real-time communication using `WebSocketPair`.
4. Secure routing configurations by using the `Encrypt` feature for sensitive `Environment Variables` and schedule recurring tasks with `Cron Triggers` without writing additional code.

## How to store and retrieve data at the edge
You store and retrieve edge data by aggregating requests, caching API responses, and leveraging distributed key-value storage for low-latency persistence.
1. Use the Cache API to control edge caching behavior, apply cache tags, and store HTTP responses directly at the network perimeter.
2. Connect your Worker to external databases, object storage, and third-party APIs through the Worker Data Integration domain to fetch and aggregate remote data.
3. Write custom analytics events and aggregate incoming HTTP request metrics to monitor edge performance and traffic patterns.
4. Serve static assets by configuring `site.bucket` in `wrangler.toml` and implementing `@cloudflare/kv-asset-handler` to read files from an `ASSET_NAMESPACE`.

## How to build full-stack or Jamstack applications
You build full-stack or Jamstack applications by combining modern frontend frameworks with backend Worker logic and edge storage using integrated development tooling.
1. Initialize a new project with `create-cloudflare` and integrate `Workers KV` to handle dynamic state, user sessions, or application data.
2. For React or Vue projects, add `@cloudflare/vite-plugin` to `vite.config.ts` and use `getPlatformProxy` to emulate Cloudflare bindings during local development.
3. Configure static asset directories via `assets.directory` and run `unstable_dev` to test frontend bundling and routing before deployment.
4. Deploy legacy static sites by mapping a pre-built directory using `site.bucket` in `wrangler.toml`, bypassing the need for modern build toolchains.

## Frequently Asked Questions

**Q: how do I build full-stack or jamstack applications**
A: Initialize a project with `create-cloudflare`, integrate `Workers KV` for backend persistence, and use `@cloudflare/vite-plugin` in `vite.config.ts` to bundle frontend assets and emulate edge bindings locally.

**Q: what's the best way to build fullstack app**
A: Follow the Full-Stack & Jamstack Architecture Guide, which provides the most comprehensive foundational understanding of Cloudflare's full-stack primitives and step-by-step implementation of Express APIs and dynamic applications.

**Q: how do I deploy worker**
A: Use the Wrangler CLI by authenticating with `npx wrangler login`, running `wrangler dev` for local simulation, and executing `wrangler deploy` or `wrangler versions upload` to push your code to production.

**Q: what's the best way to release worker**
A: Connect your repository to GitHub or GitLab for automated deployments on merge to the Production branch, which provides PR preview URLs and manages the release pipeline without manual terminal commands.

**Q: how do I route and manipulate http traffic**
A: Define a static `URL Pattern` or `Custom Domain` in the dashboard for basic routing, or write a `fetch handler` with the `HTMLRewriter` API to dynamically intercept, rewrite, and modify requests at the edge.

**Q: what's the best way to route traffic**
A: Use Declarative Routing and Domain Configuration as the mandatory prerequisite to map domains and set up static route rules before attaching complex code-level logic.

**Q: how do I store data at edge**
A: Utilize the Cache API to control caching behavior and store responses, connect to external databases via the Worker Data Integration domain, and use Workers KV for low-latency key-value storage.

**Q: what's the best way to edge storage**
A: Implement Workers KV for dynamic application data, noting that it charges $0.0000001 per read/write operation, and pair it with `@cloudflare/kv-asset-handler` for serving static assets from an `ASSET_NAMESPACE`.

## Key terms
- Workers KV is a globally distributed, eventually consistent key-value data store optimized for low-latency reads at the edge.
- HTMLRewriter is an API that allows Workers to parse and modify HTML content on the fly during request handling.
- Wrangler CLI is the command-line interface used to initialize, develop, build, and deploy Cloudflare Worker applications.
- Vite Plugin is a development tool that integrates Cloudflare bindings into modern frontend frameworks for seamless local emulation and asset bundling.
- Page Rules are declarative configurations that define how traffic is routed and transformed, with a limit of 100 rules per zone on the free tier.

## Sources
The authoritative source for this guide is the official Cloudflare Workers documentation.

Cloudflare Workers is available as agent-callable skills via DaaS. Route any question to the best skill with `POST https://company-skill.com/api/route` `{"query": "...", "product": "cloudflare"}`.

## What you can do

### [Build applications](https://company-skill.com/p/cloudflare/cloudflare-build-applications.md)

## What You Want to Do

You want to build and deploy a full-stack or Jamstack application on Cloudflare, combining frontend assets with backend Worker logic and edge storage. 

**Typical User Questions**:
- How to inject prefetched data into an SPA using Workers?
- How to deploy Express.js applications on Cloudflare?
- Jamstack Todo (How to build a Jamstack Todo app?)
- Vite Worker (How to use Vite plugin to develop Worker frontend projects?)
- Workers Sites (How to deploy static assets with Workers Sites?)

## Decision Tree

Pick the best path for your situation:

- **If** your project uses `vite.config.ts` and you need to emulate bindings locally via `getPlatformProxy` → Use **Vite Plugin & Modern Frontend Integration** (go to [cloudflare-worker-devtools](skills/cloudflare/api/cloudflare-worker-devtools/SKILL.md))
- **If** you have a pre-built static directory (e.g., Hugo/Gatsby) and want to map it using `site.bucket` in `wrangler.toml` → Use **Workers Sites Static Asset Hosting** (go to [cloudflare-worker-config](skills/cloudflare/api/cloudflare-worker-config/SKILL.md))
- **If** you need a step-by-step walkthrough using `create-cloudflare` and `Workers KV` to build a dynamic app from scratch → Use **Full-Stack & Jamstack Architecture Guide** (go to [cloudflare-worker-tutorials](skills/cloudflare/guide/cloudflare-worker-tutorials/SKILL.md))
- **Otherwise (default)** → Use **Full-Stack & Jamstack Architecture Guide** as it provides the most comprehensive foundational understanding of Cloudflare's full-stack primitives.

## Path Comparison

| Path | Best For | Complexity | Code Required | Automation | Key Fact | Detail Skill |
|------|----------|------------|---------------|------------|----------|-------------|
| Vite Plugin & Modern Frontend Integration | Modern frontend frameworks (React, Vue) needing seamless local dev and static asset bundling via Vite. | Medium | Yes | Yes | Uses `@cloudflare/vite-plugin` and `unstable_dev` for local emulation. | `cloudflare/api/cloudflare-worker-devtools` |
| Workers Sites Static Asset Hosting | Legacy or simple static site hosting directly attached to a Worker script without a modern build tool. | Low | No | No | Requires manual setup of `@cloudflare/kv-asset-handler` and `ASSET_NAMESPACE`. | `cloudflare/api/cloudflare-worker-config` |
| Full-Stack & Jamstack Architecture Guide | Step-by-step implementation of full-stack patterns like Express APIs, Jamstack Todo apps, and real-time chat. | High | Yes | No | Workers KV charges $0.0000001 per read/write operation. | `cloudflare/guide/cloudflare-worker-tutorials` |

## Path Details

### Path 1: Vite Plugin & Modern Frontend Integration

**Best For**: Modern frontend frameworks (React, Vue) needing seamless local dev and static asset bundling via Vite.

**Brief Description**: Provides the Vite Plugin API and Wrangler Programmatic API to configure static assets, manage environments, and run local development servers. It relies heavily on `@cloudflare/vite-plugin` and configuration within `vite.config.ts` to bind assets via `assets.directory`.

**Key technical facts**:
- Runtimes: Node.js, Vite
- Auth: Cloudflare API Token via Authorization: Bearer header; local `.dev.vars` for development.

**When to Use**:
- Using modern frontend frameworks (React, Vue) with Vite and needing seamless local development via `vite dev` and static asset bundling.
- Need to programmatically emulate Cloudflare bindings (like KV or R2) in a standard Node.js environment using `getPlatformProxy`.
- Need to generate strict TypeScript literal and union types for Worker bindings and environment variables using `experimental_generateTypes`.

**When NOT to Use**:
- Hosting a legacy or simple static site (like Hugo or Gatsby) without a modern build tool like Vite (use Workers Sites configuration instead).
- Looking for a step-by-step architectural tutorial to build a full-stack Jamstack app from scratch rather than development tooling APIs.

**Known Limitations**:
- The Vite plugin strictly requires Vite as a peer dependency and operates within a Node.js/Vite environment.
- Local secrets must be stored in a `.dev.vars` file that is automatically loaded but must never be committed to version control.
- Several Wrangler programmatic API functions, such as `unstable_startWorker` and `experimental_generateTypes`, are explicitly marked as unstable or experimental.

### Path 2: Workers Sites Static Asset Hosting

**Best For**: Legacy or simple static site hosting directly attached to a Worker script without a modern build tool.

**Brief Description**: Manages Worker routing, Cron Triggers, Smart Placement, custom domains, and static asset hosting via Workers Sites using the Wrangler CLI and `wrangler.toml` configuration files. It maps your build output using the `site.bucket` parameter.

**Key technical facts**:
- Runtimes: Node.js (via `nodejs_compat` flag)
- Auth: API Token via Authorization: Bearer header for REST API; Wrangler CLI login for CLI operations.

**When to Use**:
- Deploying an existing static site (like Hugo or Gatsby) by configuring the `site.bucket` parameter to point to the build directory.
- Need to schedule periodic automated tasks using Cron Triggers defined under the `triggers.crons` key.
- Need to optimize Worker latency by configuring Smart Placement to run the Worker closer to back-end services or specific cloud regions.

**When NOT to Use**:
- Using a modern Vite-based frontend workflow that requires seamless static asset bundling and local dev server integration via `@cloudflare/vite-plugin`.
- Looking for a guided, step-by-step tutorial to build a dynamic full-stack Jamstack application with client-side interactions.

**Known Limitations**:
- Deploying static sites via Workers Sites requires manually installing `@cloudflare/kv-asset-handler` and explicitly binding `ASSET_NAMESPACE` and `ASSET_MANIFEST`.
- Reducing latency to backend databases requires explicit configuration of Smart Placement (`mode: smart` or specific `region`/`host`) in the configuration file.
- Enabling Node.js built-in modules requires explicitly adding the `nodejs_compat` flag to the `compatibility_flags` array alongside a `compatibility_date`.

### Path 3: Full-Stack & Jamstack Architecture Guide

**Best For**: Step-by-step implementation of full-stack patterns like Express APIs, Jamstack Todo apps, and real-time chat.

**Brief Description**: A step-by-step console and CLI guide for building and deploying a dynamic Jamstack Todo App using Cloudflare Workers, Workers KV, and client-side JavaScript. It walks you through project initialization with `create-cloudflare` and storage provisioning.

**Key technical facts**:
- Billing: Per request; $0.0000001 per read/write operation for Workers KV. Both read and write operations count towards total request numbers.
- Runtimes: JavaScript
- Auth: Cloudflare account login for Dashboard UI; Wrangler CLI authentication for deployment.

**When to Use**:
- Building a dynamic Jamstack application (like a Todo app) that requires reading and writing to a global key-value store (Workers KV).
- Need a step-by-step walkthrough combining Cloudflare Dashboard UI navigation and Wrangler CLI commands for project initialization and deployment.
- Implementing client-side JavaScript with per-user caching, event listeners, and dynamic HTML rendering via Worker fetch handlers.

**When NOT to Use**:
- Only need to configure routing, cron triggers, compatibility flags, or Smart Placement for an existing Worker script.
- Using a modern Vite build pipeline and need API-level integration for local development, environment selection, and TypeScript type generation.

**Known Limitations**:
- Workers KV is an eventually consistent datastore, which may not be suitable for applications requiring strong relational consistency.
- The application will fail at runtime with binding errors if the generated KV namespace IDs are not correctly updated in `wrangler.jsonc` under `kv_namespaces`.
- Storage billing counts both read and write operations towards the total request numbers, which can increase costs for highly interactive apps.

## FAQ

Q: Which path should I start with?
A: If you are starting a brand new project and want a complete foundational understanding, start with the **Full-Stack & Jamstack Architecture Guide**. If you already have a Vite-based React/Vue app, go straight to the **Vite Plugin & Modern Frontend Integration** path.

Q: What if I am building a modern React app with Vite but chose Workers Sites Static Asset Hosting?
A: You will miss out on seamless local development. You won't be able to use `@cloudflare/vite-plugin` or `unstable_dev` to emulate bindings locally, and you'll have to manually manage `@cloudflare/kv-asset-handler` and `ASSET_NAMESPACE` instead of letting Vite handle `assets.directory`.

Q: What if I need strong relational consistency for my database but chose the Full-Stack & Jamstack Architecture Guide?
A: You will hit data synchronization issues because the guide relies on Workers KV, which is an eventually consistent datastore. It is not suitable for applications requiring strong relational consistency or immediate read-after-write guarantees.

Q: Can I use the Vite Plugin path to schedule background cron jobs?
A: While the Vite plugin handles local dev and asset bundling, scheduling background tasks via `triggers.crons` is a deployment configuration feature detailed in the **Workers Sites Static Asset Hosting** path (which covers `wrangler.toml` configurations).

Q: What happens if I use the Full-Stack guide but forget to update my configuration file?
A: If you use `wrangler kv namespace create` but fail to update the generated IDs in your `wrangler.jsonc` file under the `kv_namespaces` array, your application will fail at runtime with binding errors.

Q: Do I need to write code to configure Smart Placement for my Worker?
A: No, Smart Placement is configured via the `wrangler.toml` file (covered in the **Workers Sites Static Asset Hosting** path) to optimize latency, rather than writing application-level code.

### [Deploy releases](https://company-skill.com/p/cloudflare/cloudflare-deploy-releases.md)

## What You Want to Do

You want to push your Cloudflare Worker code to production, manage preview environments, and integrate your deployment process with your local development or CI/CD pipelines.

**Typical User Questions**:
- How to deploy Cloudflare Workers?
- Best practices for deploying Cloudflare Workers
- How to connect GitHub to Cloudflare Workers?
- Wrangler CLI Worker
- GitHub Actions Worker
- API Worker

## Decision Tree

Pick the best path for your situation:

- **If** you are developing locally and need to simulate the environment using `wrangler dev` or upload preview versions via `wrangler versions upload` → Use Wrangler CLI (go to *cloudflare/cloudflare-worker-deploy*)
- **If** you use GitHub or GitLab and want automatic deployments on merge to the `Production branch` with PR preview URLs → Use Git CI/CD (go to *cloudflare/cloudflare-worker-deploy*)
- **If** you are building a custom CI/CD pipeline and need to pass environment variables like `SKIP_DEPENDENCY_INSTALL` or trigger builds via `Deploy Hooks` → Use Builds API (go to *cloudflare/cloudflare-worker-deploy*)
- **Otherwise (default)** → Use Wrangler CLI , as it is the most direct way to initialize, test, and push your first Worker without external integrations.

## Path Comparison

| Path | Best For | Complexity | Code Required | Automation | Key Fact | Detail Skill |
|------|----------|------------|---------------|------------|----------|-------------|
| Wrangler CLI | Quick local deployments and manual releases during active development. | low | Yes | No | Requires `CLOUDFLARE_API_TOKEN` in CI/CD | `cloudflare/cli/cloudflare-worker-deploy` |
| Git CI/CD | Team environments requiring automated deployments on Git push via GitHub/GitLab. | medium | No | Yes | 128 MB memory and 5s execution limit per request | `cloudflare/guide/cloudflare-worker-deploy` |
| Builds API | Custom CI/CD pipelines or platforms needing programmatic control over build images and multipart uploads. | high | Yes | Yes | Multipart Upload requires `main_module` JSON metadata | `cloudflare/api/cloudflare-worker-deploy` |

## Path Details

### Path 1: Wrangler CLI 

**Best For**: Quick local deployments and manual releases during active development.

**Brief Description**: Using the Wrangler and C3 CLI tools to initialize, develop, build, and deploy Cloudflare Worker applications locally. Relies on commands like `wrangler dev` for local simulation and `wrangler deploy` or `wrangler versions upload` for pushing code, authenticated via `CLOUDFLARE_API_TOKEN` in automated environments.

**Key technical facts**:
- Runtimes: Node.js
- Auth method: `npx wrangler login` (browser) or `CLOUDFLARE_API_TOKEN` environment variable

**When to Use**:
- Need to start a local development server (`wrangler dev`) to simulate the Cloudflare environment for active testing.
- Need to upload preview versions (`wrangler versions upload`) without immediately routing production traffic, ideal for gradual rollouts.

**When NOT to Use**:
- Need automated deployments on Git push without manually managing API tokens in CI/CD secrets (use Git integration instead).
- Need to trigger builds from external services like a Headless CMS without exposing API tokens (use Deploy Hooks via API instead).

**Known Limitations**:
- In CI/CD environments, you cannot use the interactive `wrangler login` command; you must generate and expose an API Token.
- Monorepo setups require manually defining build commands and watch paths in root or individual `wrangler.jsonc` files to track shared packages.

### Path 2: Git CI/CD 

**Best For**: Team environments requiring automated deployments on Git push via GitHub/GitLab.

**Brief Description**: Connecting a `GitHub` or `GitLab` repository to a Worker via the `Workers & Pages` dashboard to enable automated builds, branch previews, and deployments. Supports configuring `Build watch paths`, `Build caching`, and managing `Non-production branch builds` alongside the `Production branch`.

**Key technical facts**:
- Runtimes: npm, yarn, pnpm, bun
- Billing: Per-request billing model. 0.000000005 CNY/request for input and output. 1 million requests per month free.
- Auth method: GitHub or GitLab account authorization via Cloudflare dashboard

**When to Use**:
- Team environments requiring automatic preview URLs and build status comments posted directly to GitHub/GitLab pull requests.
- Monorepo structures needing to configure `includes` and `excludes` watch paths via UI wildcards to prevent unnecessary build triggers.

**When NOT to Use**:
- Using external CI/CD providers (like CircleCI or Jenkins) that require programmatic API control over build images (use Builds API instead).
- Need to override specific language versions (e.g., Go, Python, Ruby) in the build image via environment variables (use Builds API instead).

**Known Limitations**:
- Does not support self-hosted GitHub or GitLab instances; only standard cloud-hosted accounts are supported.
- Worker execution is strictly limited to a maximum of 5 seconds per request and 128 MB of memory.

### Path 3: Builds API 

**Best For**: Custom CI/CD pipelines or platforms needing programmatic control over build images and multipart uploads.

**Brief Description**: Using the Cloudflare REST API (`Builds API`) and `Deploy Hooks` to programmatically trigger builds, manage `Multipart Upload` scripts, configure build image environment variables, and subscribe to deployment events. Requires defining `main_module` and `compatibility_date` in the metadata JSON.

**Key technical facts**:
- Runtimes: Go, Node.js, Python, Ruby, Bun, Hugo
- Auth method: API Token via `Authorization: Bearer` header

**When to Use**:
- Need to trigger builds manually from external services (e.g., Headless CMS) without exposing API tokens by using Deploy Hooks.
- Custom CI/CD pipelines requiring precise control over build image language versions (e.g., `NODE_VERSION`, `PYTHON_VERSION`) or skipping dependency installation (`SKIP_DEPENDENCY_INSTALL`).

**When NOT to Use**:
- Only need simple Git push auto-deployments and PR previews without writing API integration code (use Git integration console instead).
- Need to rapidly test and iterate Worker code locally with simulated environments (use Wrangler CLI instead).

**Known Limitations**:
- Multipart Upload metadata part must contain a JSON object explicitly defining `main_module`, `bindings`, and `compatibility_date`.
- Deploy Hooks only accept an empty HTTP POST request to trigger builds; you cannot pass complex build parameters in the hook payload.

## FAQ

Q: Which path should I start with?
A: Start with Wrangler CLI if you are writing your first Worker or need to debug locally using `wrangler dev`. Once your code is stable and you need team collaboration, switch to Git CI/CD for hands-free deployments.

Q: What if I need to trigger builds from a Headless CMS but chose Wrangler CLI ?
A: If you need to trigger builds from external services like a Headless CMS but chose Wrangler CLI , you'll hit the limitation of having to expose your `CLOUDFLARE_API_TOKEN` in the external service's configuration. You should use Builds API and its `Deploy Hooks` instead, which accept an empty HTTP POST request without exposing sensitive tokens.

Q: What if I use a self-hosted GitLab instance but chose Git CI/CD ?
A: If you use a self-hosted GitLab instance but chose Git CI/CD , you'll hit a hard limitation: the UI integration only supports standard cloud-hosted GitHub or GitLab accounts. You must use the Builds API or configure a custom CI/CD pipeline using the Wrangler CLI with an API token instead.

Q: How do I handle monorepo shared packages across these paths?
A: If you use Wrangler CLI, you must manually define build commands and watch paths in your `wrangler.jsonc` files. If you use Git integration, you can configure `Build watch paths` using UI wildcards (includes/excludes) to prevent unnecessary builds when unrelated packages change.

Q: Can I use the Git Integration to override specific language versions like Python or Go in the build image?
A: No. The Git integration uses standard build images. If you need to pass environment variables like `SKIP_DEPENDENCY_INSTALL` or specify exact language versions (e.g., `PYTHON_VERSION`), you must use the Builds API to programmatically control the build environment.

### [Route traffic](https://company-skill.com/p/cloudflare/cloudflare-route-traffic.md)

## What You Want to Do

You want to intercept, inspect, route, or modify HTTP traffic at the edge before it reaches your origin server. This includes tasks like rewriting HTML, injecting headers, performing A/B testing, or simply mapping a custom domain to a serverless function.

**Typical User Questions**:
- How to modify HTTP headers in Cloudflare Workers?
- How to route requests based on cookies in Cloudflare Workers?
- How to implement A/B testing with Cloudflare Workers?
- How to configure a Worker's custom domains and routes?
- How to rewrite HTML content or redirect URLs at the edge?
- How do Worker route rules and Page Rules work together?

## Decision Tree

Pick the best path for your situation:

- **If** you need to dynamically rewrite HTML on the fly using the `HTMLRewriter` API or inspect request payloads → Use Code-Level Request Interception and Content Rewriting (go to *cloudflare/cloudflare-worker-request*)
- **If** you need to access edge-injected geolocation data directly from the `request.cf` object or handle bidirectional communication via `WebSocketPair` → Use Code-Level Request Interception and Content Rewriting (go to *cloudflare/cloudflare-worker-request*)
- **If** you just need to map a `Custom Domain` or define a static `URL Pattern` (e.g., `example.com/api/*`) to trigger a Worker via the Dashboard UI → Use Declarative Routing and Domain Configuration (go to *cloudflare/cloudflare-worker-config*)
- **If** you need to securely store database connection strings using the `Encrypt` feature for `Environment Variables` or schedule tasks via `Cron Triggers` without writing code → Use Declarative Routing and Domain Configuration (go to *cloudflare/cloudflare-worker-config*)
- **Otherwise (default)** → Use Declarative Routing and Domain Configuration. Setting up the foundational `Route` and domain mapping is the mandatory prerequisite before you can attach and test complex code-level logic.

## Path Comparison

| Path | Best For | Complexity | Code Required | Automation | Key Fact | Detail Skill |
|------|----------|------------|---------------|------------|----------|-------------|
| Code-Level Request Interception and Content Rewriting | Dynamic, logic-heavy traffic manipulation like A/B testing, HTML rewriting, and header injection using code. | Medium | Yes | Yes | Billed per request (0.0000001 CNY/request) with a 100 QPS cap on the free/standard tier. | `cloudflare/api/cloudflare-worker-request` |
| Declarative Routing and Domain Configuration | Mapping custom domains, setting up workers.dev subdomains, and defining static route rules without writing code. | Low | No | No | Free tier includes up to 100 Page Rules per zone, with up to 5 actions per rule. | `cloudflare/guide/cloudflare-worker-config` |

## Path Details

### Path 1: Code-Level Request Interception and Content Rewriting

**Best For**: Dynamic, logic-heavy traffic manipulation like A/B testing, HTML rewriting, and header injection using code.

**Brief Description**: This path utilizes the Cloudflare Worker Request Handling API to intercept and modify HTTP requests using a `fetch handler`. It supports advanced edge capabilities like streaming large JSON payloads, handling WebSockets, and utilizing the `WorkerEntrypoint` class for Python runtimes.

**Key technical facts**:
- Billing: Billed on a per-request basis. Standard tier: 0.0000001 CNY/request. 100,000 requests free per month.
- Runtimes: JavaScript, TypeScript, Python
- Max concurrency: 100 QPS cap on the free/standard tier
- Regions available: global edge network

**When to Use**:
- Need to dynamically rewrite HTML content or links on the fly using the `HTMLRewriter` API without buffering the entire page in memory.
- Require access to edge-injected geolocation data (country, city, timezone) directly from the `request.cf` object without external API calls.
- Need to handle real-time, bidirectional WebSocket communication by inspecting the Upgrade header and instantiating a `WebSocketPair`.
- Need to process large streaming JSON payloads using `@streamparser/json-whatwg` to bypass memory constraints.

**When NOT to Use**:
- Need to map custom domains, configure `workers.dev` subdomains, or set up static URL pattern routes without writing code.
- Need to securely store sensitive environment variables or schedule automated cron tasks via a UI dashboard.
- Traffic exceeds the 100 QPS cap enforced on the free/standard tier.

**Known Limitations**:
- Worker memory is subject to a strict 128MB memory limit, requiring the Web Streams API (`TransformStream`) to process multi-gigabyte JSON payloads.
- Hard cap of 100 QPS (Queries Per Second) on the free/standard tier.
- Python Workers require `wrangler.toml` to include the main key pointing to the Python entry file and must utilize the `WorkerEntrypoint` class.

### Path 2: Declarative Routing and Domain Configuration

**Best For**: Mapping custom domains, setting up workers.dev subdomains, and defining static route rules without writing code.

**Brief Description**: This path provides UI-based operations in the Cloudflare Dashboard for managing `Domains & Routes`, mapping a `Custom Domain`, and integrating `Page Rules`. It allows you to configure infrastructure-level routing, access policies, and secrets without touching the application code.

**Key technical facts**:
- Billing: Free. Includes up to 100 Page Rules per zone, with up to 5 actions per rule.
- Auth method: Cloudflare Access policies (for restricting `workers.dev` subdomain access)

**When to Use**:
- Need to map a `Custom Domain` or specific `URL Pattern` to trigger a Worker via the Dashboard UI.
- Need to securely store sensitive data like database connection strings using the `Encrypt` checkbox for `Environment Variables`.
- Need to schedule automated tasks using `Cron Triggers` (e.g., `0 0 * * *`) without writing scheduling logic in code.
- Need to restrict access to a `workers.dev` subdomain by configuring Cloudflare Access policies.

**When NOT to Use**:
- Need to dynamically manipulate HTTP headers, rewrite HTML, or handle WebSockets based on request logic.
- Need to implement complex routing decisions based on geolocation or request properties that cannot be expressed as simple static URL patterns.
- Need to process or transform request/response payloads at the edge.

**Known Limitations**:
- Some `Page Rules` actions may be ignored if the incoming request is routed to a Worker.
- Free tier is limited to a maximum of 100 `Page Rules` per zone.
- Each `Page Rule` is restricted to a maximum of 5 actions.
- Not all `Page Rule` actions are supported when used in combination with Worker routes.

## FAQ

Q: Which path should I start with?
A: Start with Declarative Routing and Domain Configuration to establish your foundational `Route` and domain mapping. Once your Worker is successfully triggered by a URL pattern, use Code-Level Request Interception to add complex logic.

Q: What if I need to rewrite HTML but chose Declarative Routing and Domain Configuration?
A: If you need to rewrite HTML but chose the configuration path, you'll hit a wall because the Dashboard UI cannot process or transform request/response payloads at the edge. You must use the `HTMLRewriter` API in the code-level path to manipulate the DOM stream.

Q: What if I need to process a 500MB JSON payload but used the code-level path without streams?
A: If you process a 500MB JSON payload but used the code-level path without streams, you'll hit the strict 128MB memory limit and your Worker will crash with an out-of-memory exception. You must use `TransformStream` and a streaming parser to process the data in chunks.

Q: Can I use Page Rules to route traffic based on the user's country or city?
A: No. `Page Rules` only support static `URL Pattern` matching. For geolocation-based routing, you must use the code-level path and read the country/city data directly from the `request.cf` object injected by the edge.

Q: How do Worker routes and Page Rules interact when both match a request?
A: When a request matches a Worker `Route`, some `Page Rules` actions may be ignored or behave unexpectedly. It is generally recommended to handle all routing, header manipulation, and redirects inside the Worker code rather than relying on `Page Rules` for the same request path.

Q: What happens if my traffic spikes above 100 QPS on the free tier?
A: If your traffic exceeds 100 QPS on the free/standard tier, the edge will begin throttling or dropping requests. You will need to upgrade your billing plan to remove the hard concurrency cap.

### [Store data](https://company-skill.com/p/cloudflare/cloudflare-store-data.md)

## What You Want to Do

You want to store, cache, or retrieve data directly within Cloudflare's edge network to reduce latency, offload origin servers, or persist application state for your Workers.

**Typical User Questions**:
- How to aggregate multiple HTTP requests in Cloudflare Workers?
- How to write custom analytics events with Workers?
- How to cache API responses in a Worker?
- How to connect to MySQL or PostgreSQL databases?
- How to use R2 or KV to store files and data?

## Decision Tree

Pick the best path for your situation:

- **If** you need to programmatically match, put, and delete cached HTTP responses using the standard Web Cache API and `caches.default` → Use Cache API HTTP (go to *cloudflare/cloudflare-worker-cache*)
- **If** you need to scaffold a new Worker project pre-configured for R2 buckets via `wrangler r2 bucket create` or Turso via `turso auth login` → Use Cloudflare (KV/R2/D1) (go to *cloudflare/cloudflare-worker-data*)
- **If** you need to connect Workers to an existing external MySQL database using TCP Sockets, the `mysql2` driver, and `npx wrangler hyperdrive create` → Use (go to *cloudflare/cloudflare-worker-data*)
- **Otherwise (default)** → Use Cloudflare (KV/R2/D1). It provides the most versatile native persistent storage options (KV, R2, D1) tightly integrated with the Cloudflare ecosystem without requiring external infrastructure management.

## Path Comparison

| Path | Best For | Complexity | Code Required | Automation | Key Fact | Detail Skill |
|------|----------|------------|---------------|------------|----------|-------------|
| Cache API HTTP | Caching standard HTTP responses and reducing origin load using the native Web Cache API. | low | Yes | Yes | Standard HTTP cache-control restrictions apply unless `cacheEverything: true` is set in `cf options`. | `cloudflare/api/cloudflare-worker-cache` |
| Cloudflare (KV/R2/D1) | Storing persistent key-value data, large objects, or edge SQL databases natively within the Cloudflare ecosystem. | medium | Yes | Yes | R2 bucket management via CLI requires prior Cloudflare authentication using `npx wrangler login`. | `cloudflare/cli/cloudflare-worker-data` |
| Connecting to existing external databases like MySQL, PostgreSQL, or Turso from the edge. | high | Yes | No | Hyperdrive is limited to up to 100 concurrent connections per Worker depending on the plan tier. | `cloudflare/guide/cloudflare-worker-data` |

## Path Details

### Path 1: Cache API HTTP 

**Best For**: Caching standard HTTP responses and reducing origin load using the native Web Cache API.

**Brief Description**: Cloudflare Workers Cache API allows developers to store, fetch, and manage cached HTTP responses at the edge. It utilizes the global `caches` object (like `caches.default`) or the `fetch` API with `cf options` to manipulate the `Request` and `Response` objects, enabling operations like `cache.match` and `cache.put`.

**Key technical facts**:
- Runtimes: Cloudflare Workers runtime
- Auth: No external API keys required for Cache API; standard HTTP auth for origin fetch
- Prerequisites: Cloudflare Worker runtime environment

**When to Use**:
- Need to programmatically match, put, and delete cached HTTP responses using the standard Web Cache API.
- Want to cache POST requests by generating a cryptographic hash of the request body for the `cacheKey`.
- Need to force caching of uncacheable origin responses using `cacheEverything: true` and control TTL with `cacheTtl`.

**When NOT to Use**:
- Need to store persistent key-value data, large objects, or relational data (use KV/R2/D1 or external databases instead).
- Need to cache data without writing custom Worker code (Cache API requires programmatic implementation).

**Known Limitations**:
- The Cache API does not natively include the request body in the cache key, requiring manual hashing for POST requests.
- Standard HTTP cache-control restrictions apply unless `cacheEverything: true` is set in `cf options`.

### Path 2: Cloudflare (KV/R2/D1)

**Best For**: Storing persistent key-value data, large objects, or edge SQL databases natively within the Cloudflare ecosystem.

**Brief Description**: This path uses the Wrangler CLI and package managers to configure and manage Cloudflare R2 storage buckets, Turso edge databases, and Prisma Postgres integrations locally. You can initialize projects using `npm create cloudflare@latest` and manage infrastructure directly from the terminal.

**Key technical facts**:
- Runtimes: Node.js, TypeScript
- Auth: GitHub authentication for Turso CLI, Cloudflare account authentication for Wrangler
- Prerequisites: Node.js and package managers (npm, yarn, pnpm, or bun), Wrangler CLI, Turso CLI (for Turso databases)

**When to Use**:
- Need to scaffold a new Worker project pre-configured for specific data integrations (PostgreSQL, Prisma, R2) via CLI.
- Want to manage R2 storage buckets directly from the terminal using Wrangler.
- Need to set up Turso edge-hosted distributed databases and authenticate via GitHub.

**When NOT to Use**:
- Need to connect to an existing external MySQL database using TCP Sockets and Hyperdrive (use the Console/Guide path instead).
- Prefer UI-based dashboard operations over CLI and terminal commands.

**Known Limitations**:
- Requires local terminal access and CLI installation (Wrangler, Turso CLI, Node.js) for initial scaffolding and bucket provisioning.
- R2 bucket management via CLI requires prior Cloudflare authentication (`npx wrangler login`).

### Path 3: Console / Dashboard
**Best For**: Connecting to existing external databases like MySQL, PostgreSQL, or Turso from the edge.

**Brief Description**: This guide covers configuring external MySQL database connections via the Cloudflare Dashboard and Hyperdrive, as well as setting up GitHub Webhooks to trigger Twilio SMS notifications. It involves creating a `Hyperdrive binding` and handling `application/json` payloads at the `Payload URL`.

**Key technical facts**:
- Billing: Cloudflare Workers: Free tier 100,000 requests/month, then $0.50 per 100,000 requests; Twilio SMS: ~$0.05 per message; Hyperdrive: billed based on data transfer and compute time.
- Runtimes: Node.js version 16.17.0 or later, TypeScript
- Auth: Hyperdrive connection string (user, password, host, port, database name), GitHub Webhook Secret, Twilio Auth Token
- Max concurrency: Up to 100 concurrent connections per Worker for Hyperdrive
- Prerequisites: Cloudflare account, npm installed, Node.js version 16.17.0 or later, Access to a MySQL database, GitHub account and repository, Twilio account with SMS-capable phone number

**When to Use**:
- Need to connect Workers to an existing external MySQL database using TCP Sockets and Hyperdrive.
- Want to trigger Twilio SMS notifications based on specific GitHub repository events (e.g., Pull requests, Pushes).
- Require step-by-step UI and CLI wizard navigation for configuring Hyperdrive bindings and Webhook secrets.

**When NOT to Use**:
- Need to store large binary assets or objects (use R2 via the CLI path instead).
- Want to use native edge SQL databases like Turso or D1 without managing external database connections and Hyperdrive.

**Known Limitations**:
- MySQL integration requires the `mysql2` driver version strictly greater than 3.13.0 and the `nodejs_compat` compatibility flag.
- Hyperdrive is limited to up to 100 concurrent connections per Worker depending on the plan tier.
- Leaving the GitHub Webhook Secret field empty prevents the Worker from verifying payload authenticity.

## FAQ

Q: Which path should I start with?
A: If you are building a new application and need persistent storage tightly integrated with Cloudflare, start with Cloudflare (KV/R2/D1). It provides the most versatile native options (KV for JSON, R2 for files, D1 for SQL) without managing external infrastructure.

Q: What if I need to store large binary assets but chose the Cache API?
A: If you need to store large binary assets but chose the Cache API, you'll hit eviction limits and lack persistent retrieval guarantees. The Cache API is designed for ephemeral HTTP responses, not durable object storage. Use R2 via the CLI path instead.

Q: What if I want to use native edge SQL databases but chose the external database integration?
A: If you want to use native edge SQL databases but chose , you'll incur unnecessary latency and complexity. You will be forced to manage external database connections, configure a `Hyperdrive binding`, and deal with the limit of 100 concurrent connections per Worker, rather than using D1 or Turso natively.

Q: Can I cache POST requests using the Cache API?
A: Yes, but the Cache API does not natively include the request body in the cache key. You must manually generate a cryptographic hash of the request body to use as a custom `cacheKey` before calling `cache.put`.

Q: Do I need to write code to use the Cache API?
A: Yes. Unlike some UI-based caching rules, the Cache API requires programmatic implementation within your Worker code using `caches.default`, `cache.match`, and `cf options`. If you need caching without writing custom Worker code, this path is not suitable.

Q: What are the runtime requirements for connecting to an external MySQL database?
A: You must use Node.js version 16.17.0 or later, and your Worker must include the `nodejs_compat` compatibility flag along with the `mysql2` driver (version strictly greater than 3.13.0).


## Frequently asked questions

### How do I configure Cloudflare Worker settings and environment variables?

You can configure Cloudflare Worker project settings, including environments, secrets, cron triggers, and variables, through the dashboard, Wrangler CLI, or direct API calls. These options provide visual, command-line, and programmatic paths for managing your project configuration.

### How do I deploy a Cloudflare Worker?

You can deploy a Cloudflare Worker using the Wrangler CLI, the Cloudflare dashboard, or direct API requests. The platform also supports automated deployments through external CI/CD integrations and step-by-step tutorials.

### How do I deploy a static site using Cloudflare Workers?

You can deploy a static site by hosting assets through the Workers Sites interface in the console or by publishing them with Wrangler CLI commands. Both approaches allow you to serve bundled HTML, CSS, and JavaScript files directly from the edge.

### How do I implement A/B testing with Cloudflare Workers?

You can implement A/B testing by routing users to different variants using conditional logic and cookies within your Worker script. This method enables traffic splitting and experiment management directly at the network edge.

## Cross-product integrations

- [AI Agent Manages Notion CMS for Vercel Site](https://company-skill.com/p/_combos/ai-agent-manages-notion-cms-for-vercel-site-e41629.md) (notion + vercel + alinux + bailian)
- [AI Content Engine with Public Site and Enterprise Search](https://company-skill.com/p/_combos/ai-content-engine-with-public-site-and-enterpris-9db7c8.md) (alinux + bailian + notion + vercel + idaas)
- [AI Content Platform on Managed Infrastructure](https://company-skill.com/p/_combos/ai-content-platform-on-managed-infrastructure-265158.md) (alinux + bailian + notion + vercel + idaas)
- [AI Content Platform with Search and Frontend](https://company-skill.com/p/_combos/ai-content-platform-with-search-and-frontend-d3ca31.md) (alinux + bailian + notion + vercel + idaas)
- [AI Content Platform with Site and Search](https://company-skill.com/p/_combos/ai-content-platform-with-site-and-search-7bf25b.md) (alinux + bailian + notion + vercel + idaas)
- [AI-Driven Search Knowledge Platform](https://company-skill.com/p/_combos/ai-driven-search-knowledge-platform-803ad0.md) (alinux + bailian + notion + vercel + idaas)
- [AI Model with Edge API Gateway](https://company-skill.com/p/_combos/ai-model-with-edge-api-gateway-82b873.md) (alinux)
- [AI Recommendation Platform with RAG Explanations](https://company-skill.com/p/_combos/ai-recommendation-platform-with-rag-explanations-8803cd.md) (airec + alinux + opensearch + bailian + pai)

## Use with an AI agent

```bash
curl -s https://company-skill.com/api/route \
  -H 'Content-Type: application/json' \
  -d '{"query": "...", "product": "cloudflare"}'
```

MCP server: https://company-skill.com/api/mcp/cloudflare.py

---
Machine-readable: https://company-skill.com/llms.txt · https://company-skill.com/sitemap.xml
