### Quick Start: Deploy Rule Template Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/bot-management/README.md This quick start guide provides examples for deploying rule templates in the Cloudflare dashboard or for Enterprise deployments. It demonstrates how to block definite bots or apply managed challenges based on bot scores. ```txt # Dashboard: Security > Bots # Enterprise: Deploy rule template (cf.bot_management.score eq 1 and not cf.bot_management.verified_bot) → Block (cf.bot_management.score le 29 and not cf.bot_management.verified_bot) → Managed Challenge ``` -------------------------------- ### Local Development with Bindings Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pages-functions/configuration.md Start the local development server with specific bindings enabled. This example enables KV, D1, and R2 bindings. ```bash npx wrangler pages dev ./dist --kv=KV --d1=DB=db-id --r2=BUCKET ``` -------------------------------- ### Quick Start: Run a Simple Worker with Miniflare API Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/miniflare/README.md This example demonstrates how to instantiate Miniflare programmatically, dispatch a fetch request, and dispose of the instance. Ensure Miniflare is installed and ES modules are enabled. ```javascript import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: ` export default { async fetch(request, env, ctx) { return new Response("Hello Miniflare!"); } } `, }); const res = await mf.dispatchFetch("http://localhost:8787/"); console.log(await res.text()); // Hello Miniflare! await mf.dispose(); ``` -------------------------------- ### Base Agent Quick Start Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/agents-sdk/README.md Create a custom agent using the base Agent class. This example shows how to initialize a SQL table on agent start and handle incoming requests, returning the agent's current state. ```typescript import { Agent } from "agents"; export class MyAgent extends Agent { onStart() { this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)`; } async onRequest(request: Request) { return Response.json({ state: this.state }); } } ``` -------------------------------- ### Multi-Environment Setup Example Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/terraform/patterns.md Defines modules for zone, worker, and pages, demonstrating how to reference them within environment-specific configurations. Ensure module paths are correct relative to the current directory. ```hcl # Directory: environments/{production,staging}/main.tf + modules/{zone,worker,pages} module "zone" { source = "../../modules/zone"; account_id = var.account_id; zone_name = "example.com"; environment = "production" } module "api_worker" { source = "../../modules/worker"; account_id = var.account_id; zone_id = module.zone.zone_id name = "api-worker-prod"; script = file("../../workers/api.js"); environment = "production" } ``` -------------------------------- ### Deploy Site via Wrangler CLI (Quick Start) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pages/README.md Deploy your static site to Cloudflare Pages using the wrangler CLI. This command is part of the quick start guide and requires the build output directory. ```bash npx wrangler pages deploy ./dist --project-name=my-project ``` -------------------------------- ### KV Quick Start Example Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/kv/README.md Demonstrates basic usage of Cloudflare Workers KV for writing and reading data. ```APIDOC ## KV Quick Start Example ### Description This example shows how to perform basic write and read operations using Cloudflare Workers KV. ### Code Examples #### Writing a value ```typescript // Assuming 'env.MY_KV' is your KV namespace binding await env.MY_KV.put("key", "value", { expirationTtl: 300 }); ``` #### Reading a value ```typescript // Read as a string (default) const value = await env.MY_KV.get("key"); // Read as JSON, expecting a specific type interface Config { setting: string; } const json = await env.MY_KV.get("config", "json"); ``` ``` -------------------------------- ### Basic Hono Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers/frameworks.md Set up a basic Hono application with GET and POST routes. Handles plain text and JSON responses. ```typescript import { Hono } from 'hono'; const app = new Hono(); app.get('/', (c) => c.text('Hello World!')); app.post('/api/users', async (c) => { const body = await c.req.json(); return c.json({ id: 1, ...body }, 201); }); export default app; ``` -------------------------------- ### Node.js Dockerfile Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/sandbox/configuration.md Dockerfile for Node.js environments, installing TypeScript and ts-node globally. ```dockerfile FROM docker.io/cloudflare/sandbox:0.7.0 RUN npm install -g typescript ts-node ``` -------------------------------- ### GraphQL Analytics API - Python Client Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/graphql-api/configuration.md Example of setting up a client to query the GraphQL Analytics API using Python. ```APIDOC ## Client Setup - Python ### Function to Query GraphQL ```python import requests, os def query_graphql(query: str, variables: dict = None) -> dict: r = requests.post("https://api.cloudflare.com/client/v4/graphql", headers={"Authorization": f"Bearer {os.environ['CF_API_TOKEN']}", "Content-Type": "application/json"}, json={"query": query, "variables": variables or {}}) r.raise_for_status() result = r.json() if result.get("errors"): raise Exception("; ".join(e["message"] for e in result["errors"])) return result["data"] ``` **Note**: Ensure your API token is stored securely, for example, in an environment variable `CF_API_TOKEN`. ``` -------------------------------- ### Start Container Basic Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/containers/api.md Initiate a container's process with a basic start command. This method returns when the process starts, not when ports are ready. It has an 8-second timeout. ```typescript await container.start(); ``` ```typescript await container.start({ envVars: { KEY: "value" } }); ``` -------------------------------- ### Install React UI Kit Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/realtimekit/configuration.md Install the RealtimeKit package and the React UI kit using npm. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-react-ui ``` -------------------------------- ### Bindings Access Examples Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/miniflare/api.md Examples demonstrating how to access various types of bindings within the Miniflare environment. ```APIDOC ## Bindings Access ### Environment Variables Accessing environment variables, with and without type safety. ```typescript // Basic usage const bindings = await mf.getBindings(); console.log(bindings.SECRET_KEY); // With type safety (recommended): interface Env { SECRET_KEY: string; API_URL: string; KV: KVNamespace; } const env = await mf.getBindings(); env.SECRET_KEY; // string (typed!) env.KV.get("key"); // KVNamespace methods available ``` ### Request.cf Object Accessing Cloudflare specific request properties. ```typescript const cf = await mf.getCf(); console.log(cf?.colo); // "DFW" console.log(cf?.country); // "US" ``` ### KV Namespace Interacting with a KV namespace. ```typescript const ns = await mf.getKVNamespace("TEST_NAMESPACE"); await ns.put("key", "value"); const value = await ns.get("key"); ``` ### R2 Bucket Interacting with an R2 bucket. ```typescript const bucket = await mf.getR2Bucket("BUCKET"); await bucket.put("file.txt", "content"); const object = await bucket.get("file.txt"); ``` ### Durable Objects Interacting with Durable Objects. ```typescript const ns = await mf.getDurableObjectNamespace("COUNTER"); const id = ns.idFromName("test"); const stub = ns.get(id); const res = await stub.fetch("http://localhost/"); // Access storage directly: const storage = await mf.getDurableObjectStorage(id); await storage.put("key", "value"); ``` ### D1 Database Interacting with a D1 database. ```typescript const db = await mf.getD1Database("DB"); await db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)`); await db.prepare("INSERT INTO users (name) VALUES (?)").bind("Alice").run(); ``` ### Cache API Interacting with the Cache API. ```typescript const caches = await mf.getCaches(); const defaultCache = caches.default; await defaultCache.put("http://example.com", new Response("cached")); ``` ### Queue Producer Sending messages to a queue. ```typescript const producer = await mf.getQueueProducer("QUEUE"); await producer.send({ body: "message data" }); ``` ``` -------------------------------- ### Example Agent Use Cases Source: https://github.com/cloudflare/skills/blob/main/commands/build-agent.md Examples of how to invoke the build-agent command for different types of AI agents. ```bash /build-agent a customer support chatbot with tool calling ``` ```bash /build-agent a real-time collaborative editor with state sync ``` ```bash /build-agent a background processing agent with scheduled tasks ``` ```bash /build-agent a voice assistant that can browse the web ``` -------------------------------- ### Install Hono Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers/frameworks.md Install the Hono framework using npm. This is the recommended framework for most use cases. ```bash npm install hono ``` -------------------------------- ### TypeScript: Cloudflare Skills Complete Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/waf/patterns.md This example combines custom rules, managed rulesets, and rate limiting for comprehensive protection. Ensure you have the Cloudflare client initialized with your API token and zone ID. ```typescript const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN }); const zoneId = process.env.ZONE_ID; // 1. Custom rules (execute first) await client.rulesets.create({ zone_id: zoneId, phase: 'http_request_firewall_custom', rules: [ { action: 'skip', action_parameters: { phases: ['http_request_firewall_managed', 'http_ratelimit'] }, expression: 'ip.src in {192.0.2.0/24}' }, { action: 'block', expression: 'cf.waf.score gt 50' }, { action: 'managed_challenge', expression: 'cf.waf.score gt 20' }, ], }); // 2. Managed ruleset (execute second) await client.rulesets.create({ zone_id: zoneId, phase: 'http_request_firewall_managed', rules: [{ action: 'execute', action_parameters: { id: 'efb7b8c949ac4650a09736fc376e9aee', overrides: { categories: [{ category: 'wordpress', enabled: false }] } }, expression: 'true', }], }); // 3. Rate limiting (execute third) await client.rulesets.create({ zone_id: zoneId, phase: 'http_ratelimit', rules: [ { action: 'block', expression: 'true', action_parameters: { ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requests_per_period: 100, mitigation_timeout: 600 } } }, { action: 'block', expression: 'http.request.uri.path eq "/api/login"', action_parameters: { ratelimit: { characteristics: ['ip.src'], period: 60, requests_per_period: 5, mitigation_timeout: 600 } } }, ], }); ``` -------------------------------- ### Lifecycle Management Examples Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/miniflare/api.md Examples for managing the Miniflare instance lifecycle, including reloading configuration and cleanup. ```APIDOC ## Lifecycle Management ### Reloading Configuration Reloads the Miniflare instance with new options. ```typescript await mf.setOptions({ scriptPath: "worker.js", bindings: { VERSION: "2.0" }, }); ``` ### Manual Watcher Example of manually watching for file changes to trigger reloads. ```typescript import { watch } from "fs"; const config = { scriptPath: "worker.js" }; const mf = new Miniflare(config); watch("worker.js", async () => { console.log("Reloading..."); await mf.setOptions(config); }); ``` ### Cleanup Resources Disposes of the Miniflare instance and releases resources. ```typescript await mf.dispose(); ``` ``` -------------------------------- ### Install web-push Package Source: https://github.com/cloudflare/skills/blob/main/skills/agents-sdk/references/webhooks-push.md Install the `web-push` package to handle Web Push notifications via VAPID. ```bash npm install web-push ``` -------------------------------- ### Install Angular UI Kit Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/realtimekit/configuration.md Install the RealtimeKit package and the Angular UI kit using npm. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-angular-ui ``` -------------------------------- ### Install Cloudflare Skills using npx skills CLI Source: https://github.com/cloudflare/skills/blob/main/README.md Install the Cloudflare skills using the npx skills CLI by providing the GitHub repository URL. This command fetches and installs the skills for use with compatible agents. ```bash npx skills add https://github.com/cloudflare/skills ``` -------------------------------- ### Event Dispatching Examples Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/miniflare/api.md Examples of how to dispatch various types of events to the Miniflare worker. ```APIDOC ## Event Dispatching ### Fetch Request Simulates a fetch request to the worker. ```js const res = await mf.dispatchFetch("http://localhost:8787/path", { method: "POST", headers: { "Authorization": "Bearer token" }, body: JSON.stringify({ data: "value" }), }); ``` ### Custom Host Routing Dispatches a fetch request with a custom `Host` header. ```js const res = await mf.dispatchFetch("http://localhost:8787/", { headers: { "Host": "api.example.com" }, }); ``` ### Scheduled Event Manually triggers a scheduled event. ```js const worker = await mf.getWorker(); const result = await worker.scheduled({ cron: "30 * * * *" }); // result: { outcome: "ok", noRetry: false } ``` ### Queue Event Manually triggers a queue event. ```js const worker = await mf.getWorker(); const result = await worker.queue("queue-name", [ { id: "msg1", timestamp: new Date(), body: "data", attempts: 1 }, ]); // result: { outcome: "ok", retryAll: false, ackAll: false, ... } ``` ``` -------------------------------- ### Install Agents SDK Source: https://github.com/cloudflare/skills/blob/main/skills/agents-sdk/SKILL.md Install the core agents package. For chat agents, also install `@cloudflare/ai-chat`, `ai`, and `@ai-sdk/react`. ```bash npm ls agents # Should show agents package ``` ```bash npm install agents ``` ```bash npm install agents @cloudflare/ai-chat ai @ai-sdk/react ``` -------------------------------- ### macOS launchd Service Installation Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/tunnel/patterns.md Commands to install and start the cloudflared service on macOS using launchd. ```bash sudo cloudflared service install sudo launchctl start com.cloudflare.cloudflared ``` -------------------------------- ### Initialize New Project with Framework Source: https://github.com/cloudflare/skills/blob/main/skills/wrangler/SKILL.md Initialize a new project with a framework using the create-cloudflare tool. ```bash npx create-cloudflare@latest my-app ``` -------------------------------- ### REST API Example: Get Apps Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/flagship/configuration.md Example cURL command to fetch a list of Flagship apps using the REST API and authenticate with a bearer token. ```bash curl -s -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/flagship/apps" | jq . ``` -------------------------------- ### Post-Creation Checklist Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/c3/patterns.md Essential steps to complete after project creation, including configuration, binding setup, type generation, testing, deployment, and secret management. ```bash 1. Review `wrangler.jsonc` - set `compatibility_date`, verify `name` 2. Create bindings: `wrangler kv namespace create`, `wrangler d1 create`, `wrangler r2 bucket create` 3. Generate types: `npm run cf-typegen` 4. Test: `npm run dev` 5. Deploy: `npm run deploy` 6. Set secrets: `wrangler secret put SECRET_NAME` ``` -------------------------------- ### Linux systemd Service Installation Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/tunnel/patterns.md Commands to install and manage the cloudflared service on Linux systems using systemd. Includes starting the service, enabling it on boot, and viewing logs. ```bash cloudflared service install systemctl start cloudflared && systemctl enable cloudflared journalctl -u cloudflared -f # Logs ``` -------------------------------- ### System Prompt for Documentation Assistant Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/ai-search/patterns.md Define a system prompt to guide the AI's behavior. This example instructs the AI to answer only based on context and include code examples. ```typescript const systemPrompt = `You are a documentation assistant. - Answer ONLY based on provided context - If context doesn't contain answer, say "I don't have information" - Include code examples from context`; ``` -------------------------------- ### Basic RealtimeKit Client Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/realtimekit/patterns.md Initialize the RealtimeKit client with authentication and enable video and audio. Listen for room join events and participant join events. ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken, video: true, audio: true }); meeting.self.on('roomJoined', () => console.log('Joined:', meeting.meta.meetingTitle)); meeting.participants.joined.on('participantJoined', (p) => console.log(`${p.name} joined`)); await meeting.join(); ``` -------------------------------- ### MQTT Protocol Example (CONNECT/PUBLISH) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers-vpc/patterns.md Illustrates the initial bytes for MQTT CONNECT and PUBLISH packets. Full MQTT implementation requires handling many more details. ```typescript const socket = connect({ hostname: "mqtt.broker", port: 1883 }); const writer = socket.writable.getWriter(); // CONNECT: 0x10 0x00 0x04 "MQTT" 0x04 ... // PUBLISH: 0x30 ``` -------------------------------- ### Expression Syntax Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/waf/api.md Guide to constructing expressions for rules, including available fields, operators, and examples. ```APIDOC ## Expression Syntax ### Fields Commonly used fields for constructing expressions: - **Request properties** - `http.request.method` (string) - e.g., GET, POST - `http.request.uri.path` (string) - e.g., /api/users - `http.host` (string) - e.g., example.com - **IP and Geolocation** - `ip.src` (string) - e.g., 192.0.2.1 - `ip.geoip.country` (string) - e.g., US, GB - `ip.geoip.continent` (string) - e.g., NA, EU - **Attack detection** - `cf.waf.score` (integer) - 0-100 attack score - `cf.waf.score.sqli` (integer) - SQL injection score - `cf.waf.score.xss` (integer) - XSS score - **Headers & Cookies** - `http.request.headers["authorization"][0]` (string) - `http.request.cookies["session"][0]` (string) - `lower(http.user_agent)` (string) - Lowercase user agent ### Operators Operators used for comparisons and logical operations: - **Comparison** - `eq` (Equal) - `ne` (Not equal) - `lt` (Less than) - `le` (Less than or equal) - `gt` (Greater than) - `ge` (Greater than or equal) - **String matching** - `contains` (Substring match) - `matches` (Regex match - use carefully) - `starts_with` (Prefix match) - `ends_with` (Suffix match) - **List operations** - `in` (Value in list) - `not` (Logical NOT) - `and` (Logical AND) - `or` (Logical OR) ### Expression Examples Examples of valid expressions: - `'cf.waf.score gt 40'` - `'http.request.uri.path eq "/api/login" and http.request.method eq "POST"'` - `'ip.src in {192.0.2.0/24 203.0.113.0/24}'` - `'ip.geoip.country in {"CN" "RU" "KP"}'` - `'http.user_agent contains "bot"'` - `'not http.request.headers["authorization"][0]'` - `'(cf.waf.score.sqli gt 20 or cf.waf.score.xss gt 20) and http.request.uri.path starts_with "/api"'` ``` -------------------------------- ### Setup Cloudflare Pipelines Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pipelines/README.md Interactively set up a stream, sink, and pipeline. Optionally creates a bucket and catalog. ```bash npx wrangler pipelines setup ``` -------------------------------- ### Start Local Development Server Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare-email-service/references/cli-and-mcp.md Run this command to start the local development server with the configured settings, including real email sending if enabled. ```bash npx wrangler dev ``` -------------------------------- ### Example: GitHub Template Project Creation Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/c3/api.md Creates a new project from a specified GitHub template repository. ```bash # GitHub template npm create cloudflare@latest -- --template=cloudflare/templates/worker-openapi ``` -------------------------------- ### Startup Methods Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/containers/api.md Methods to start and manage the container lifecycle, including waiting for ports to be ready. ```APIDOC ## Startup Methods ### start() - Basic start (8s timeout) ```typescript await container.start(); await container.start({ envVars: { KEY: "value" } }); ``` Returns when **process starts**, NOT when ports ready. Use for fire-and-forget. ### startAndWaitForPorts() - Recommended (20s timeout) ```typescript await container.startAndWaitForPorts(); // Uses requiredPorts await container.startAndWaitForPorts({ ports: [8080, 9090] }); await container.startAndWaitForPorts({ ports: [8080], startOptions: { envVars: { KEY: "value" } } }); ``` Returns when **ports listening**. Use before HTTP/TCP requests. **Port resolution:** explicit ports → requiredPorts → defaultPort → port 33 ### waitForPort() - Wait for specific port ```typescript await container.waitForPort(8080); await container.waitForPort(8080, { timeout: 30000 }); ``` ``` -------------------------------- ### R2 Bucket Binding Example Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pages-functions/api.md Demonstrates using the R2 object storage binding to get and put files. This example retrieves a file, checks for its existence, and then uploads new content to the same file. Ensure an R2 bucket is bound to your Worker. ```typescript interface Env { BUCKET: R2Bucket; } export const onRequest: PagesFunction = async (ctx) => { const obj = await ctx.env.BUCKET.get('file.txt'); if (!obj) return new Response('Not found', { status: 404 }); await ctx.env.BUCKET.put('file.txt', ctx.request.body); return new Response(obj.body); }; ``` -------------------------------- ### Example: Astro Blog Deployment Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/c3/api.md Creates a new Astro web application with TypeScript and immediately deploys it. ```bash # Astro blog npm create cloudflare@latest my-blog -- --type=web-app --framework=astro --ts --deploy ``` -------------------------------- ### GraphQL Analytics API - TypeScript/JavaScript Client Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/graphql-api/configuration.md Example of setting up a client to query the GraphQL Analytics API using TypeScript/JavaScript. ```APIDOC ## Client Setup - TypeScript / JavaScript ### Function to Query GraphQL ```typescript const GRAPHQL_ENDPOINT = "https://api.cloudflare.com/client/v4/graphql"; async function queryGraphQL(query: string, variables: Record = {}): Promise { const response = await fetch(GRAPHQL_ENDPOINT, { method: "POST", headers: { Authorization: `Bearer ${process.env.CF_API_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ query, variables }), }); if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`); const json = await response.json() as { data: T | null; errors?: { message: string }[] }; if (json.errors?.length) throw new Error(json.errors.map((e) => e.message).join("; ")); return json.data!; } ``` **Note**: Ensure your API token is stored securely, for example, in an environment variable `CF_API_TOKEN`. ``` -------------------------------- ### Complete Example Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers-vpc/api.md Demonstrates a full cycle of connecting to a TCP service, sending data, receiving a response, and closing the connection. ```APIDOC ## Complete Example ```typescript import { connect } from 'cloudflare:sockets'; export default { async fetch(req: Request): Promise { const socket = connect({ hostname: "echo.example.com", port: 7 }, { secureTransport: "on" }); try { await socket.opened; const writer = socket.writable.getWriter(); await writer.write(new TextEncoder().encode("Hello, TCP!\n")); await writer.close(); const reader = socket.readable.getReader(); const { value } = await reader.read(); return new Response(value); } finally { await socket.close(); } } }; ``` See [patterns.md](./patterns.md) for multi-chunk reading, error handling, and protocol implementations. ``` -------------------------------- ### Custom Routing with getAgentByName Source: https://github.com/cloudflare/skills/blob/main/skills/agents-sdk/references/routing.md Implement custom routing logic to fetch specific agents by name. This example routes requests starting with '/api/' to a 'singleton' agent. ```typescript import { getAgentByName } from "agents"; export default { async fetch(req, env) { const url = new URL(req.url); if (url.pathname.startsWith("/api/")) { const agent = getAgentByName(env.MyAgent, "singleton"); return agent.fetch(req); } return routeAgentRequest(req, env); } }; ``` -------------------------------- ### Client Provider Setup (Browser) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/flagship/configuration.md Configure the FlagshipClientProvider for browser environments. It pre-fetches flags on initialization for synchronous evaluation. ```typescript import { OpenFeature } from "@openfeature/web-sdk"; import { FlagshipClientProvider } from "@cloudflare/flagship"; await OpenFeature.setProviderAndWait( new FlagshipClientProvider({ appId: "", accountId: "", authToken: "", prefetchFlags: ["promo-banner", "dark-mode", "max-uploads"], }), ); await OpenFeature.setContext({ targetingKey: "user-42", plan: "enterprise" }); const client = OpenFeature.getClient(); ``` -------------------------------- ### Decision Tree: Routing Strategy Selection Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers-for-platforms/README.md A decision tree to guide the selection of an appropriate routing strategy for different hostname requirements in a Workers for Platforms setup. ```text Hostname routing needed? ├─ Subdomains only (*.saas.com) → `*.saas.com/*` route + subdomain extraction ├─ Custom domains → `*/*` wildcard + Cloudflare for SaaS + KV/metadata routing └─ Path-based (/customer/app) → Any route + path parsing ``` -------------------------------- ### SDK Setup Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/waf/api.md Initialize the Cloudflare SDK client with your API token. ```APIDOC ## SDK Setup ### Description Initialize the Cloudflare SDK client with your API token. ### Request Example ```typescript import Cloudflare from 'cloudflare'; const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN, }); ``` ``` -------------------------------- ### Email Routing Configuration Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/agents-sdk/configuration.md Configure email handling for your worker. This example shows how to route incoming emails to an agent using `routeAgentEmail` and includes the necessary dashboard setup. ```typescript import { routeAgentEmail } from "agents"; export default { fetch: (req: Request, env: Env) => routeAgentRequest(req, env), email: (message: ForwardableEmailMessage, env: Env) => { return routeAgentEmail(message, env); } } ``` ```plaintext Destination: Workers with Durable Objects Worker: my-agents-app ``` ```typescript export class EmailAgent extends Agent { async onEmail(email: AgentEmail) { const text = await email.text(); // Process email } } ``` -------------------------------- ### Redis RESP Protocol Example Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers-vpc/patterns.md Demonstrates sending a basic Redis GET command using the RESP (REdis Serialization Protocol). Note that raw protocol handling can be complex. ```typescript // Send: *2\r\n$3\r\nGET\r\n$\r\n\r\n // Recv: $\r\n\r\n or $-1\r\n for null const socket = connect({ hostname: "redis.internal", port: 6379 }); const writer = socket.writable.getWriter(); await writer.write(new TextEncoder().encode(`*2\r\n$3\r\nGET\r\n$3\r\nkey\r\n`)); ``` -------------------------------- ### Create Cloudflare Project (Interactive) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/c3/README.md Use this command for an interactive setup of a new Cloudflare project. Recommended for first-time users. ```bash npm create cloudflare@latest my-app ``` -------------------------------- ### Python SDK for Spectrum Applications Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/spectrum/api.md Provides examples for managing Spectrum applications using the Cloudflare Python SDK, covering create, list, get, update, delete, and analytics operations. ```python from cloudflare import Cloudflare client = Cloudflare(api_token="your-api-token") # Create app = client.spectrum.apps.create( zone_id="your-zone-id", protocol="tcp/22", dns={"type": "CNAME", "name": "ssh.example.com"}, origin_direct=["tcp://192.0.2.1:22"], ip_firewall=True, tls="off", ) # List apps = client.spectrum.apps.list(zone_id="your-zone-id") # Get app_details = client.spectrum.apps.get(zone_id="your-zone-id", app_id=app.id) # Update client.spectrum.apps.update(zone_id="your-zone-id", app_id=app.id, tls="full") # Delete client.spectrum.apps.delete(zone_id="your-zone-id", app_id=app.id) # Analytics analytics = client.spectrum.analytics.aggregate( zone_id="your-zone-id", metrics=["bytesIngress", "bytesEgress"], since=datetime.now() - timedelta(hours=1), ) ``` -------------------------------- ### Sync KV Operations (SQLite) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/do-storage/api.md Performs synchronous Key-Value store operations, including get, put, delete, and list. Supports listing with options like start, prefix, reverse, and limit. ```typescript this.ctx.storage.kv.get("counter"); // undefined if missing this.ctx.storage.kv.put("counter", 42); this.ctx.storage.kv.put("user", { name: "Alice", age: 30 }); this.ctx.storage.kv.delete("counter"); // true if existed for (let [key, value] of this.ctx.storage.kv.list()) {} // List options: start, prefix, reverse, limit this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 }); ``` -------------------------------- ### Install Web Components UI Kit Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/realtimekit/configuration.md Install the RealtimeKit package and the generic UI kit for web components using npm. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-ui ``` -------------------------------- ### Pulumi Configuration for Rate Limiting Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/waf/configuration.md Implement rate limiting for API paths using Pulumi with TypeScript. This example configures a rule to block requests to paths starting with '/api' if they exceed a specified threshold. ```typescript // Rate limiting const rateLimiting = new cloudflare.Ruleset('rate-limiting', { zoneId, phase: 'http_ratelimit', rules: [{ action: 'block', expression: 'http.request.uri.path starts_with "/api"', ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requestsPerPeriod: 100, mitigationTimeout: 600, }, }], }); ``` -------------------------------- ### Manual Agent Routing with Durable Objects Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/agents-sdk/configuration.md Advanced method for manually routing requests to Durable Objects. This example shows how to get a stub for a named or random ID Durable Object and forward the request. ```typescript export default { async fetch(request: Request, env: Env) { const url = new URL(request.url); // Named ID (deterministic) const id = env.MyAgent.idFromName("user-123"); // Random ID (from URL param) // const id = env.MyAgent.idFromString(url.searchParams.get("id")); const stub = env.MyAgent.get(id); return stub.fetch(request); } } ``` -------------------------------- ### Binding Configuration Examples Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/wrangler/configuration.md Examples for configuring various types of bindings, including variables, KV namespaces, D1 databases, R2 buckets, Durable Objects, services, queues, Vectorize, Hyperdrive, Workers AI, Workflows, Secrets Store, and Constellation. ```jsonc // Variables { "vars": { "API_URL": "https://api.example.com" } } ``` ```jsonc // KV { "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }] } ``` ```jsonc // D1 { "d1_databases": [{ "binding": "DB", "database_id": "abc-123" }] } ``` ```jsonc // R2 { "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-assets" }] } ``` ```jsonc // Durable Objects { "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter", "script_name": "my-worker" // Required for external DOs }] } } ``` ```jsonc { "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }] } ``` ```jsonc // Service Bindings { "services": [{ "binding": "AUTH", "service": "auth-worker" }] } ``` ```jsonc // Queues { "queues": { "producers": [{ "binding": "TASKS", "queue": "task-queue" }], "consumers": [{ "queue": "task-queue", "max_batch_size": 10 }] } } ``` ```jsonc // Vectorize { "vectorize": [{ "binding": "VECTORS", "index_name": "embeddings" }] } ``` ```jsonc // Hyperdrive (requires nodejs_compat for pg/postgres) { "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "hyper-id" }] } ``` ```jsonc { "compatibility_flags": ["nodejs_compat"] } // For pg/postgres ``` ```jsonc // Workers AI { "ai": { "binding": "AI" } } ``` ```jsonc // Workflows { "workflows": [{ "binding": "WORKFLOW", "name": "my-workflow", "class_name": "MyWorkflow" }] } ``` ```jsonc // Secrets Store (centralized secrets) { "secrets_store": [{ "binding": "SECRETS", "id": "store-id" }] } ``` ```jsonc // Constellation (AI inference) { "constellation": [{ "binding": "MODEL", "project_id": "proj-id" }] } ``` -------------------------------- ### Query Data Presence with R2 SQL Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pipelines/api.md Check if data is present in your R2 table using an R2 SQL query. This example counts all rows in `my_ns.my_table`. Subsequent flushes are faster than the initial setup. ```bash # 3. Data present? (R2 SQL) curl -s -X POST \ "https://api.sql.cloudflarestorage.com/api/v1/accounts/$ACCOUNT_ID/r2-sql/query/$BUCKET" \ -H "Authorization: Bearer $API_TOKEN" -H "Content-Type: application/json" \ -d '{"query": "SELECT COUNT(*) AS total FROM my_ns.my_table"}' ``` -------------------------------- ### Interactive Pipelines Setup with Wrangler Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/pipelines/configuration.md Use this command for the simplest setup, creating a stream, sink, and pipeline. Optionally, it can also create a bucket and catalog. ```bash npx wrangler pipelines setup # creates stream + sink + pipeline, optionally bucket + catalog ``` -------------------------------- ### Handle Nullable KV Values in TypeScript Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/bindings/gotchas.md Cloudflare KV `get()` can return a string or null. Always handle the null case to prevent runtime errors. This example shows how to check for a null value before using it. ```typescript // ❌ Wrong - KV returns string | null const value: string = await env.MY_KV.get('key'); // ✅ Handle null const value = await env.MY_KV.get('key'); if (!value) return new Response('Not found', { status: 404 }); ``` -------------------------------- ### Cloudflare REST API Secret Operations Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/secrets-store/api.md Examples of REST API endpoints for managing secrets within a store, including listing, creating (single/batch), getting metadata, updating, deleting (single/batch), duplicating, and checking quota. ```bash # List GET /accounts/{account_id}/secrets_store/stores/{store_id}/secrets # Create (single) POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets { "name": "my_secret", "value": "secret_value", "scopes": ["workers"], "comment": "Optional" } # Create (batch) POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets [ {"name": "secret_one", "value": "val1", "scopes": ["workers"]}, {"name": "secret_two", "value": "val2", "scopes": ["workers", "ai-gateway"]} ] # Get metadata GET /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} # Update PATCH /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} {"value": "new_value", "comment": "Updated"} # Delete (single) DELETE /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id} # Delete (batch) DELETE /accounts/{account_id}/secrets_store/stores/{store_id}/secrets {"secret_ids": ["id-1", "id-2"]} # Duplicate POST /accounts/{account_id}/secrets_store/stores/{store_id}/secrets/{secret_id}/duplicate {"name": "new_name"} # Quota GET /accounts/{account_id}/secrets_store/quota ``` -------------------------------- ### Example D1 SQL Migration File Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/d1/configuration.md An example SQL file demonstrating the creation of `users` and `posts` tables with primary keys, foreign keys, and indexes. Migration files should be placed in the directory specified by `migrations_dir` in `wrangler.jsonc`. ```sql -- migrations/0001_initial_schema.sql CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT UNIQUE NOT NULL, name TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP, updated_at TEXT DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_users_email ON users(email); CREATE TABLE IF NOT EXISTS posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, title TEXT NOT NULL, content TEXT, published BOOLEAN DEFAULT 0, created_at TEXT DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); CREATE INDEX idx_posts_user_id ON posts(user_id); CREATE INDEX idx_posts_published ON posts(published); ``` -------------------------------- ### Upload and Download Objects with R2 Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/r2/README.md TypeScript examples for uploading and downloading objects using the R2 binding in Cloudflare Workers. The `put` method takes a key, data, and optional httpMetadata, while `get` retrieves an object by key. ```typescript // Upload await env.MY_BUCKET.put(key, data, { httpMetadata: { contentType: 'image/jpeg' } }); // Download const object = await env.MY_BUCKET.get(key); if (object) return new Response(object.body); ``` -------------------------------- ### AI Chat Agent Quick Start Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/agents-sdk/README.md Implement an AI chat interface using the AIChatAgent class. This example demonstrates how to stream responses from an AI model like GPT-4, utilizing message history and an optional onFinish callback. ```typescript import { AIChatAgent } from "@cloudflare/ai-chat"; import { openai } from "@ai-sdk/openai"; export class ChatAgent extends AIChatAgent { async onChatMessage(onFinish) { return this.streamText({ model: openai("gpt-4"), messages: this.messages, onFinish, }); } } ``` -------------------------------- ### Use AI Search in a Cloudflare Worker Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/ai-search/README.md This TypeScript example demonstrates how to use the AI Search binding in a Cloudflare Worker to perform a semantic search and get an AI-generated response. Ensure your AI Search instance is configured and bound correctly. ```typescript export default { async fetch(request, env) { const answer = await env.AI.autorag("my-search-instance").aiSearch({ query: "How do I configure caching?", model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast" }); return Response.json({ answer: answer.response }); } }; ``` -------------------------------- ### Configure Core SDK Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/realtimekit/configuration.md Initialize the RealtimeKit client with authentication token and media configurations, then join the meeting. ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken: '', video: true, audio: true, autoSwitchAudioDevice: true, mediaConfiguration: { video: { width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, screenshare: { width: { max: 1920 }, height: { max: 1080 }, frameRate: { ideal: 15 } } } }); await meeting.join(); ``` -------------------------------- ### Routing Configuration Examples Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/wrangler/configuration.md Examples of how to configure routing for your worker using custom domains, zone names, or workers.dev. ```jsonc // Custom domain (recommended) { "routes": [{ "pattern": "api.example.com", "custom_domain": true }] } ``` ```jsonc // Zone-based { "routes": [{ "pattern": "api.example.com/*", "zone_name": "example.com" }] } ``` ```jsonc // workers.dev { "workers_dev": true } ``` -------------------------------- ### Quick Start: Define a Cloudflare Workflow Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workflows/README.md This example demonstrates the basic structure of a Cloudflare Workflow using TypeScript. It extends `WorkflowEntrypoint` and defines a `run` method to orchestrate steps like fetching user data, sleeping for a duration, and sending a reminder. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; type Env = { MY_WORKFLOW: Workflow; DB: D1Database }; type Params = { userId: string }; export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { const user = await step.do('fetch user', async () => { return await this.env.DB.prepare('SELECT * FROM users WHERE id = ?') .bind(event.payload.userId).first(); }); await step.sleep('wait 7 days', '7 days'); await step.do('send reminder', async () => { await sendEmail(user.email, 'Reminder!'); }); } } ``` -------------------------------- ### Server Provider Setup with App ID (Node.js) Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/flagship/configuration.md Configure the FlagshipServerProvider for non-Worker runtimes like Node.js. Requires an API token with read permissions. ```typescript import { OpenFeature } from "@openfeature/server-sdk"; import { FlagshipServerProvider } from "@cloudflare/flagship"; await OpenFeature.setProviderAndWait( new FlagshipServerProvider({ appId: "", accountId: "", authToken: "", }), ); const client = OpenFeature.getClient(); ``` -------------------------------- ### Configure Rate Limiting with TypeScript SDK Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/waf/configuration.md Implement rate limiting for specific API paths using the Cloudflare TypeScript SDK. This example blocks requests to paths starting with '/api' if they exceed 100 requests per minute per source. ```typescript // Rate limiting await client.rulesets.create({ zone_id: process.env.ZONE_ID, phase: 'http_ratelimit', rules: [{ action: 'block', expression: 'http.request.uri.path starts_with "/api"', action_parameters: { ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requests_per_period: 100, mitigation_timeout: 600, }, }, }], }); ``` -------------------------------- ### Durable Objects RPC Pattern for State Management Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/workers/api.md Implements a Durable Object using the RPC pattern for type-safe, zero-serialization communication. The `Counter` example demonstrates managing state (`value`) stored persistently. Worker usage involves getting a stub and calling methods directly. ```typescript export class Counter { private value = 0; constructor(private state: DurableObjectState) { state.blockConcurrencyWhile(async () => { this.value = (await state.storage.get('value')) || 0; }); } // Export methods directly - called via RPC (type-safe, zero serialization) async increment(): Promise { this.value++; await this.state.storage.put('value', this.value); return this.value; } async getValue(): Promise { return this.value; } } // Worker usage: const stub = env.COUNTER.get(env.COUNTER.idFromName('global')); const count = await stub.increment(); // Direct method call, full type safety ``` -------------------------------- ### Multi-Environment Configuration with Wrangler Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/email-routing/configuration.md Example configuration files for managing different environments (dev and prod) and deploying using specific configs. ```bash # wrangler.dev.jsonc { "name": "worker-dev", "vars": { "ENV": "dev" } } # wrangler.prod.jsonc { "name": "worker-prod", "vars": { "ENV": "prod" } } npx wrangler deploy --config wrangler.dev.jsonc npx wrangler deploy --config wrangler.prod.jsonc ``` -------------------------------- ### Example: Convert Existing Project Source: https://github.com/cloudflare/skills/blob/main/skills/cloudflare/references/c3/api.md Converts an existing project by specifying the type as 'pre-existing' and providing the path to the worker script. ```bash # Convert existing project npm create cloudflare@latest . -- --type=pre-existing --existing-script=./build/worker.js ```