Technical Documentation: midudev/autoskills
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
Scans your project, detects your tech stack, and installs curated AI agent skills automatically.
npx autoskillsHow it works
- Run
npx autoskillsin your project root - Your
package.json, Gradle files, and config files are scanned to detect technologies - The best matching AI agent skills are selected from the audited autoskills registry
- Only the selected skill files are downloaded from the registry and verified before writing them locally
That's it. No config needed.
Security model
autoskills does not install directly from random upstream repositories at runtime.
Skills are synced by maintainers into the repository-local autoskills registry, reviewed by AI for prompt-injection and supply-chain attacks (a fast model triages every change and a stronger one decides on anything suspicious), and recorded with SHA-256 hashes in a manifest. Skills that are safe but worth a heads-up are shown with a security warning before you install them. When you run autoskills, the CLI downloads only the skills your project needs from that curated registry, verifies every file against the manifest, and writes a skills-lock.json entry with the installed source and bundle hash.
This keeps the package small while avoiding live downloads from third-party skill sources during installation.
Options
-y, --yes Skip confirmation prompt
--dry-run Show what would be installed without installing
--clear-cache Clear the downloaded skills cache
-a, --agent Install for specific IDEs only (e.g. cursor claude-code)
-v, --verbose Show install trace and error details
-h, --help Show help messageRun npx autoskills ui to browse the skills installed in your project in a local web desk.
Supported Technologies
Built to work across modern frontend, backend, mobile, cloud, and media stacks.
- Frameworks & UI: React, Next.js, Vue, Nuxt, Svelte, Angular, Astro, Tailwind CSS, shadcn/ui, GSAP, Three.js
- Languages & Runtimes: TypeScript, Node.js, Go, Bun, Dart
- Backend & APIs: Express, Hono, NestJS, Spring Boot
- Mobile & Desktop: Expo, React Native, Flutter, SwiftUI, Android, Kotlin Multiplatform, Tauri, Electron
- Data & Storage: Supabase, Neon, Prisma, Drizzle ORM, Zod, React Hook Form
- Auth & Billing: Better Auth, Clerk, Stripe
- Testing: Vitest, Playwright
- Cloud & Infrastructure: Vercel, Vercel AI SDK, Cloudflare, Durable Objects, Cloudflare Agents, Cloudflare AI, AWS, Azure, Terraform
- Tooling: Turborepo, Vite, oxlint
- Media & AI: Remotion, ElevenLabs
Requirements
Node.js >= 22.6
License
Overview (`packages/autoskills/README.md`)
autoskills
Auto-detect and install the best AI agent skills for your project. One command, zero config.
npx autoskillsautoskills scans your project, detects the technologies you use, and installs curated AI agent skills that make Cursor, Claude Code, and other AI coding assistants actually understand your stack.
Quick Start
Run it in your project root:
npx autoskillsThat's it. It will:
- Scan your
package.json, config files, and project structure - Detect every technology in your stack
- Show an interactive selector with the best skills for your project
- Install them in parallel with live progress
- Generate
CLAUDE.mdautomatically when Claude Code is one of the target agents
Skip the prompt
npx autoskills -yPreview without installing
npx autoskills --dry-runBrowse installed skills
npx autoskills uiOpens a local desk (bound to 127.0.0.1) to browse the skills installed in the current project.
Claude Code summary
If claude-code is auto-detected or passed with -a, autoskills writes a CLAUDE.md file in your project root summarizing the markdown files installed under .claude/skills.
Options
| Flag | Description |
|---|---|
-y, --yes |
Skip confirmation prompt, install all detected skills |
--dry-run |
Show detected skills without installing anything |
--clear-cache |
Clear the downloaded skills cache |
-a, --agent |
Install for specific IDEs only (e.g. cursor claude-code) |
-v, --verbose |
Show install trace and error details |
-h, --help |
Show help message |
autoskills ui also accepts --port <number> and --no-open.
Supported Technologies
autoskills detects 50+ technologies from your package.json, lockfiles, Gradle files, and config files:
Frameworks & Libraries
| Technology | Detected from |
|---|---|
| React | react, react-dom packages |
| Next.js | next package or next.config.* |
| Vue | vue package |
| Nuxt | nuxt package or nuxt.config.* |
| Svelte | svelte, @sveltejs/kit or svelte.config.js |
| Angular | @angular/core or angular.json |
| Astro | astro package or astro.config.* |
| Expo | expo package |
| React Native | react-native package |
| Flutter | pubspec.yaml file with flutter: key |
| Kotlin Multiplatform | Gradle with KMP plugin: kotlin("multiplatform"), org.jetbrains.kotlin.multiplatform, or kotlin-multiplatform in gradle/libs.versions.toml |
| Android | Gradle with com.android.application, com.android.library, or com.android.kotlin.multiplatform.library |
| Remotion | remotion, @remotion/cli |
| GSAP | gsap package |
| Three.js | three, @react-three/fiber, @react-three/drei |
| Express | express package |
| Hono | hono package |
| NestJS | @nestjs/core package |
| Spring Boot | Gradle with spring-boot-starter or org.springframework.boot |
| ASP.NET Core | .csproj file with Microsoft.NET.Sdk.Web |
| Blazor | .csproj with Microsoft.NET.Sdk.BlazorWebAssembly or Microsoft.AspNetCore.Components |
| ASP.NET Minimal API | .csproj with Microsoft.AspNetCore.OpenApi or Swashbuckle.AspNetCore |
Styling & UI
| Technology | Detected from |
|---|---|
| Tailwind CSS | tailwindcss, @tailwindcss/vite or tailwind.config.* |
| shadcn/ui | components.json |
Runtimes & Tooling
| Technology | Detected from |
|---|---|
| TypeScript | typescript package or tsconfig.json |
| Node.js | package-lock.json, yarn.lock, pnpm-lock.yaml, .nvmrc |
| Bun | bun.lockb, bun.lock, bunfig.toml |
| Dart | pubspec.yaml |
| Go | go.mod, go.work |
| Vite | vite package or vite.config.* |
| Turborepo | turbo package or turbo.json |
| Vitest | vitest package or vitest.config.* |
| oxlint | oxlint package or .oxlintrc.json |
| .NET | global.json, NuGet.Config, *.csproj, *.sln |
| C# | *.csproj, *.sln |
Backend & Data
| Technology | Detected from |
|---|---|
| Supabase | @supabase/supabase-js, @supabase/ssr |
| Zod | zod package |
| React Hook Form | react-hook-form package |
| Neon Postgres | @neondatabase/serverless |
| Prisma | prisma, @prisma/client |
| Drizzle ORM | drizzle-orm, drizzle-kit |
| Stripe | stripe, @stripe/stripe-js, @stripe/react-stripe-js |
| Better Auth | better-auth package |
Authentication
| Technology | Detected from |
|---|---|
| Clerk | @clerk/nextjs, @clerk/react, @clerk/expo, @clerk/astro, @clerk/remix, @clerk/vue, or any @clerk/* scope |
Cloud & Deploy
| Technology | Detected from |
|---|---|
| Vercel | vercel.json, .vercel/, @astrojs/vercel |
| Cloudflare | wrangler, wrangler.toml, @astrojs/cloudflare |
| Cloudflare Agents | agents package |
| Cloudflare AI | @cloudflare/ai or AI binding in wrangler.json |
| Durable Objects | durable_objects in wrangler.json/wrangler.toml |
| Azure | @azure/* packages |
| AWS | @aws-sdk/*, aws-cdk* packages |
AI
| Technology | Detected from |
|---|---|
| Vercel AI SDK | ai, @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google |
| ElevenLabs | elevenlabs package |
Other
| Technology | Detected from |
|---|---|
| Playwright | @playwright/test, playwright or playwright.config.* |
| SwiftUI | Package.swift |
| WordPress | wp-config.php, @wordpress/*, composer.json with wpackagist, theme style.css |
| Tauri | @tauri-apps/api, @tauri-apps/cli or src-tauri/tauri.conf.json |
| Electron | electron package, electron-builder.yml, forge.config.js, or electron-vite.config.ts |
Web Frontend Detection
Even without a framework, autoskills scans your file tree for web frontend signals (.html, .css, .scss, .vue, .svelte, .jsx, .tsx, .twig, .blade.php, etc.) and installs skills for frontend design, accessibility, and SEO.
Combo Detection
When multiple technologies are used together, autoskills detects technology combos and adds specialized skills for the combination:
- Next.js + Supabase — Supabase Postgres best practices for Next.js
- Next.js + Vercel AI SDK — AI SDK patterns with Next.js
- Next.js + Playwright — E2E testing best practices for Next.js
- React + shadcn/ui — shadcn component patterns with React
- Tailwind CSS + shadcn/ui — Tailwind v4 + shadcn integration
- React Native + Expo — Native UI patterns
- React Hook Form + Zod — Form validation patterns with Zod schemas
- GSAP + React — GSAP animation patterns in React
- Cloudflare + Vite — Vinext migration guide
- Node.js + Express — Express server patterns
How It Works
Skills are markdown files that teach AI assistants how to work with specific technologies, following best practices and patterns from the official maintainers. autoskills installs them from its own curated registry: maintainers sync them from their upstream repositories (the ones listed on skills.sh), an AI security review blocks anything that attacks the user or plants a serious vulnerability, and every file is recorded with a SHA-256 hash that the CLI verifies before writing it.
The detection runs entirely locally with zero network requests until installation begins.
Requirements
- Node.js >= 22.6.0
License
CC-BY-NC-4.0 — Created by @midudev
Overview (`packages/autoskills/skills-registry/composition-patterns/README.md`)
React Composition Patterns
A structured repository for React composition patterns that scale. These
patterns help avoid boolean prop proliferation by using compound components,
lifting state, and composing internals.
Structure
rules/- Individual rule files (one per rule)_sections.md- Section metadata (titles, impacts, descriptions)_template.md- Template for creating new rulesarea-description.md- Individual rule files
metadata.json- Document metadata (version, organization, abstract)AGENTS.md- Compiled output (generated)
Rules
Component Architecture (CRITICAL)
architecture-avoid-boolean-props.md- Don't add boolean props to customize
behaviorarchitecture-compound-components.md- Structure as compound components with
shared context
State Management (HIGH)
state-lift-state.md- Lift state into provider componentsstate-context-interface.md- Define clear context interfaces
(state/actions/meta)state-decouple-implementation.md- Decouple state management from UI
Implementation Patterns (MEDIUM)
patterns-children-over-render-props.md- Prefer children over renderX propspatterns-explicit-variants.md- Create explicit component variants
Core Principles
- Composition over configuration — Instead of adding props, let consumers
compose - Lift your state — State in providers, not trapped in components
- Compose your internals — Subcomponents access context, not props
- Explicit variants — Create ThreadComposer, EditComposer, not Composer
with isThread
Creating a New Rule
- Copy
rules/_template.mdtorules/area-description.md - Choose the appropriate area prefix:
architecture-for Component Architecturestate-for State Managementpatterns-for Implementation Patterns
- Fill in the frontmatter and content
- Ensure you have clear examples with explanations
Impact Levels
CRITICAL- Foundational patterns, prevents unmaintainable codeHIGH- Significant maintainability improvementsMEDIUM- Good practices for cleaner code
Overview (`packages/autoskills/skills-registry/react-best-practices/README.md`)
React Best Practices
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
Structure
rules/- Individual rule files (one per rule)_sections.md- Section metadata (titles, impacts, descriptions)_template.md- Template for creating new rulesarea-description.md- Individual rule files
src/- Build scripts and utilitiesmetadata.json- Document metadata (version, organization, abstract)AGENTS.md- Compiled output (generated)test-cases.json- Test cases for LLM evaluation (generated)
Getting Started
Install dependencies:
bashpnpm installBuild AGENTS.md from rules:
bashpnpm buildValidate rule files:
bashpnpm validateExtract test cases:
bashpnpm extract-tests
Creating a New Rule
- Copy
rules/_template.mdtorules/area-description.md - Choose the appropriate area prefix:
async-for Eliminating Waterfalls (Section 1)bundle-for Bundle Size Optimization (Section 2)server-for Server-Side Performance (Section 3)client-for Client-Side Data Fetching (Section 4)rerender-for Re-render Optimization (Section 5)rendering-for Rendering Performance (Section 6)js-for JavaScript Performance (Section 7)advanced-for Advanced Patterns (Section 8)
- Fill in the frontmatter and content
- Ensure you have clear examples with explanations
- Run
pnpm buildto regenerate AGENTS.md and test-cases.json
Rule File Structure
Each rule file should follow this structure:
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect (description of what's wrong):**
```typescript
// Bad code exampleCorrect (description of what's right):
// Good code exampleOptional explanatory text after examples.
Reference: Link
File Naming Convention
- Files starting with
_are special (excluded from build) - Rule files:
area-description.md(e.g.,async-parallel.md) - Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build
Impact Levels
CRITICAL- Highest priority, major performance gainsHIGH- Significant performance improvementsMEDIUM-HIGH- Moderate-high gainsMEDIUM- Moderate performance improvementsLOW-MEDIUM- Low-medium gainsLOW- Incremental improvements
Scripts
pnpm build- Compile rules into AGENTS.mdpnpm validate- Validate all rule filespnpm extract-tests- Extract test cases for LLM evaluationpnpm dev- Build and validate
Contributing
When adding or modifying rules:
- Use the correct filename prefix for your section
- Follow the
_template.mdstructure - Include clear bad/good examples with explanations
- Add appropriate tags
- Run
pnpm buildto regenerate AGENTS.md and test-cases.json - Rules are automatically sorted by title - no need to manage numbers!
Acknowledgments
Originally created by @shuding at Vercel.
Overview (`packages/autoskills/skills-registry/react-hook-form/README.md`)
React Hook Form Best Practices Skill
Corrective guidance for React Hook Form — the decisions that go wrong by default.
Overview
This skill provides 35 rules across 7 categories. Every rule names a decision that a capable model gets wrong by default; rules that merely restated correct library behaviour were removed in 2.0.0. Verified against react-hook-form 7.82.0 (July 2026), with every code block type-checked under tsc --strict against the real package types.
Directory Structure
react-hook-form/
├── SKILL.md # Entry point with quick reference
├── AGENTS.md # Compiled comprehensive guide (TOC over references/)
├── metadata.json # Version, org, references
├── README.md # This file
├── assets/
│ └── templates/
│ └── _template.md # Rule template
└── references/
├── _sections.md # Category definitions and impact ordering
├── formcfg-*.md # Form configuration rules (9)
├── sub-*.md # Field subscription rules (7)
├── ctrl-*.md # Controlled component rules (2)
├── valid-*.md # Validation pattern rules (4)
├── formstate-*.md # State management rules (6)
├── array-*.md # Field array rules (4)
└── integ-*.md # Integration pattern rules (3)Validating
This skill is validated by the repo-level tooling, not by per-skill scripts:
npm run validate # structural validation of every skill
node /path/to/dev-skill/scripts/validate-skill.js . # discipline-aware validation of this skillCreating a New Rule
- Choose the appropriate category prefix:
| Category | Prefix | Impact |
|---|---|---|
| Form Configuration | formcfg- |
CRITICAL |
| Field Subscription | sub- |
CRITICAL |
| Controlled Components | ctrl- |
HIGH |
| Validation Patterns | valid- |
HIGH |
| State Management | formstate- |
MEDIUM-HIGH |
| Field Arrays | array- |
MEDIUM-HIGH |
| Integration Patterns | integ- |
MEDIUM |
Create a new file:
references/{prefix}-{slug}.mdUse the rule template from
assets/templates/_template.mdAdd the rule to the SKILL.md quick reference and to the AGENTS.md table of contents (entries are ordered alphabetically by title within each section).
Rule File Structure
---
title: Rule Title Here
impact: CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW
impactDescription: What the rule prevents or enables
tags: prefix, keyword1, keyword2
---
## Rule Title Here
Brief explanation of WHY this matters (1-3 sentences).
**Incorrect (description of problem):**
\`\`\`typescript
// Bad code with comment on key line
\`\`\`
**Correct (description of solution):**
\`\`\`typescript
// Good code with minimal diff from incorrect
\`\`\`
Reference: [Documentation Link](https://example.com)File Naming Convention
Rules follow the pattern: {prefix}-{slug}.md
- prefix: Category identifier from
_sections.md(lowercase letters only) - slug: Kebab-case description of the rule
Examples:
formcfg-validation-mode.mdsub-usewatch-over-watch.mdctrl-usecontroller-isolation.md
Impact Levels
| Level | Description |
|---|---|
| CRITICAL | Cascade effect on entire form performance |
| HIGH | Significant impact on specific operations |
| MEDIUM-HIGH | Notable improvement for common patterns |
| MEDIUM | Measurable improvement in specific scenarios |
| LOW-MEDIUM | Minor optimization for edge cases |
| LOW | Best practice with minimal performance impact |
Companion Skill
react-hook-form-audit is a static-analysis skill that detects violations of these rules in a Next.js App Router codebase and links each finding back to the corresponding file in references/.
Contributing
- Read existing rules in the same category for style consistency
- Ensure incorrect/correct examples have minimal diff
- Typecheck every example against the pinned react-hook-form version before committing
- Include authoritative reference links
- Run validation before submitting
Acknowledgments
Based on official React Hook Form documentation, the library's shipped type definitions, and community best practices.
Overview (`packages/autoskills/skills-registry/tauri-v2/README.md`)
Tauri v2+ Development Skill
Build cross-platform desktop and mobile apps with web frontends and Rust backends.
| Status | Active |
| Version | 1.0.1 |
| Last Updated | 2026-04-02 |
| Confidence | 4/5 |
| Production Tested | https://v2.tauri.app/ |
What This Skill Does
Provides expert assistance for Tauri v2 application development, covering the full development lifecycle from project setup to cross-platform deployment. Specializes in Rust backend commands, IPC patterns, security configuration, and frontend-backend communication.
Core Capabilities
- Implement Rust commands with
#[tauri::command]and proper error handling - Configure IPC patterns (invoke, events, channels) for frontend-backend communication
- Set up security capabilities and permissions for plugins and APIs
- Access exhaustive reference docs for plugins (fs, dialog, shell, store, etc.), updater/distribution signing, and advanced runtime (tray, sidecars, deep links)
- Build and deploy for desktop (macOS, Windows, Linux) and mobile (iOS, Android)
- Integrate Vite + TanStack Router frontends with Tauri backends
- Configure tauri.conf.json and Cargo.toml for cross-platform builds
Auto-Trigger Keywords
Primary Keywords
Exact terms that strongly trigger this skill:
- tauri
- tauri v2
- tauri.conf.json
- src-tauri
- #[tauri::command]
- tauri::invoke
- capabilities.json
Secondary Keywords
Related terms that may trigger in combination:
- rust backend
- desktop app
- cross-platform app
- webview
- invoke command
- emit event
- app permissions
- bundle desktop
Error-Based Keywords
Common error messages that should trigger this skill:
- "Command not found"
- "Permission denied" (in Tauri context)
- "Failed to invoke command"
- "Missing capability"
- "Cannot read property of undefined" (invoke result)
- "tauri build failed"
- "Missing Rust target"
Known Issues Prevention
| Issue | Root Cause | Solution |
|---|---|---|
| Command not found | Missing from generate_handler![] |
Register all commands in the macro |
| Permission denied | Missing capability configuration | Add required permissions to capabilities file |
| State access panic | Type mismatch in State<T> |
Use exact type matching .manage() call |
| White screen | Frontend not building | Verify beforeDevCommand and devUrl |
| Mobile build fails | Missing Rust targets | Run rustup target add <platform-targets> |
| IPC timeout | Blocking in async command | Use non-blocking async or spawn threads |
When to Use
Use This Skill For
- Creating new Tauri v2 projects or commands
- Configuring permissions and capabilities
- Setting up IPC (invoke, events, channels)
- Debugging command invocation issues
- Cross-platform build configuration
- Plugin integration and configuration
- Mobile (iOS/Android) deployment setup
Don't Use This Skill For
- Tauri v1 development (use migration guide then this skill)
- Pure frontend development without Tauri integration
- Native mobile development (Swift/Kotlin directly)
- Backend API development without Tauri
Version Policy
[!NOTE]
This skill targets Tauri v2+. Feature availability may vary across minor versions. When exact version timing matters, check the official Tauri changelog and release notes fortauri,@tauri-apps/api,@tauri-apps/cli, and relevant plugins.
Quick Usage
# Create new Tauri project
npm create tauri-app@latest
# Add Tauri to existing project
npm install -D @tauri-apps/cli@latest
npx tauri init
# Development
npm run tauri dev
# Production build
npm run tauri build
# Add a plugin (e.g., fs, dialog, store)
cargo tauri add fs # Adds tauri-plugin-fs to Cargo.toml + JS package
cargo tauri add dialog
cargo tauri add store
# Mobile development
cargo tauri android init # One-time setup
cargo tauri android dev # Run on Android
cargo tauri android build # Release build
cargo tauri ios init # One-time setup (macOS only)
cargo tauri ios dev # Run on iOS simulator
cargo tauri ios build # Release buildToken Efficiency
| Approach | Estimated Tokens | Time |
|---|---|---|
| Manual Implementation | ~15,000 | 2+ hours |
| With This Skill | ~6,000 | 30 min |
| Savings | 60% | ~1.5 hours |
Reference Documentation
For deep-dive guidance on specific topics, see the following reference files:
| Topic | Reference File | Purpose |
|---|---|---|
| Security & Permissions | capabilities-reference.md |
V2 security model, capability files, permissions, and scopes |
| IPC Patterns | ipc-patterns.md |
Decision framework for Commands, Events, and Channels |
| Official Plugins | plugin-reference.md |
Install, registration, and permissions for all official plugins |
| Updater & Distribution | updater-distribution-reference.md |
Signing, updater setup, and platform-specific distribution |
| Advanced Runtime | advanced-runtime-reference.md |
Tray icons, sidecars, deep links, and custom protocols |
See the References Index for a complete navigation guide.
File Structure
tauri-v2/
├── SKILL.md # Quick-start patterns, core rules, critical guidance
├── README.md # This file - discovery and quick reference
└── references/ # Deep-dive reference documentation
├── README.md # Index and navigation
├── capabilities-reference.md # Security model, permissions, scopes
├── ipc-patterns.md # Commands, events, channels decision framework
├── plugin-reference.md # Exhaustive plugin install/register/permissions
├── updater-distribution-reference.md # Signing, HTTPS, platform distribution
└── advanced-runtime-reference.md # Tray, sidecars, deep links, protocolsDependencies
| Package | Version | Verified |
|---|---|---|
@tauri-apps/cli |
^2 (v2+) | 2026-04-02* |
@tauri-apps/api |
^2 (v2+) | 2026-04-02* |
tauri (Rust) |
^2 (v2+) | 2026-04-02* |
tauri-build (Rust) |
^2 (v2+) | 2026-04-02* |
*Last verified: 2026-04-02. Always check official changelog for feature timing.
Official Documentation
- Tauri v2+ Documentation
- Commands Reference
- IPC Concepts
- Capabilities & Permissions
- Configuration Reference
- Plugin Directory
Related Skills
tanstack-start-expert- TanStack Router patterns for type-safe frontend routingreact-component-architect- React component patterns for Tauri frontendsgo-google-style-expert- Alternative backend patterns (if using Go instead)
Companion Agent (Deprecated)
The tauri-v2-expert agent at .claude/agents/specialized/tauri/tauri-v2-expert.md is deprecated/legacy. This skill is the preferred and actively maintained interface. Use this skill over the agent for all new Tauri v2 work.
License: MIT
Overview (`packages/autoskills/skills-registry/zod/README.md`)
Zod Best Practices Skill
A comprehensive guide for using Zod effectively in TypeScript applications. This skill provides 42 rules across 8 categories, organized by impact to help AI agents and developers write better validation code.
Overview
Zod is a TypeScript-first schema declaration and validation library. This skill covers best practices for:
- Schema Definition: Choosing correct types, avoiding
z.any(), proper string validations - Parsing & Validation: Using
safeParse(), async validation, error handling - Type Inference: Leveraging
z.infer, distinguishing input/output types - Error Handling: Custom messages, internationalization, form error display
- Object Schemas: strict/strip modes, partial updates, discriminated unions
- Schema Composition: Reusable schemas, intersections, recursive types
- Refinements & Transforms: Custom validation, data transformation
- Performance: Caching, Zod Mini, lazy loading, batch validation
Usage
For Claude Code / AI Agents
The skill is automatically loaded when working with Zod code. Reference specific rules:
See rules/parse-use-safeparse.md for safeParse best practicesFor Developers
Read SKILL.md for a quick reference, or AGENTS.md for the full compiled guide.
File Structure
zod/
├── SKILL.md # Quick reference with rule index
├── AGENTS.md # Full compiled guide (all rules)
├── metadata.json # Version, categories, references
├── README.md # This file
└── rules/
├── _sections.md # Category definitions
├── _template.md # Rule template
├── schema-*.md # Schema definition rules
├── parse-*.md # Parsing rules
├── type-*.md # Type inference rules
├── error-*.md # Error handling rules
├── object-*.md # Object schema rules
├── compose-*.md # Composition rules
├── refine-*.md # Refinement rules
└── perf-*.md # Performance rulesRule Categories
| Priority | Category | Rules | Impact |
|---|---|---|---|
| 1 | Schema Definition | 6 | CRITICAL |
| 2 | Parsing & Validation | 6 | CRITICAL |
| 3 | Type Inference | 5 | HIGH |
| 4 | Error Handling | 5 | HIGH |
| 5 | Object Schemas | 6 | MEDIUM-HIGH |
| 6 | Schema Composition | 5 | MEDIUM |
| 7 | Refinements & Transforms | 5 | MEDIUM |
| 8 | Performance & Bundle | 5 | LOW-MEDIUM |
Key Principles
- Type Safety First: Always use
z.infer, never duplicate types manually - Validate at Boundaries: Parse external data immediately at entry points
- User-Friendly Errors: Provide custom messages, collect all issues
- Single Source of Truth: Schema defines validation AND TypeScript types
- Composition Over Duplication: Use extend, pick, omit, partial
References
Overview (`packages/autoskills/skills-registry/django-expert/references/README.md`)
Django Expert - Reference Documentation
This directory contains comprehensive Django best practices documentation that
will be loaded into the active AI coding agent's context when needed.
Purpose
Reference files provide detailed guidelines, patterns, and examples that would
make SKILL.md too long (>5k words). The agent will read these files as needed
based on the specific Django task at hand.
Recommended Reference Files
Create the following markdown files in this directory to provide comprehensive Django guidance:
1. `models-and-orm.md` - Model Design & ORM Best Practices
Topics to cover:
- Model field types and when to use each
- Database relationships (ForeignKey, ManyToMany, OneToOne)
- Model Meta options (ordering, indexes, constraints)
- Custom model methods and properties
- Model managers and custom querysets
- Database query optimization (select_related, prefetch_related, only, defer)
- Common ORM patterns and anti-patterns
- Migration best practices
- Database indexing strategies
Example structure:
# Django Models and ORM Best Practices
## Model Design Patterns
### Field Choices
- Use TextChoices or IntegerChoices for Django 3.0+
- Keep choices close to the model definition
[detailed examples...]
## Query Optimization
### N+1 Query Problem
[explanation and solutions...]
### Using select_related vs prefetch_related
[detailed guidance with examples...]2. `views-and-urls.md` - Views, URLs, and Request Handling
Topics to cover:
- Function-based views vs class-based views
- When to use generic CBVs (ListView, DetailView, CreateView, etc.)
- Custom mixins and view composition
- URL patterns and routing best practices
- Request/response handling
- Middleware usage
- Context processors
- Form handling in views
- Error handling and custom error pages
3. `drf-guidelines.md` - Django REST Framework Best Practices
Topics to cover:
- Serializer patterns (ModelSerializer, nested serializers, write-only fields)
- ViewSets vs APIView vs function-based views
- Permissions and authentication
- Filtering, searching, and pagination
- Versioning strategies
- Custom actions and decorators
- Response formatting
- Error handling in APIs
- Testing DRF endpoints
4. `testing-strategies.md` - Testing Django Applications
Topics to cover:
- Test organization and structure
- TestCase vs TransactionTestCase
- Factory patterns and fixtures
- Mocking external services
- Testing models, views, and APIs
- Testing permissions and authentication
- Database testing best practices
- Coverage and test performance
- Integration vs unit testing
5. `security-checklist.md` - Django Security Best Practices
Topics to cover:
- CSRF protection
- XSS prevention
- SQL injection prevention
- Authentication and authorization
- Password handling and storage
- Secure settings for production
- HTTPS and SSL/TLS configuration
- Content Security Policy
- Rate limiting and throttling
- Security headers
- Common vulnerabilities and mitigations
6. `performance-optimization.md` - Performance and Scaling
Topics to cover:
- Database query optimization
- Caching strategies (per-view cache, template fragment cache, low-level cache)
- Redis/Memcached integration
- Database connection pooling
- Async views and background tasks (Celery)
- Static file optimization
- Database indexing and query profiling
- Monitoring and profiling tools
- Pagination strategies for large datasets
How to Populate These Files
- Research: Gather Django best practices from official docs, style guides, and community resources
- Structure: Use clear headings, code examples, and explanations
- Examples: Include both good and bad examples with explanations
- Keep Updated: Maintain version-specific guidance (note Django version compatibility)
- Be Specific: Provide concrete examples rather than general statements
Example Reference File
Here's an example of what a well-structured reference file looks like:
# Django REST Framework Guidelines
## Serializer Best Practices
### 1. Use ModelSerializer for Standard CRUD
For basic model serialization, always start with ModelSerializer:
```python
# Good
from rest_framework import serializers
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'price', 'category']
read_only_fields = ['id', 'created_at']2. Nested Serializers for Relationships
For related objects, use nested serializers or use depth:
# Option 1: Nested serializer (more control)
class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True, read_only=True)
class Meta:
model = Order
fields = ['id', 'items', 'total']
# Option 2: Auto-nesting with depth (simpler but less control)
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
depth = 1 # Be careful with performance[Continue with more patterns...]
## Usage
Compatible agents automatically read these files when working on Django tasks.
You don't need to manually reference them—the active agent will determine which
references are needed based on the task.
## Notes
- Keep files focused on specific topics (don't create one giant file)
- Use code examples liberally
- Include both do's and don'ts
- Reference Django and DRF version numbers when relevant
- Link to official documentation for deep dives
---
### Overview (`packages/autoskills/skills-registry/tauri-v2/references/README.md`)
# Tauri v2 References
Deep-dive reference documentation for Tauri v2 development. Use these when the main [`SKILL.md`](../SKILL.md) quick-start isn't enough.
## Reference Files
| File | Description | Key Topics |
|------|-------------|------------|
| [`capabilities-reference.md`](capabilities-reference.md) | **Security & Permissions** | Capability files, permissions, scopes, v1 vs v2 model |
| [`ipc-patterns.md`](ipc-patterns.md) | **IPC Decision Framework** | Commands vs Events vs Channels, typed `Channel<T>` |
| [`plugin-reference.md`](plugin-reference.md) | **Official Plugins** | Registration, JS package, and required capability permissions |
| [`updater-distribution-reference.md`](updater-distribution-reference.md) | **Updater & Distribution** | Signing, HTTPS endpoints, macOS/Windows/Linux packaging |
| [`advanced-runtime-reference.md`](advanced-runtime-reference.md) | **Advanced Runtime** | `TrayIconBuilder`, sidecars, deep links, custom protocols |
## Navigation Guide
- **New to Tauri v2 security?** → Start with [`capabilities-reference.md`](capabilities-reference.md) to understand the mandatory capability model.
- **Choosing an IPC method?** → See [`ipc-patterns.md`](ipc-patterns.md) for the "Commands vs Events vs Channels" decision matrix.
- **Adding a plugin?** → Check [`plugin-reference.md`](plugin-reference.md) for the specific permission strings you MUST add to your capabilities.
- **Shipping to production?** → See [`updater-distribution-reference.md`](updater-distribution-reference.md) for mandatory signing and update server requirements.
- **Tray icons, sidecars, or deep links?** → See [`advanced-runtime-reference.md`](advanced-runtime-reference.md) for v2-specific implementations.
*Last verified: 2026-04-02. Check [official Tauri changelog](https://github.com/tauri-apps/tauri/blob/dev/crates/tauri/CHANGELOG.md) for updates.*
---
### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/README.md`)
# Recipes
Deployment recipes for different infrastructure approaches.
| Recipe | When to Use |
|--------|-------------|
| [AZD](azd/README.md) | Projects using Azure Developer CLI |
| [AZCLI](azcli/README.md) | Projects using Azure CLI scripts |
| [Bicep](bicep/README.md) | Projects using Bicep templates |
| [Terraform](terraform/README.md) | Projects using Terraform |
| [CI/CD](cicd/README.md) | Pipeline-based deployments |
---
### Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/app-service/README.md`)
# App Service Troubleshooting
> **Request to "collect"/"gather" diagnostics?** Once the app name and resource
> group are known from the request or existing context, run the
> [`appservice-diagnostics`](../../scripts/appservice-diagnostics.sh) script
> ([PowerShell](../../scripts/appservice-diagnostics.ps1)) directly as your first action —
> don't verify the app/resource group exists with separate calls first, and don't substitute
> the individual commands below for it. It's read-only and reports clearly if the
> resource can't be found. Ask only for identifiers that remain missing. See "Combined
> Diagnostic Script" below for usage.
## Common Issues Matrix
| Symptom | Likely Cause | Action |
|---------|--------------|-----------|
| High CPU / memory | Runaway process, inefficient code | Use Process Explorer via Kudu, scale up |
| Deployment failure | Build error, locked files, quota | Check Kudu logs at `https://APP.scm.azurewebsites.net/api/deployments` to look for details on build errors, locked files or lack of storage quota |
| App crash / restart | Unhandled exception, OOM kill | Review Event Log and STDERR in Diagnose & Solve |
| Slow responses | Downstream dependency, no caching | Enable request tracing, check dependency calls |
| 502 / 503 errors | App not starting, port conflict | Check STDERR logs, verify startup command |
| TLS / domain errors | Certificate expired, DNS mismatch | `az webapp config ssl list`, verify CNAME |
| Health check failure | Endpoint not returning 200 | Verify health check path responds within 2 min |
---
## High CPU / Memory Diagnosis
**Diagnose:**
```bash
# Check app metrics
az monitor metrics list --resource APP_RESOURCE_ID \
--metric "CpuPercentage,MemoryPercentage" --interval PT1M --output table
# View running processes via ARM Processes API (Entra ID auth)
az rest --method get \
--uri "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/sites/<app-name>/processes?api-version=2024-04-01"Fix: Scale up (az appservice plan update -n <app-service-plan-name> -g <resource-group> --sku P1V3) or profile the app via Kudu Process Explorer at https://APP.scm.azurewebsites.net/ProcessExplorer/ to identify hot paths.
Deployment Failure Analysis
Diagnose:
# List deployment history
az webapp deployment list -n APP -g RG --output table
# View deployment log for a specific deployment
az webapp log deployment show -n APP -g RG --deployment-id DEPLOY_ID
# Stream build logs from Kudu
az webapp log tail -n APP -g RGKQL — Failed deployments:
// Replace <app-service-resource-id> with the full resource ID, for example:
// /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/sites/<app-name>
AppServicePlatformLogs
| where TimeGenerated > ago(24h)
| where Level == "Error" and _ResourceId == "<app-service-resource-id>"
| project TimeGenerated, Level, Message
| order by TimeGenerated descCommon deployment failures:
| Error Message | Cause | Fix |
|---|---|---|
WEBSITE_RUN_FROM_PACKAGE=1 but no package |
Missing zip deploy artifact | Redeploy with az webapp deploy --src-path app.zip |
Error building on server |
Oryx build failure | Check build logs, pin runtime version |
Locked file during deploy |
Files in use | Set an environment variable named MSDEPLOY_RENAME_LOCKED_FILES=1 on the App Service resource to enable MSDeploy to rename locked files. |
Application Crash / Restart Diagnosis
Diagnose:
# Check recent restarts via activity log
az monitor activity-log list -g RG --resource-id APP_RESOURCE_ID \
--max-events 10 --query "[?operationName.value=='Microsoft.Web/sites/restart/action']"
# View STDERR/STDOUT (Linux)
az webapp log download -n APP -g RG --log-file logs.zipKQL — App crashes and errors:
AppServiceConsoleLogs
| where TimeGenerated > ago(1h)
| where ResultDescription contains "error" or ResultDescription contains "fatal"
| project TimeGenerated, ResultDescription
| order by TimeGenerated desc
| take 50Health check failures:
# Show health check config
az webapp show -n APP -g RG --query "siteConfig.healthCheckPath"
# Test the endpoint directly
curl -s -o /dev/null -w "%{http_code}" https://APP.azurewebsites.net/health⚠️ Warning: If the health check fails on >50% of instances for 1 hour, the instance is replaced.
Slow Response Time Investigation
Diagnose:
# Check average response time
az monitor metrics list --resource APP_RESOURCE_ID \
--metric "HttpResponseTime" --interval PT5M --aggregation Average --output table
# Enable failed request tracing
az webapp log config -n APP -g RG --failed-request-tracing trueKQL — Slow requests with dependency analysis:
AppServiceHTTPLogs
| where TimeGenerated > ago(1h)
| where TimeTaken > 5000
| project TimeGenerated, CsUriStem, ScStatus, TimeTaken, CsHost
| order by TimeTaken desc
| take 20Auto-Heal — Automatic mitigation:
# Configure auto-heal to recycle on slow requests
az webapp config set -n APP -g RG \
--auto-heal-enabled true \
--generic-configurations '{"autoHealRules":{"triggers":{"slowRequests":{"timeTaken":"00:00:30","count":10,"timeInterval":"00:02:00"}},"actions":{"actionType":"Recycle"}}}'Custom Domain / TLS Certificate Issues
Diagnose:
# List custom domains
az webapp config hostname list -g RG --webapp-name APP --output table
# List TLS certificates
az webapp config ssl list -g RG --output table
# Check SSL binding
az webapp config ssl show --certificate-name CERT -g RG| Symptom | Cause | Fix |
|---|---|---|
ERR_CERT_DATE_INVALID |
Certificate expired | If certificate came from an external certificate authority, renew with az webapp config ssl upload and upload a new certificate or enable managed certificates to allow Azure to provide a free TLS/SSL certificate |
DNS_PROBE_FINISHED_NXDOMAIN |
CNAME not configured | Add CNAME record pointing to APP.azurewebsites.net |
SSL binding not found |
Missing SNI binding | Add the missing SNI binding using az webapp config ssl bind --certificate-thumbprint THUMB --ssl-type SNI -n APP -g RG |
| Managed cert pending | DNS validation incomplete | Verify TXT record asuid.DOMAIN matches custom domain verification ID |
AZ CLI or MCP Tools for App Service Diagnostics
| Tool | Command | Use When |
|---|---|---|
Azure CLI |
az webapp list |
List all web apps in subscription |
Azure CLI |
az webapp show -n APP -g RG |
Get app config, stack, status |
Azure CLI |
az webapp config appsettings list -n APP -g RG |
Check env vars and connection strings |
Azure CLI |
az webapp deployment slot list -n APP -g RG |
Compare slot configurations |
mcp_azure_mcp_appservice |
appservice_webapp_diagnostic_diagnose |
AI-powered root cause analysis |
mcp_azure_mcp_monitor |
monitor_resource_log_query |
Run KQL against Log Analytics |
mcp_azure_mcp_resourcehealth |
get |
Check platform-level health status |
💡 Tip: Start with
mcp_azure_mcp_appservice(diagnose) — it automatically runs relevant detectors and surfaces the most likely root cause before you dig into logs manually.
Combined Diagnostic Script
Use the appservice-diagnostics script
(PowerShell) to collect everything in one call.
It prints clearly labeled sections — app config, recent deployments, app settings, and
custom domains — and a summary line describing what it collected. Interpreting the output
remains your job.
..\..\scripts\appservice-diagnostics.ps1 -Name <app> -ResourceGroup <rg>../../scripts/appservice-diagnostics.sh --name <app> --resource-group <rg>Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/container-apps/README.md`)
Container Apps Troubleshooting
Request to "collect"/"gather" diagnostics? Once the app name and resource
group are known from the request or existing context, run thecontainerapp-diagnosticsscript
(PowerShell) directly as your first action —
don't verify the app/resource group exists with separate calls first, and don't substitute
the individual commands below for it. It's read-only and reports clearly if the
resource can't be found. Ask only for identifiers that remain missing. See "Get All
Diagnostic Info" below for usage.
Common Issues Matrix
| Symptom | Likely Cause | Quick Fix |
|---|---|---|
| Image pull failure | ACR credentials missing | az containerapp registry set --identity system |
| ACR build fails | ACR Tasks disabled (free sub) | Build locally with Docker |
| Cold start timeout | min-replicas=0 | az containerapp update --min-replicas 1 |
| Port mismatch | Wrong target port | Check Dockerfile EXPOSE matches ingress |
| App keeps restarting | Health probe failing | Verify /health endpoint |
Image Pull Failures
Diagnose:
# Check registry configuration
az containerapp show --name APP -g RG --query "properties.configuration.registries"
# Check revision status
az containerapp revision list --name APP -g RG --output tableFix:
az containerapp registry set \
--name APP -g RG \
--server ACR.azurecr.io \
--identity systemACR Tasks Disabled (Free Subscriptions)
Symptom: az acr build fails with "ACR Tasks is not supported"
Fix: Build locally instead:
docker build -t ACR.azurecr.io/myapp:v1 .
az acr login --name ACR
docker push ACR.azurecr.io/myapp:v1Cold Start Issues
Symptom: First request very slow or times out
Fix:
az containerapp update --name APP -g RG --min-replicas 1Health Probe Failures
Symptom: Container keeps restarting
Check:
# View health probe config
az containerapp show --name APP -g RG --query "properties.configuration.ingress"
# Check if /health endpoint responds
curl https://APP.REGION.azurecontainerapps.io/healthFix: Ensure app has health endpoint returning 200:
app.get('/health', (req, res) => res.sendStatus(200));Port Mismatch
Symptom: App starts but returns 502/503
Check:
az containerapp show --name APP -g RG --query "properties.configuration.ingress.targetPort"Verify: App must listen on this exact port. Check:
- Dockerfile
EXPOSEstatement process.env.PORTor hardcoded port in app
View Logs
# Stream logs (wait for replicas if scale-to-zero)
az containerapp logs show --name APP -g RG --follow
# Recent logs
az containerapp logs show --name APP -g RG --tail 100
# System logs (startup issues)
az containerapp logs show --name APP -g RG --type systemGet All Diagnostic Info
Use the containerapp-diagnostics script
(PowerShell) to collect everything in one
call. It prints clearly labeled sections — revisions, registry config, ingress config, and
recent logs — and a summary line describing what it collected. Interpreting the output
remains your job.
..\..\scripts\containerapp-diagnostics.ps1 -Name <app> -ResourceGroup <rg>../../scripts/containerapp-diagnostics.sh --name <app> --resource-group <rg>Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/functions/README.md`)
Function Apps Troubleshooting
Find Linked App Insights / Log Analytics
Preferred: Use Azure Resource Graph
A single ARG query returns the App Insights name, instrumentation key, connection string, and Log Analytics workspace for a given function app:
az graph query -q "
resources | where type =~ 'microsoft.web/sites' and name == '<func-app-name>'
| project funcName=name, rg=resourceGroup
| join kind=inner (resources | where type =~ 'microsoft.insights/components' | project appiName=name, rg=resourceGroup, instrumentationKey=properties.InstrumentationKey, connectionString=properties.ConnectionString, workspaceId=properties.WorkspaceResourceId) on rg
| project funcName, appiName, instrumentationKey, connectionString, workspaceId
" -o json💡 Tip: This join matches by resource group. If App Insights is in a different resource group, use the CLI fallback below.
Fallback: CLI Commands
Step 1: Get the App Insights connection string from app settings
az functionapp config appsettings list \
--name <func-app-name> -g <rg-name> \
--query "[?name=='APPLICATIONINSIGHTS_CONNECTION_STRING' || name=='APPINSIGHTS_INSTRUMENTATIONKEY']"Step 2: Find the App Insights resource by instrumentation key
az monitor app-insights component show \
--query "[?instrumentationKey=='<key>'] | [0].{name:name, rg:resourceGroup, workspaceId:workspaceResourceId}"Step 3: Find the Log Analytics workspace
az monitor app-insights component show --app <appinsights-name> -g <rg-name> \
--query "workspaceResourceId" -o tsvConfirm logs are flowing
Query App Insights traces table to verify the function app is sending telemetry:
az monitor app-insights query --apps <appinsights-name> -g <rg-name> \
--analytics-query "traces | where operation_Name != '' | take 1 | project timestamp, operation_Name, message"For FunctionAppLogs (available in Log Analytics only, not App Insights), query the workspace directly:
az monitor log-analytics query -w <workspace-guid> \
--analytics-query "FunctionAppLogs | where _ResourceId contains '<func-app-name>' | take 5 | project TimeGenerated, FunctionName, Message, Level"⚠️ Classic App Insights: Some function apps use classic App Insights without a linked Log Analytics workspace (
workspaceIdis null). In this case,FunctionAppLogsis not available — use thetraces,requests, andexceptionstables viaaz monitor app-insights queryinstead. As a last resort,az webapp log tail --name <func-app-name> -g <rg-name>can stream live logs directly.
If results are returned, logs are flowing. If empty, verify the APPLICATIONINSIGHTS_CONNECTION_STRING app setting matches this App Insights instance.
⚠️ Always prefer querying App Insights or Log Analytics for function app logs.
az webapp log tailcan stream live logs directly but App Insights provides richer data, historical queries, and correlation across requests.
💡 Tip: App Insights logs can be delayed by a few minutes. If you don't see recent data, wait 3-5 minutes and query again.
Check Recent Deployments
Correlate issues with recent deployments by listing deployment history:
az rest --method get \
--uri "/subscriptions/<subscription-id>/resourceGroups/<rg-name>/providers/Microsoft.Web/sites/<func-app-name>/deployments?api-version=2023-12-01"Compare deployment timestamps against when errors started appearing in App Insights to identify if a deployment caused the issue.
Trigger & Durable Function Troubleshooting
- Trigger & Binding Troubleshooting - HTTP, Timer, Queue, Blob, Service Bus, and Cosmos DB trigger diagnostics, plus Flex Consumption specifics and SDK conflicts.
- Durable Functions Troubleshooting - stuck orchestrations, non-determinism violations, timeout/cancellation patterns, and task hub conflicts.
Overview (`packages/autoskills/skills-registry/azure-diagnostics/troubleshooting/messaging/README.md`)
Azure Messaging Troubleshooting
Diagnose and resolve issues with Azure Event Hubs and Service Bus SDKs.
Routing
| Symptom | Guide |
|---|---|
| Connection failures, firewall, IP/VNet, WebSocket | service-troubleshooting.md |
| SDK-specific errors (see language below) | Language guide |
SDK Troubleshooting by Language
Common Issues
| Issue | Category |
|---|---|
| AMQP link detach, idle timeout, connection inactive | service-troubleshooting.md |
| Message lock lost/expired, lock renewal failures | Language-specific SDK guide |
| Session lock errors, session receiver detach | Language-specific SDK guide |
| Duplicate events, checkpoint/offset reset | Language-specific SDK guide |
| Batch >1 MB rejected, partition key conflicts | service-troubleshooting.md |
MCP Tools
| Tool | Use |
|---|---|
mcp_azure_mcp_eventhubs |
List namespaces, hubs, consumer groups |
mcp_azure_mcp_servicebus |
List namespaces, queues, topics, subscriptions |
mcp_azure_mcp_monitor |
Query diagnostic logs with KQL |
mcp_azure_mcp_resourcehealth |
Check service health status |
mcp_azure_mcp_documentation |
Search Microsoft Learn for troubleshooting docs |
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/agents-sdk/README.md`)
Cloudflare Agents SDK
Cloudflare Agents SDK enables building AI-powered agents on Durable Objects with state, WebSockets, SQL, scheduling, and AI integration.
Core Value
Build stateful, globally distributed AI agents with persistent memory, real-time connections, scheduled tasks, and async workflows.
When to Use
- Persistent state + memory required
- Real-time WebSocket connections
- Long-running workflows (minutes/hours)
- Chat interfaces with AI models
- Scheduled/recurring tasks with state
- DB queries with agent state
What Type of Agent?
| Use Case | Class | Key Features |
|---|---|---|
| AI chat interface | AIChatAgent |
Auto-streaming, tools, message history, resumable |
| MCP tool provider | Agent + MCP |
Expose tools to AI systems |
| Custom logic/routing | Agent |
Full control, WebSockets, email, SQL |
| Real-time collaboration | Agent |
WebSocket state, broadcasts |
| Email processing | Agent |
onEmail() handler |
Quick Start
AI Chat Agent:
import { AIChatAgent } from "agents";
import { openai } from "@ai-sdk/openai";
export class ChatAgent extends AIChatAgent<Env> {
async onChatMessage(onFinish) {
return this.streamText({
model: openai("gpt-4"),
messages: this.messages,
onFinish,
});
}
}Base Agent:
import { Agent } from "agents";
export class MyAgent extends Agent<Env> {
onStart() {
this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)`;
}
async onRequest(request: Request) {
return Response.json({ state: this.state });
}
}Reading Order
| Task | Files to Read |
|---|---|
| Quick start | README only |
| Build chat agent | README → api.md (AIChatAgent) → patterns.md |
| Setup project | README → configuration.md |
| Add React frontend | README → api.md (Client Hooks) → patterns.md |
| Build MCP server | api.md (MCP) → patterns.md |
| Background tasks | api.md (Scheduling, Task Queue) → patterns.md |
| Debug issues | gotchas.md |
Package Entry Points
| Import | Purpose |
|---|---|
agents |
Server-side Agent classes, lifecycle |
agents/react |
useAgent() hook for WebSocket connections |
agents/ai-react |
useAgentChat() hook for AI chat UIs |
In This Reference
- configuration.md - SDK setup, wrangler config, routing
- api.md - Agent classes, lifecycle, client hooks
- patterns.md - Common workflows, best practices
- gotchas.md - Common issues, limits
See Also
- durable-objects - Agent infrastructure
- d1 - External database integration
- workers-ai - AI model integration
- vectorize - Vector search for RAG patterns
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ai-gateway/README.md`)
Cloudflare AI Gateway
Expert guidance for implementing Cloudflare AI Gateway - a universal gateway for AI model providers with analytics, caching, rate limiting, and routing capabilities.
When to Use This Reference
- Setting up AI Gateway for any AI provider (OpenAI, Anthropic, Workers AI, etc.)
- Implementing caching, rate limiting, or request retry/fallback
- Configuring dynamic routing with A/B testing or model fallbacks
- Managing provider API keys securely with BYOK
- Adding security features (guardrails, DLP)
- Setting up observability with logging and custom metadata
- Debugging AI Gateway requests or optimizing configurations
Quick Start
What's your setup?
- Using Vercel AI SDK → Pattern 1 (recommended) - see sdk-integration.md
- Using OpenAI SDK → Pattern 2 - see sdk-integration.md
- Cloudflare Worker + Workers AI → Pattern 3 - see sdk-integration.md
- Direct HTTP (any language) → Pattern 4 - see configuration.md
- Framework (LangChain, etc.) → See sdk-integration.md
Pattern 1: Vercel AI SDK (Recommended)
Most modern pattern using official ai-gateway-provider package with automatic fallbacks.
import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';
const gateway = createAiGateway({
accountId: process.env.CF_ACCOUNT_ID,
gateway: process.env.CF_GATEWAY_ID,
});
const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Single model
const { text } = await generateText({
model: gateway(openai('gpt-4o')),
prompt: 'Hello'
});
// Automatic fallback array
const { text } = await generateText({
model: gateway([
openai('gpt-4o'), // Try first
anthropic('claude-sonnet-4-5'), // Fallback
]),
prompt: 'Hello'
});Install: npm install ai-gateway-provider ai @ai-sdk/openai @ai-sdk/anthropic
Pattern 2: OpenAI SDK
Drop-in replacement for OpenAI API with multi-provider support.
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/compat`,
defaultHeaders: {
'cf-aig-authorization': `Bearer ${cfToken}` // For authenticated gateways
}
});
// Switch providers by changing model format: {provider}/{model}
const response = await client.chat.completions.create({
model: 'openai/gpt-4o', // or 'anthropic/claude-sonnet-4-5'
messages: [{ role: 'user', content: 'Hello!' }]
});Pattern 3: Workers AI Binding
For Cloudflare Workers using Workers AI.
export default {
async fetch(request, env, ctx) {
const response = await env.AI.run(
'@cf/meta/llama-3-8b-instruct',
{ messages: [{ role: 'user', content: 'Hello!' }] },
{
gateway: {
id: 'my-gateway',
metadata: { userId: '123', team: 'engineering' }
}
}
);
return Response.json(response);
}
};Headers Quick Reference
| Header | Purpose | Example | Notes |
|---|---|---|---|
cf-aig-authorization |
Gateway auth | Bearer {token} |
Required for authenticated gateways |
cf-aig-metadata |
Tracking | {"userId":"x"} |
Max 5 entries, flat structure |
cf-aig-cache-ttl |
Cache duration | 3600 |
Seconds, min 60, max 2592000 (30 days) |
cf-aig-skip-cache |
Bypass cache | true |
- |
cf-aig-cache-key |
Custom cache key | my-key |
Must be unique per response |
cf-aig-collect-log |
Skip logging | false |
Default: true |
cf-aig-cache-status |
Cache hit/miss | Response only | HIT or MISS |
In This Reference
| File | Purpose |
|---|---|
| sdk-integration.md | Vercel AI SDK, OpenAI SDK, Workers binding patterns |
| configuration.md | Dashboard setup, wrangler, API tokens |
| features.md | Caching, rate limits, guardrails, DLP, BYOK, unified billing |
| dynamic-routing.md | Fallbacks, A/B testing, conditional routing |
| troubleshooting.md | Debugging, errors, observability, gotchas |
Reading Order
| Task | Files |
|---|---|
| First-time setup | README + configuration.md |
| SDK integration | README + sdk-integration.md |
| Enable caching | README + features.md |
| Setup fallbacks | README + dynamic-routing.md |
| Debug errors | README + troubleshooting.md |
Architecture
AI Gateway acts as a proxy between your application and AI providers:
Your App → AI Gateway → AI Provider (OpenAI, Anthropic, etc.)
↓
Analytics, Caching, Rate Limiting, LoggingKey URL patterns:
- Unified API (OpenAI-compatible):
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat/chat/completions - Provider-specific:
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/{provider}/{endpoint} - Dynamic routes: Use route name instead of model:
dynamic/{route-name}
Gateway Types
- Unauthenticated Gateway: Open access (not recommended for production)
- Authenticated Gateway: Requires
cf-aig-authorizationheader with Cloudflare API token (recommended)
Provider Authentication Options
- Unified Billing: Use AI Gateway billing to pay for inference (keyless mode - no provider API key needed)
- BYOK (Store Keys): Store provider API keys in Cloudflare dashboard
- Request Headers: Include provider API key in each request
Related Skills
- Workers AI - For
env.AI.run()details - Agents SDK - For stateful AI patterns
- Vectorize - For RAG patterns with embeddings
Resources
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ai-search/README.md`)
Cloudflare AI Search Reference
Expert guidance for implementing Cloudflare AI Search (formerly AutoRAG), Cloudflare's managed semantic search and RAG service.
Overview
AI Search is a managed RAG (Retrieval-Augmented Generation) pipeline that combines:
- Automatic semantic indexing of your content
- Vector similarity search
- Built-in LLM generation
Key value propositions:
- Zero vector management - No manual embedding, indexing, or storage
- Auto-indexing - Content automatically re-indexed every 6 hours
- Built-in generation - Optional AI response generation from retrieved context
- Multi-source - Index from R2 buckets or website crawls
Data source options:
- R2 bucket - Index files from Cloudflare R2 (supports MD, TXT, HTML, PDF, DOC, CSV, JSON)
- Website - Crawl and index website content (requires Cloudflare-hosted domain)
Indexing lifecycle:
- Automatic 6-hour refresh cycle
- Manual "Force Sync" available (30s rate limit)
- Not designed for real-time updates
Quick Start
1. Create AI Search instance in dashboard:
- Go to Cloudflare Dashboard → AI Search → Create
- Choose data source (R2 or website)
- Configure instance name and settings
2. Configure Worker:
// wrangler.jsonc
{
"ai": {
"binding": "AI"
}
}3. Use in Worker:
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 });
}
};When to Use AI Search
AI Search vs Vectorize
| Factor | AI Search | Vectorize |
|---|---|---|
| Management | Fully managed | Manual embedding + indexing |
| Use when | Want zero-ops RAG pipeline | Need custom embeddings/control |
| Indexing | Automatic (6hr cycle) | Manual via API |
| Generation | Built-in optional | Bring your own LLM |
| Data sources | R2 or website | Manual insert |
| Best for | Docs, support, enterprise search | Custom ML pipelines, real-time |
AI Search vs Direct Workers AI
| Factor | AI Search | Workers AI (direct) |
|---|---|---|
| Context | Automatic retrieval | Manual context building |
| Use when | Need RAG (search + generate) | Simple generation tasks |
| Indexing | Built-in | Not applicable |
| Best for | Knowledge bases, docs | Simple chat, transformations |
search() vs aiSearch()
| Method | Returns | Use When |
|---|---|---|
search() |
Search results only | Building custom UI, need raw chunks |
aiSearch() |
AI response + results | Need ready-to-use answer (chatbot, Q&A) |
Real-time Updates Consideration
AI Search is NOT ideal if:
- Need real-time content updates (<6 hours)
- Content changes multiple times per hour
- Strict freshness requirements
AI Search IS ideal if:
- Content relatively stable (docs, policies, knowledge bases)
- 6-hour refresh acceptable
- Prefer zero-ops over real-time
Platform Limits
| Limit | Value |
|---|---|
| Max instances per account | 10 |
| Max files per instance | 100,000 |
| Max file size | 4 MB |
| Index frequency | Every 6 hours |
| Force Sync rate limit | Once per 30 seconds |
| Filter nesting depth | 2 levels |
| Filters per compound | 10 |
| Score threshold range | 0.0 - 1.0 |
Reading Order
Navigate these references based on your task:
| Task | Read | Est. Time |
|---|---|---|
| Understand AI Search | README only | 5 min |
| Implement basic search | README → api.md | 10 min |
| Configure data source | README → configuration.md | 10 min |
| Production patterns | patterns.md | 15 min |
| Debug issues | gotchas.md | 10 min |
| Full implementation | README → api.md → patterns.md | 30 min |
In This Reference
- api.md - API endpoints, methods, TypeScript interfaces
- configuration.md - Setup, data sources, wrangler config
- patterns.md - Common patterns, decision guidance, code examples
- gotchas.md - Troubleshooting, code-level gotchas, limits
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/analytics-engine/README.md`)
Cloudflare Workers Analytics Engine Reference
Expert guidance for implementing unlimited-cardinality analytics at scale using Cloudflare Workers Analytics Engine.
What is Analytics Engine?
Time-series analytics database designed for high-cardinality data (millions of unique dimensions). Write data points from Workers, query via SQL API. Use for:
- Custom user-facing analytics dashboards
- Usage-based billing & metering
- Per-customer/per-feature monitoring
- High-frequency instrumentation without performance impact
Key Capability: Track metrics with unlimited unique values (e.g., millions of user IDs, API keys) without performance degradation.
Core Concepts
| Concept | Description | Example |
|---|---|---|
| Dataset | Logical table for related metrics | api_requests, user_events |
| Data Point | Single measurement with timestamp | One API request's metrics |
| Blobs | String dimensions (max 20) | endpoint, method, status, user_id |
| Doubles | Numeric values (max 20) | latency_ms, request_count, bytes |
| Indexes | Filtered blobs for efficient queries | customer_id, api_key |
Reading Order
| Task | Start Here | Then Read |
|---|---|---|
| First-time setup | configuration.md → api.md → patterns.md | |
| Writing data | api.md → gotchas.md (sampling) | |
| Querying data | api.md (SQL API) → patterns.md (examples) | |
| Debugging | gotchas.md → api.md (limits) | |
| Optimization | patterns.md (anti-patterns) → gotchas.md |
When to Use Analytics Engine
Need to track metrics? → Yes
↓
Millions of unique dimension values? → Yes
↓
Need real-time queries? → Yes
↓
Use Analytics Engine ✓
Alternative scenarios:
- Low cardinality (<10k unique values) → Workers Analytics (free tier)
- Complex joins/relations → D1 Database
- Logs/debugging → Tail Workers (logpush)
- External tools → Send to external analytics (Datadog, etc.)Quick Start
- Add binding to
wrangler.jsonc:
{
"analytics_engine_datasets": [
{ "binding": "ANALYTICS", "dataset": "my_events" }
]
}- Write data points (fire-and-forget, no await):
env.ANALYTICS.writeDataPoint({
blobs: ["/api/users", "GET", "200"],
doubles: [145.2, 1], // latency_ms, count
indexes: [customerId]
});- Query via SQL API (HTTP):
SELECT blob1, SUM(double2) AS total_requests
FROM my_events
WHERE index1 = 'customer_123'
AND timestamp >= NOW() - INTERVAL '7' DAY
GROUP BY blob1
ORDER BY total_requests DESCIn This Reference
- configuration.md - Setup, bindings, TypeScript types, limits
- api.md -
writeDataPoint(), SQL API, query syntax - patterns.md - Use cases, examples, anti-patterns
- gotchas.md - Sampling, index selection, troubleshooting
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/api-shield/README.md`)
Cloudflare API Shield Reference
Expert guidance for API Shield - comprehensive API security suite for discovery, protection, and monitoring.
Reading Order
| Task | Files to Read |
|---|---|
| Initial setup | README → configuration.md |
| Implement JWT validation | configuration.md → api.md |
| Add schema validation | configuration.md → patterns.md |
| Detect API attacks | patterns.md → api.md |
| Debug issues | gotchas.md |
Feature Selection
What protection do you need?
├─ Validate request/response structure → Schema Validation 2.0 (configuration.md)
├─ Verify auth tokens → JWT Validation (configuration.md)
├─ Client certificates → mTLS (configuration.md)
├─ Detect BOLA attacks → BOLA Detection (patterns.md)
├─ Track auth coverage → Auth Posture (patterns.md)
├─ Stop volumetric abuse → Abuse Detection (patterns.md)
└─ Discover shadow APIs → API Discovery (api.md)In This Reference
- configuration.md - Setup, session identifiers, rules, token/mTLS configs
- api.md - Endpoint management, discovery, validation APIs, GraphQL operations
- patterns.md - Common patterns, progressive rollout, OWASP mappings, workflows
- gotchas.md - Troubleshooting, false positives, performance, best practices
Quick Start
API Shield: Enterprise-grade API security (Discovery, Schema Validation 2.0, JWT, mTLS, BOLA Detection, Auth Posture). Available as Enterprise add-on with preview access.
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/api/README.md`)
Cloudflare API Integration
Guide for working with Cloudflare's REST API - authentication, SDK usage, common patterns, and troubleshooting.
Quick Decision Tree
How are you calling the Cloudflare API?
├─ From Workers runtime → Use bindings, not REST API (see ../bindings/)
├─ Server-side (Node/Python/Go) → Official SDK (see api.md)
├─ CLI/scripts → Wrangler or curl (see configuration.md)
├─ Infrastructure-as-code → See ../pulumi/ or ../terraform/
└─ One-off requests → curl examples (see api.md)SDK Selection
| Language | Package | Best For | Default Retries |
|---|---|---|---|
| TypeScript | cloudflare |
Node.js, Bun, Next.js, Workers | 2 |
| Python | cloudflare |
FastAPI, Django, scripts | 2 |
| Go | cloudflare-go/v4 |
CLI tools, microservices | 10 |
All SDKs are Stainless-generated from OpenAPI spec (consistent APIs).
Authentication Methods
| Method | Security | Use Case | Scope |
|---|---|---|---|
| API Token ✓ | Scoped, rotatable | Production | Per-zone or account |
| API Key + Email | Full account access | Legacy only | Everything |
| User Service Key | Limited | Origin CA certs only | Origin CA |
Always use API tokens for new projects.
Rate Limits
| Limit | Value |
|---|---|
| Per user/token | 1200 requests / 5 minutes |
| Per IP | 200 requests / second |
| GraphQL | 320 / 5 minutes (cost-based) |
Reading Order
| Task | Files to Read |
|---|---|
| Initialize SDK client | api.md |
| Configure auth/timeout/retry | configuration.md |
| Find usage patterns | patterns.md |
| Debug errors/rate limits | gotchas.md |
| Product-specific APIs | ../workers/, ../r2/, ../kv/, etc. |
In This Reference
- api.md - SDK client initialization, pagination, error handling, examples
- configuration.md - Environment variables, SDK config, Wrangler setup
- patterns.md - Real-world patterns, batch operations, workflows
- gotchas.md - Rate limits, SDK-specific issues, troubleshooting
See Also
- Cloudflare API Docs
- Bindings Reference - Workers runtime bindings (preferred over REST API)
- Wrangler Reference - CLI tool for Cloudflare development
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/argo-smart-routing/README.md`)
Cloudflare Argo Smart Routing Skill Reference
Overview
Cloudflare Argo Smart Routing is a performance optimization service that detects real-time network issues and routes web traffic across the most efficient network path. It continuously monitors network conditions and intelligently routes traffic through the fastest, most reliable routes in Cloudflare's network.
Note on Smart Shield: Argo Smart Routing is being integrated into Cloudflare's Smart Shield product for enhanced DDoS protection and performance. Existing Argo customers maintain full functionality with gradual migration to Smart Shield features.
Quick Start
Enable via cURL
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"value": "on"}'Enable via TypeScript SDK
import Cloudflare from 'cloudflare';
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
const result = await client.argo.smartRouting.edit({
zone_id: 'your-zone-id',
value: 'on',
});
console.log(`Argo enabled: ${result.value}`);Core Concepts
What It Does
- Intelligent routing: Detects congestion, outages, packet loss in real-time
- Global optimization: Routes across 300+ Cloudflare data centers
- Automatic failover: Switches paths when issues detected (typically <1s)
- Works with existing setup: No origin changes required
Billing Model
- Usage-based: Charged per GB of traffic (excluding DDoS/WAF mitigated traffic)
- Requires billing configuration before enabling
- Available on Enterprise+ plans (check zone eligibility)
When to Use
- High-traffic production sites with global user base
- Latency-sensitive applications (APIs, real-time services)
- Sites behind Cloudflare proxy (orange-clouded DNS records)
- Combined with Tiered Cache for maximum performance gains
When NOT to Use
- Development/staging environments (cost control)
- Low-traffic sites (<1TB/month) where cost may exceed benefit
- Sites with primarily single-region traffic
Should I Enable Argo?
| Your Situation | Recommendation |
|---|---|
| Global production app, >1TB/month traffic | ✅ Enable - likely ROI positive |
| Enterprise plan, latency-critical APIs | ✅ Enable - performance matters |
| Regional site, <100GB/month traffic | ⚠️ Evaluate - cost may not justify |
| Development/staging environment | ❌ Disable - use in production only |
| Not yet configured billing | ❌ Configure billing first |
Reading Order by Task
| Your Goal | Start With | Then Read |
|---|---|---|
| Enable Argo for first time | Quick Start above → configuration.md | gotchas.md |
| Use TypeScript/Python SDK | api.md | patterns.md |
| Terraform/IaC setup | configuration.md | - |
| Enable for Spectrum TCP app | patterns.md → Spectrum section | api.md |
| Troubleshoot enablement issue | gotchas.md | api.md |
| Manage billing/usage | patterns.md → Billing section | gotchas.md |
In This Reference
- api.md - API endpoints, SDK methods, error handling, Python/TypeScript examples
- configuration.md - Terraform setup, environment config, billing configuration
- patterns.md - Tiered Cache integration, Spectrum TCP apps, billing management, validation patterns
- gotchas.md - Common errors, permission issues, limits, best practices
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/bindings/README.md`)
Cloudflare Bindings Skill Reference
Expert guidance on Cloudflare Workers Bindings - the runtime APIs that connect Workers to Cloudflare platform resources.
What Are Bindings?
Bindings are how Workers access Cloudflare resources (storage, compute, services) via the env object. They're configured in wrangler.jsonc, type-safe via TypeScript, and zero-overhead at runtime.
Reading Order
- This file - Binding catalog and selection guide
- api.md - TypeScript types and env access patterns
- configuration.md - Complete wrangler.jsonc examples
- patterns.md - Best practices and common patterns
- gotchas.md - Critical pitfalls and troubleshooting
Binding Catalog
Storage Bindings
| Binding | Use Case | Access Pattern |
|---|---|---|
| KV | Key-value cache, CDN-backed reads | env.MY_KV.get(key) |
| R2 | Object storage (S3-compatible) | env.MY_BUCKET.get(key) |
| D1 | SQL database (SQLite) | env.DB.prepare(sql).all() |
| Durable Objects | Coordination, real-time state | env.MY_DO.get(id) |
| Vectorize | Vector embeddings search | env.VECTORIZE.query(vector) |
| Queues | Async message processing | env.MY_QUEUE.send(msg) |
Compute Bindings
| Binding | Use Case | Access Pattern |
|---|---|---|
| Service | Worker-to-Worker RPC | env.MY_SERVICE.fetch(req) |
| Workers AI | LLM inference | env.AI.run(model, input) |
| Browser Rendering | Headless Chrome | env.BROWSER.fetch(url) |
Platform Bindings
| Binding | Use Case | Access Pattern |
|---|---|---|
| Analytics Engine | Custom metrics | env.ANALYTICS.writeDataPoint(data) |
| mTLS | Client certificates | env.MY_CERT (string) |
| Hyperdrive | Database pooling | env.HYPERDRIVE.connectionString |
| Rate Limiting | Request throttling | env.RATE_LIMITER.limit(id) |
| Workflows | Long-running workflows | env.MY_WORKFLOW.create() |
Configuration Bindings
| Binding | Use Case | Access Pattern |
|---|---|---|
| Environment Variables | Non-sensitive config | env.API_URL (string) |
| Secrets | Sensitive values | env.API_KEY (string) |
| Text/Data Blobs | Static files | env.MY_BLOB (string) |
| WASM | WebAssembly modules | env.MY_WASM (WebAssembly.Module) |
Quick Selection Guide
Need persistent storage?
- Key-value < 25MB → KV
- Files/objects → R2
- Relational data → D1
- Real-time coordination → Durable Objects
Need AI/compute?
- LLM inference → Workers AI
- Scraping/PDFs → Browser Rendering
- Call another Worker → Service binding
Need async processing?
- Background jobs → Queues
Need config?
- Public values → Environment Variables
- Secrets → Secrets (never commit)
Quick Start
- Add binding to wrangler.jsonc:
{
"kv_namespaces": [
{ "binding": "MY_KV", "id": "your-kv-id" }
]
}- Generate types:
npx wrangler types- Access in Worker:
export default {
async fetch(request, env, ctx) {
await env.MY_KV.put('key', 'value');
return new Response('OK');
}
}Type Safety
Bindings are fully typed via wrangler types. See api.md for details.
Limits
- 64 bindings max per Worker (all types combined)
- See gotchas.md for per-binding limits
Key Concepts
Zero-overhead access: Bindings compiled into Worker, no network calls to access
Type-safe: Full TypeScript support via wrangler types
Per-environment: Different IDs for dev/staging/production
Secrets vs Vars: Secrets encrypted at rest, never in config files
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/bot-management/README.md`)
Cloudflare Bot Management
Enterprise-grade bot detection, protection, and mitigation using ML/heuristics, bot scores, JavaScript detections, and verified bot handling.
Overview
Bot Management provides multi-tier protection:
- Free (Bot Fight Mode): Auto-blocks definite bots, no config
- Pro/Business (Super Bot Fight Mode): Configurable actions, static resource protection, analytics groupings
- Enterprise (Bot Management): Granular 1-99 scores, WAF integration, JA3/JA4 fingerprinting, Workers API, Advanced Analytics
Quick Start
# 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 ChallengeWhat Do You Need?
├─ Initial setup → configuration.md
│ ├─ Free tier → "Bot Fight Mode"
│ ├─ Pro/Business → "Super Bot Fight Mode"
│ └─ Enterprise → "Bot Management for Enterprise"
├─ Workers API integration → api.md
├─ WAF rules → patterns.md
├─ Debugging → gotchas.md
└─ Analytics → api.md#bot-analyticsReading Order
| Task | Files to Read |
|---|---|
| Enable bot protection | README → configuration.md |
| Workers bot detection | README → api.md |
| WAF rule templates | README → patterns.md |
| Debug bot issues | gotchas.md |
| Advanced analytics | api.md#bot-analytics |
Core Concepts
Bot Scores: 1-99 (1 = definitely automated, 99 = definitely human). Threshold: <30 indicates bot traffic. Enterprise gets granular 1-99; Pro/Business get groupings only.
Detection Engines: Heuristics (known fingerprints, assigns score=1), ML (majority of detections, supervised learning on billions of requests), Anomaly Detection (optional, baseline traffic analysis), JavaScript Detections (headless browser detection).
Verified Bots: Allowlisted good bots (search engines, AI crawlers) verified via reverse DNS or Web Bot Auth. Access via cf.bot_management.verified_bot or cf.verified_bot_category.
Platform Limits
| Plan | Bot Scores | JA3/JA4 | Custom Rules | Analytics Retention |
|---|---|---|---|---|
| Free | No (auto-block only) | No | 5 | N/A (no analytics) |
| Pro/Business | Groupings only | No | 20/100 | 30 days (72h at a time) |
| Enterprise | 1-99 granular | Yes | 1,000+ | 30 days (1 week at a time) |
Basic Patterns
// Workers: Check bot score
export default {
async fetch(request: Request): Promise<Response> {
const botScore = request.cf?.botManagement?.score;
if (botScore && botScore < 30 && !request.cf?.botManagement?.verifiedBot) {
return new Response('Bot detected', { status: 403 });
}
return fetch(request);
}
};# WAF: Block definite bots
(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot)
# WAF: Protect sensitive endpoints
(cf.bot_management.score lt 50 and http.request.uri.path in {"/login" "/checkout"} and not cf.bot_management.verified_bot)In This Reference
- configuration.md - Product tiers, WAF rule setup, JavaScript Detections, ML auto-updates
- api.md - Workers BotManagement interface, WAF fields, JA4 Signals
- patterns.md - E-commerce, API protection, mobile app allowlisting, SEO-friendly handling
- gotchas.md - False positives/negatives, score=0 issues, JSD limitations, CSP requirements
See Also
- waf - WAF custom rules for bot enforcement
- workers - Workers request.cf.botManagement API
- api-shield - API-specific bot protection
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/browser-rendering/README.md`)
Cloudflare Browser Rendering Skill Reference
Description: Expert knowledge for Cloudflare Browser Rendering - control headless Chrome on Cloudflare's global network for browser automation, screenshots, PDFs, web scraping, testing, and content generation.
When to use: Any task involving Cloudflare Browser Rendering including: taking screenshots, generating PDFs, web scraping, browser automation, testing web applications, extracting structured data, capturing page metrics, or automating browser interactions.
Decision Tree
REST API vs Workers Bindings
Use REST API when:
- One-off, stateless tasks (screenshot, PDF, content fetch)
- No Workers infrastructure yet
- Simple integrations from external services
- Need quick prototyping without deployment
Use Workers Bindings when:
- Complex browser automation workflows
- Need session reuse for performance
- Multiple page interactions per request
- Custom scripting and logic required
- Building production applications
Puppeteer vs Playwright
| Feature | Puppeteer | Playwright |
|---|---|---|
| API Style | Chrome DevTools Protocol | High-level abstractions |
| Selectors | CSS, XPath | CSS, text, role, test-id |
| Best for | Advanced control, CDP access | Quick automation, testing |
| Learning curve | Steeper | Gentler |
Use Puppeteer: Need CDP protocol access, Chrome-specific features, migration from existing Puppeteer code
Use Playwright: Modern selector APIs, cross-browser patterns, faster development
Tier Limits Summary
| Limit | Free Tier | Paid Tier |
|---|---|---|
| Daily browser time | 10 minutes | Unlimited* |
| Concurrent sessions | 3 | 30 |
| Requests per minute | 6 | 180 |
*Subject to fair-use policy. See gotchas.md for details.
Reading Order
New to Browser Rendering:
- configuration.md - Setup and deployment
- patterns.md - Common use cases with examples
- api.md - API reference
- gotchas.md - Avoid common pitfalls
Specific task:
- Setup/deployment → configuration.md
- API reference/endpoints → api.md
- Example code/patterns → patterns.md
- Debugging/troubleshooting → gotchas.md
REST API users:
- Start with api.md REST API section
- Check gotchas.md for rate limits
Workers users:
- Start with configuration.md
- Review patterns.md for session management
- Reference api.md for Workers Bindings
In This Reference
- configuration.md - Setup, deployment, wrangler config, compatibility
- api.md - REST API endpoints + Workers Bindings (Puppeteer/Playwright)
- patterns.md - Common patterns, use cases, real examples
- gotchas.md - Troubleshooting, best practices, tier limits, common errors
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/c3/README.md`)
C3 (create-cloudflare)
Official CLI for scaffolding Cloudflare Workers and Pages projects with templates, TypeScript, and instant deployment.
Quick Start
# Interactive (recommended for first-time)
npm create cloudflare@latest my-app
# Worker (API/WebSocket/Cron)
npm create cloudflare@latest my-api -- --type=hello-world --ts
# Pages (static/SSG/full-stack)
npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pagesPlatform Decision Tree
What are you building?
├─ API / WebSocket / Cron / Email handler
│ └─ Workers (default) - no --platform flag needed
│ npm create cloudflare@latest my-api -- --type=hello-world
├─ Static site / SSG / Documentation
│ └─ Pages - requires --platform=pages
│ npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages
├─ Full-stack app (Next.js/Remix/SvelteKit)
│ ├─ Need Durable Objects, Queues, or Workers-only features?
│ │ └─ Workers (default)
│ └─ Otherwise use Pages for git integration and branch previews
│ └─ Add --platform=pages
└─ Convert existing project
└─ npm create cloudflare@latest . -- --type=pre-existing --existing-script=./src/worker.tsCritical: Pages projects require --platform=pages flag. Without it, C3 defaults to Workers.
Interactive Flow
When run without flags, C3 prompts in this order:
- Project name - Directory to create (defaults to current dir with
.) - Application type -
hello-world,web-app,demo,pre-existing,remote-template - Platform -
workers(default) orpages(for web apps only) - Framework - If web-app:
next,remix,astro,react-router,solid,svelte, etc. - TypeScript -
yes(recommended) orno - Git - Initialize repository?
yesorno - Deploy - Deploy now?
yesorno(requireswrangler login)
Installation Methods
# NPM
npm create cloudflare@latest
# Yarn
yarn create cloudflare
# PNPM
pnpm create cloudflare@latestIn This Reference
| File | Purpose | Use When |
|---|---|---|
| api.md | Complete CLI flag reference | Scripting, CI/CD, advanced usage |
| configuration.md | Generated files, bindings, types | Understanding output, customization |
| patterns.md | Workflows, CI/CD, monorepos | Real-world integration |
| gotchas.md | Troubleshooting failures | Deployment blocked, errors |
Reading Order
| Task | Read |
|---|---|
| Create first project | README only |
| Set up CI/CD | README → api → patterns |
| Debug failed deploy | gotchas |
| Understand generated files | configuration |
| Full CLI reference | api |
| Create custom template | patterns → configuration |
| Convert existing project | README → patterns |
Post-Creation
cd my-app
# Local dev with hot reload
npm run dev
# Generate TypeScript types for bindings
npm run cf-typegen
# Deploy to Cloudflare
npm run deploySee Also
- workers/README.md - Workers runtime, bindings, APIs
- workers-ai/README.md - AI/ML models
- pages/README.md - Pages-specific features
- wrangler/README.md - Wrangler CLI beyond initial setup
- d1/README.md - SQLite database
- r2/README.md - Object storage
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/cache-reserve/README.md`)
Cloudflare Cache Reserve
Persistent cache storage built on R2 for long-term content retention
Smart Shield Integration
Cache Reserve is part of Smart Shield, Cloudflare's comprehensive security and performance suite:
- Smart Shield Advanced tier: Includes 2TB Cache Reserve storage
- Standalone purchase: Available separately if not using Smart Shield
- Migration: Existing standalone customers can migrate to Smart Shield bundles
Decision: Already on Smart Shield Advanced? Cache Reserve is included. Otherwise evaluate standalone purchase vs Smart Shield upgrade.
Overview
Cache Reserve is Cloudflare's persistent, large-scale cache storage layer built on R2. It acts as the ultimate upper-tier cache, storing cacheable content for extended periods (30+ days) to maximize cache hits, reduce origin egress fees, and shield origins from repeated requests for long-tail content.
Core Concepts
What is Cache Reserve?
- Persistent storage layer: Built on R2, sits above tiered cache hierarchy
- Long-term retention: 30-day default retention, extended on each access
- Automatic operation: Works seamlessly with existing CDN, no code changes required
- Origin shielding: Dramatically reduces origin egress by serving cached content longer
- Usage-based pricing: Pay only for storage + read/write operations
Cache Hierarchy
Visitor Request
↓
Lower-Tier Cache (closest to visitor)
↓ (on miss)
Upper-Tier Cache (closest to origin)
↓ (on miss)
Cache Reserve (R2 persistent storage)
↓ (on miss)
Origin ServerHow It Works
- On cache miss: Content fetched from origin �� written to Cache Reserve + edge caches simultaneously
- On edge eviction: Content may be evicted from edge cache but remains in Cache Reserve
- On subsequent request: If edge cache misses but Cache Reserve hits → content restored to edge caches
- Retention: Assets remain in Cache Reserve for 30 days since last access (configurable via TTL)
When to Use Cache Reserve
Need persistent caching?
├─ High origin egress costs → Cache Reserve ✓
├─ Long-tail content (archives, media libraries) → Cache Reserve ✓
├─ Already using Smart Shield Advanced → Included! ✓
├─ Video streaming with seeking (range requests) → ✗ Not supported
├─ Dynamic/personalized content → ✗ Use edge cache only
├─ Need per-request cache control from Workers → ✗ Use R2 directly
└─ Frequently updated content (< 10hr lifetime) → ✗ Not eligibleAsset Eligibility
Cache Reserve only stores assets meeting ALL criteria:
- Cacheable per Cloudflare's standard rules
- Minimum 10-hour TTL (36000 seconds)
Content-Lengthheader present- Original files only (not transformed images)
Eligibility Checklist
Use this checklist to verify if an asset is eligible:
- Zone has Cache Reserve enabled
- Zone has Tiered Cache enabled (required)
- Asset TTL ≥ 10 hours (36,000 seconds)
-
Content-Lengthheader present on origin response - No
Set-Cookieheader (or uses private directive) -
Varyheader is NOT*(can beAccept-Encoding) - Not an image transformation variant (original images OK)
- Not a range request (no HTTP 206 support)
- Not O2O (Orange-to-Orange) proxied request
All boxes must be checked for Cache Reserve eligibility.
Not Eligible
- Assets with TTL < 10 hours
- Responses without
Content-Lengthheader - Image transformation variants (original images are eligible)
- Responses with
Set-Cookieheaders - Responses with
Vary: *header - Assets from R2 public buckets on same zone
- O2O (Orange-to-Orange) setup requests
- Range requests (video seeking, partial content downloads)
Quick Start
# Enable via Dashboard
https://dash.cloudflare.com/caching/cache-reserve
# Click "Enable Storage Sync" or "Purchase" buttonPrerequisites:
- Paid Cache Reserve plan or Smart Shield Advanced required
- Tiered Cache required for optimal performance
Essential Commands
# Check Cache Reserve status
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \
-H "Authorization: Bearer $API_TOKEN"
# Enable Cache Reserve
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"value": "on"}'
# Check asset cache status
curl -I https://example.com/asset.jpg | grep -i cacheIn This Reference
| Task | Files |
|---|---|
| Evaluate if Cache Reserve fits your use case | README.md (this file) |
| Enable Cache Reserve for your zone | README.md + configuration.md |
| Use with Workers (understand limitations) | api.md |
| Setup via SDKs or IaC (TypeScript, Python, Terraform) | configuration.md |
| Optimize costs and debug issues | patterns.md + gotchas.md |
| Understand eligibility and troubleshoot | gotchas.md → patterns.md |
Files:
- configuration.md - Setup, API, SDKs, and Cache Rules
- api.md - Purging, monitoring, Workers integration
- patterns.md - Best practices, cost optimization, debugging
- gotchas.md - Common issues, limitations, troubleshooting
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/containers/README.md`)
Cloudflare Containers Skill Reference
APPLIES TO: Cloudflare Containers ONLY - NOT general Cloudflare Workers
Use when working with Cloudflare Containers: deploying containerized apps on Workers platform, configuring container-enabled Durable Objects, managing container lifecycle, or implementing stateful/stateless container patterns.
Beta Status
⚠️ Containers is currently in beta. API may change without notice. No SLA guarantees. Custom instance types added Jan 2026.
Core Concepts
Container as Durable Object: Each container is a Durable Object with persistent identity. Accessed via getByName(id) or getRandom().
Image deployment: Images pre-fetched globally. Deployments use rolling strategy (not instant like Workers).
Lifecycle: cold start (2-3s) → running → sleepAfter timeout → stopped. No autoscaling - manual load balancing via getRandom().
Persistent identity, ephemeral disk: Container ID persists, but disk resets on stop. Use Durable Object storage for persistence.
Quick Start
import { Container } from "@cloudflare/containers";
export class MyContainer extends Container {
defaultPort = 8080;
sleepAfter = "30m";
}
export default {
async fetch(request: Request, env: Env) {
const container = env.MY_CONTAINER.getByName("instance-1");
await container.startAndWaitForPorts();
return container.fetch(request);
}
};Reading Order
| Task | Files |
|---|---|
| Setup new container project | README → configuration.md |
| Implement container logic | README → api.md → patterns.md |
| Choose routing pattern | patterns.md (routing section) |
| Debug issues | gotchas.md |
| Production hardening | gotchas.md → patterns.md (lifecycle) |
Routing Decision Tree
How should requests reach containers?
- Same user/session → same container: Use
getByName(sessionId)for session affinity - Stateless, spread load: Use
getRandom()for load balancing - Job per container: Use
getByName(jobId)+ explicit lifecycle management - Single global instance: Use
getByName("singleton")
When to Use Containers vs Workers
Use Containers when:
- Need stateful, long-lived processes (sessions, WebSockets, games)
- Running existing containerized apps (Node.js, Python, custom binaries)
- Need filesystem access or specific system dependencies
- Per-user/session isolation with dedicated compute
Use Workers when:
- Stateless HTTP handlers
- Sub-millisecond cold starts required
- Auto-scaling to zero critical
- Simple request/response patterns
In This Reference
- configuration.md - Wrangler config, instance types, Container class properties, environment variables, account limits
- api.md - Container class API, startup methods, communication (HTTP/TCP/WebSocket), routing helpers, lifecycle hooks, scheduling, state inspection
- patterns.md - Routing patterns (session affinity, load balancing, singleton), WebSocket forwarding, graceful shutdown, Workflow/Queue integration
- gotchas.md - Critical gotchas (WebSocket, startup methods), common errors with solutions, specific limits, beta caveats
See Also
- Durable Objects - Containers extend Durable Objects
- Workflows - Orchestrate container operations
- Queues - Trigger containers from queue messages
- Cloudflare Docs
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/cron-triggers/README.md`)
Cloudflare Cron Triggers
Schedule Workers execution using cron expressions. Runs on Cloudflare's global network during underutilized periods.
Key Features
- UTC-only execution - All schedules run on UTC time
- 5-field cron syntax - Quartz scheduler extensions (L, W, #)
- Global propagation - 15min deployment delay
- At-least-once delivery - Rare duplicate executions possible
- Workflow integration - Trigger long-running multi-step tasks
- Green Compute - Optional carbon-aware scheduling during low-carbon periods
Cron Syntax
┌─────────── minute (0-59)
│ ┌───────── hour (0-23)
│ │ ┌─────── day of month (1-31)
│ │ │ ┌───── month (1-12, JAN-DEC)
│ │ │ │ ┌─── day of week (1-7, SUN-SAT, 1=Sunday)
* * * * *Special chars: * (any), , (list), - (range), / (step), L (last), W (weekday), # (nth)
Common Schedules
*/5 * * * * # Every 5 minutes
0 * * * * # Hourly
0 2 * * * # Daily 2am UTC (off-peak)
0 9 * * MON-FRI # Weekdays 9am UTC
0 0 1 * * # Monthly 1st midnight UTC
0 9 L * * # Last day of month 9am UTC
0 10 * * MON#2 # 2nd Monday 10am UTC
*/10 9-17 * * MON-FRI # Every 10min, 9am-5pm weekdaysQuick Start
wrangler.jsonc:
{
"name": "my-cron-worker",
"triggers": {
"crons": ["*/5 * * * *", "0 2 * * *"]
}
}Handler:
export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
): Promise<void> {
console.log("Cron:", controller.cron);
console.log("Time:", new Date(controller.scheduledTime));
ctx.waitUntil(asyncTask(env)); // Non-blocking
},
};Test locally:
npx wrangler dev
curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*"Limits
- Free: 3 triggers/worker, 10ms CPU
- Paid: Unlimited triggers, 50ms CPU
- Propagation: 15min global deployment
- Timezone: UTC only
Reading Order
New to cron triggers? Start here:
- This README - Overview and quick start
- configuration.md - Set up your first cron trigger
- api.md - Understand the handler API
- patterns.md - Common use cases and examples
Troubleshooting? Jump to gotchas.md
In This Reference
- configuration.md - wrangler config, env-specific schedules, Green Compute
- api.md - ScheduledController, noRetry(), waitUntil, testing patterns
- patterns.md - Use cases, monitoring, queue integration, Durable Objects
- gotchas.md - Timezone issues, idempotency, security, testing
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/d1/README.md`)
Cloudflare D1 Database
Expert guidance for Cloudflare D1, a serverless SQLite database designed for horizontal scale-out across multiple databases.
Overview
D1 is Cloudflare's managed, serverless database with:
- SQLite SQL semantics and compatibility
- Built-in disaster recovery via Time Travel (30-day point-in-time recovery)
- Horizontal scale-out architecture (10 GB per database)
- Worker and HTTP API access
- Pricing based on query and storage costs only
Architecture Philosophy: D1 is optimized for per-user, per-tenant, or per-entity database patterns rather than single large databases.
Quick Start
# Create database
wrangler d1 create <database-name>
# Execute migration
wrangler d1 migrations apply <db-name> --remote
# Local development
wrangler devCore Query Methods
// .all() - Returns all rows; .first() - First row or null; .first(col) - Single column value
// .run() - INSERT/UPDATE/DELETE; .raw() - Array of arrays (efficient)
const { results, success, meta } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all();
const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();Batch Operations
// Multiple queries in single round trip (atomic transaction)
const results = await env.DB.batch([
env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(1),
env.DB.prepare('SELECT * FROM posts WHERE author_id = ?').bind(1),
env.DB.prepare('UPDATE users SET last_access = ? WHERE id = ?').bind(Date.now(), 1)
]);Sessions API (Paid Plans)
// Create long-running session for analytics/migrations (up to 15 minutes)
const session = env.DB.withSession();
try {
await session.prepare('CREATE INDEX idx_heavy ON large_table(column)').run();
await session.prepare('ANALYZE').run();
} finally {
session.close(); // Always close to release resources
}Read Replication (Paid Plans)
// Read from nearest replica for lower latency (automatic failover)
const user = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();
// Writes always go to primary
await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run();Platform Limits
| Limit | Free Tier | Paid Plans |
|---|---|---|
| Database size | 500 MB | 10 GB per database |
| Row size | 1 MB max | 1 MB max |
| Query timeout | 30 seconds | 30 seconds |
| Batch size | 1,000 statements | 10,000 statements |
| Time Travel retention | 7 days | 30 days |
| Read replicas | Not available | Yes (paid add-on) |
Pricing: $5/month per database beyond free tier + $0.001 per 1K reads + $1 per 1M writes + $0.75/GB storage/month
CLI Commands
# Database management
wrangler d1 create <db-name>
wrangler d1 list
wrangler d1 delete <db-name>
# Migrations
wrangler d1 migrations create <db-name> <migration-name> # Create new migration file
wrangler d1 migrations apply <db-name> --remote # Apply pending migrations
wrangler d1 migrations apply <db-name> --local # Apply locally
wrangler d1 migrations list <db-name> --remote # Show applied migrations
# Direct SQL execution
wrangler d1 execute <db-name> --remote --command="SELECT * FROM users"
wrangler d1 execute <db-name> --local --file=./schema.sql
# Backups & Import/Export
wrangler d1 export <db-name> --remote --output=./backup.sql # Full export with schema
wrangler d1 export <db-name> --remote --no-schema --output=./data.sql # Data only
wrangler d1 time-travel restore <db-name> --timestamp="2024-01-15T14:30:00Z" # Point-in-time recovery
# Development
wrangler dev --persist-to=./.wrangler/stateReading Order
Start here: Quick Start above → configuration.md (setup) → api.md (queries)
Common tasks:
- First time setup: configuration.md → Run migrations
- Adding queries: api.md → Prepared statements
- Pagination/caching: patterns.md
- Production optimization: Read Replication + Sessions API (this file)
- Debugging: gotchas.md
In This Reference
- configuration.md - wrangler.jsonc setup, migrations, TypeScript types, ORMs, local dev
- api.md - Query methods (.all/.first/.run/.raw), batch, sessions, read replicas, error handling
- patterns.md - Pagination, bulk operations, caching, multi-tenant, sessions, analytics
- gotchas.md - SQL injection, limits by plan tier, performance, common errors
See Also
- workers - Worker runtime and fetch handler patterns
- hyperdrive - Connection pooling for external databases
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ddos/README.md`)
Cloudflare DDoS Protection
Autonomous, always-on protection against DDoS attacks across L3/4 and L7.
Protection Types
- HTTP DDoS (L7): Protects HTTP/HTTPS traffic, phase
ddos_l7, zone/account level - Network DDoS (L3/4): UDP/SYN/DNS floods, phase
ddos_l4, account level only - Adaptive DDoS: Learns 7-day baseline, detects deviations, 4 profile types (Origins, User-Agents, Locations, Protocols)
Plan Availability
| Feature | Free | Pro | Business | Enterprise | Enterprise Advanced |
|---|---|---|---|---|---|
| HTTP DDoS (L7) | ✓ | ✓ | ✓ | ✓ | ✓ |
| Network DDoS (L3/4) | ✓ | ✓ | ✓ | ✓ | ✓ |
| Override rules | 1 | 1 | 1 | 1 | 10 |
| Custom expressions | ✗ | ✗ | ✗ | ✗ | ✓ |
| Log action | ✗ | ✗ | ✗ | ✗ | ✓ |
| Adaptive DDoS | ✗ | ✗ | ✗ | ✓ | ✓ |
| Alert filters | Basic | Basic | Basic | Advanced | Advanced |
Actions & Sensitivity
- Actions:
block,managed_challenge,challenge,log(Enterprise Advanced only) - Sensitivity:
default(high),medium,low,eoff(essentially off) - Override: By category/tag or individual rule ID
- Scope: Zone-level overrides take precedence over account-level
Reading Order
| File | Purpose | Start Here If... |
|---|---|---|
| configuration.md | Dashboard setup, rule structure, adaptive profiles | You're setting up DDoS protection for the first time |
| api.md | API endpoints, SDK usage, ruleset ID discovery | You're automating configuration or need programmatic access |
| patterns.md | Protection strategies, defense-in-depth, dynamic response | You need implementation patterns or layered security |
| gotchas.md | False positives, tuning, error handling | You're troubleshooting or optimizing existing protection |
See Also
- waf - Application-layer security rules
- bot-management - Bot detection and mitigation
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/do-storage/README.md`)
Cloudflare Durable Objects Storage
Persistent storage API for Durable Objects with SQLite and KV backends, PITR, and automatic concurrency control.
Overview
DO Storage provides:
- SQLite-backed (recommended) or KV-backed
- SQL API + synchronous/async KV APIs
- Automatic input/output gates (race-free)
- 30-day point-in-time recovery (PITR)
- Transactions and alarms
Use cases: Stateful coordination, real-time collaboration, counters, sessions, rate limiters
Billing: Charged by request, GB-month storage, and rowsRead/rowsWritten for SQL operations
Quick Start
export class Counter extends DurableObject {
sql: SqlStorage;
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.sql = ctx.storage.sql;
this.sql.exec('CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY, value INTEGER)');
}
async increment(): Promise<number> {
const result = this.sql.exec(
'INSERT INTO data VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = value + 1 RETURNING value',
'counter', 1
).one();
return result?.value || 1;
}
}Storage Backends
| Backend | Create Method | APIs | PITR |
|---|---|---|---|
| SQLite (recommended) | new_sqlite_classes |
SQL + sync KV + async KV | ✅ |
| KV (legacy) | new_classes |
async KV only | ❌ |
Core APIs
- SQL API (
ctx.storage.sql): Full SQLite with extensions (FTS5, JSON, math) - Sync KV (
ctx.storage.kv): Synchronous key-value (SQLite only) - Async KV (
ctx.storage): Asynchronous key-value (both backends) - Transactions (
transactionSync(),transaction()) - PITR (
getBookmarkForTime(),onNextSessionRestoreBookmark()) - Alarms (
setAlarm(),alarm()handler)
Reading Order
New to DO storage: configuration.md → api.md → patterns.md → gotchas.md
Building features: patterns.md → api.md → gotchas.md
Debugging issues: gotchas.md → api.md
Writing tests: testing.md
In This Reference
- configuration.md - wrangler.jsonc migrations, SQLite vs KV setup, RPC binding
- api.md - SQL exec/cursors, KV methods, storage options, transactions, alarms, PITR
- patterns.md - Schema migrations, caching, rate limiting, batch processing, parent-child coordination
- gotchas.md - Concurrency gates, INTEGER precision, transaction rules, SQL limits
- testing.md - vitest-pool-workers setup, testing DOs with SQL/alarms/PITR
See Also
- durable-objects - DO fundamentals and coordination patterns
- workers - Worker runtime for DO stubs
- d1 - Shared database alternative to per-DO storage
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/durable-objects/README.md`)
Cloudflare Durable Objects
Expert guidance for building stateful applications with Cloudflare Durable Objects.
Reading Order
- First time? Read this overview + Quick Start
- Setting up? See Configuration
- Building features? Use decision trees below → Patterns
- Debugging issues? Check Gotchas
- Deep dive? API and DO Storage
Overview
Durable Objects combine compute with storage in globally-unique, strongly-consistent packages:
- Globally unique instances: Each DO has unique ID for multi-client coordination
- Co-located storage: Fast, strongly-consistent storage with compute
- Automatic placement: Objects spawn near first request location
- Stateful serverless: In-memory state + persistent storage
- Single-threaded: Serial request processing (no race conditions)
Rules of Durable Objects
Critical rules preventing most production issues:
- One alarm per DO - Schedule multiple events via queue pattern
- ~1K req/s per DO max - Shard for higher throughput
- Constructor runs every wake - Keep initialization light; use lazy loading
- Hibernation clears memory - In-memory state lost; persist critical data
- Use
ctx.waitUntil()for cleanup - Ensures completion after response sent - No setTimeout for persistence - Use
setAlarm()for reliable scheduling
Core Concepts
Class Structure
All DOs extend DurableObject base class with constructor receiving DurableObjectState (storage, WebSockets, alarms) and Env (bindings).
Lifecycle States
[Not Created] → [Active] ⇄ [Hibernated] → [Evicted]
↓
[Destroyed]- Not Created: DO ID exists but instance never spawned
- Active: Processing requests, in-memory state valid, billed per GB-hour
- Hibernated: WebSocket connections open but zero compute, zero cost
- Evicted: Removed from memory; next request triggers cold start
- Destroyed: Data deleted via migration or manual deletion
Accessing from Workers
Workers use bindings to get stubs, then call RPC methods directly (recommended) or use fetch handler (legacy).
RPC vs fetch() decision:
├─ New project + compat ≥2024-04-03 → RPC (type-safe, simpler)
├─ Need HTTP semantics (headers, status) → fetch()
├─ Proxying requests to DO → fetch()
└─ Legacy compatibility → fetch()See Patterns: RPC vs fetch() for examples.
ID Generation
idFromName(): Deterministic, named coordination (rate limiting, locks)newUniqueId(): Random IDs for sharding high-throughput workloadsidFromString(): Derive from existing IDs- Jurisdiction option: Data locality compliance
Storage Options
Which storage API?
├─ Structured data, relations, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync KV)
└─ Legacy KV-only DO → ctx.storage (async KV)- SQLite (recommended): Structured data, transactions, 10GB/DO
- Synchronous KV API: Simple key-value on SQLite objects
- Asynchronous KV API: Legacy/advanced use cases
See DO Storage for deep dive.
Special Features
- Alarms: Schedule future execution per-DO (1 per DO - use queue pattern for multiple)
- WebSocket Hibernation: Zero-cost idle connections (memory cleared on hibernation)
- Point-in-Time Recovery: Restore to any point in 30 days (SQLite only)
Quick Start
import { DurableObject } from "cloudflare:workers";
export class Counter extends DurableObject<Env> {
async increment(): Promise<number> {
const result = this.ctx.storage.sql.exec(
`INSERT INTO counters (id, value) VALUES (1, 1)
ON CONFLICT(id) DO UPDATE SET value = value + 1
RETURNING value`
).one();
return result.value;
}
}
// Worker access
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const id = env.COUNTER.idFromName("global");
const stub = env.COUNTER.get(id);
const count = await stub.increment();
return new Response(`Count: ${count}`);
}
};Decision Trees
What do you need?
├─ Coordinate requests (rate limit, lock, session)
│ → idFromName(identifier) → [Patterns: Rate Limiting/Locks](./patterns.md)
│
├─ High throughput (>1K req/s)
│ → Sharding with newUniqueId() or hash → [Patterns: Sharding](./patterns.md)
│
├─ Real-time updates (WebSocket, chat, collab)
│ → WebSocket hibernation + room pattern → [Patterns: Real-time](./patterns.md)
│
├─ Background work (cleanup, notifications, scheduled tasks)
│ → Alarms + queue pattern (1 alarm/DO) → [Patterns: Multiple Events](./patterns.md)
│
└─ User sessions with expiration
→ Session pattern + alarm cleanup → [Patterns: Session Management](./patterns.md)Which access pattern?
├─ New project + typed methods → RPC (compat ≥2024-04-03)
├─ Need HTTP semantics → fetch()
├─ Proxying to DO → fetch()
└─ Legacy compat → fetch()See Patterns: RPC vs fetch() for examples.
Which storage?
├─ Structured data, SQL queries, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync API)
└─ Legacy KV-only DO → ctx.storage (async API)See DO Storage for complete guide.
Essential Commands
npx wrangler dev # Local dev with DOs
npx wrangler dev --remote # Test against prod DOs
npx wrangler deploy # Deploy + auto-apply migrationsResources
Docs: https://developers.cloudflare.com/durable-objects/
API Reference: https://developers.cloudflare.com/durable-objects/api/
Examples: https://developers.cloudflare.com/durable-objects/examples/
In This Reference
- Configuration - wrangler.jsonc setup, migrations, bindings, environments
- API - Class structure, ctx methods, alarms, WebSocket hibernation
- Patterns - Sharding, rate limiting, locks, real-time, sessions
- Gotchas - Limits, hibernation caveats, common errors
See Also
- DO Storage - SQLite, KV, transactions (detailed storage guide)
- Workers - Core Workers runtime features
- WebSockets - WebSocket APIs and patterns
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/email-routing/README.md`)
Cloudflare Email Routing Skill Reference
Overview
Cloudflare Email Routing enables custom email addresses for your domain that route to verified destination addresses. It's free, privacy-focused (no storage/access), and includes Email Workers for programmatic email processing.
Available to all Cloudflare customers using Cloudflare as authoritative nameserver.
Quick Start
// Basic email handler
export default {
async email(message, env, ctx) {
// CRITICAL: Must consume stream before response
const parser = new PostalMime.default();
const email = await parser.parse(await message.raw.arrayBuffer());
// Process email
console.log(`From: ${message.from}, Subject: ${email.subject}`);
// Forward or reject
await message.forward("[email protected]");
}
} satisfies ExportedHandler<Env>;Reading Order
Start here based on your goal:
- New to Email Routing? → configuration.md → patterns.md
- Adding Workers? → api.md § Worker Runtime API → patterns.md
- Sending emails? → api.md § SendEmail Binding
- Managing via API? → api.md § REST API Operations
- Debugging issues? → gotchas.md
Decision Tree
Need to receive emails?
├─ Simple forwarding only? → Dashboard rules (configuration.md)
├─ Complex logic/filtering? → Email Workers (api.md + patterns.md)
└─ Parse attachments/body? → postal-mime library (patterns.md § Parse Email)
Need to send emails?
├─ From Worker? → SendEmail binding (api.md § SendEmail)
└─ From external app? → Use external SMTP/API service
Having issues?
├─ Email not arriving? → gotchas.md § Mail Authentication
├─ Worker crashing? → gotchas.md § Stream Consumption
└─ Forward failing? → gotchas.md § Destination VerificationKey Concepts
Routing Rules: Pattern-based forwarding configured via Dashboard/API. Simple but limited.
Email Workers: Custom TypeScript handlers with full email access. Handles complex logic, parsing, storage, rejection.
SendEmail Binding: Outbound email API for Workers. Transactional email only (no marketing/bulk).
ForwardableEmailMessage: Runtime interface for incoming emails. Provides headers, raw stream, forward/reject methods.
In This Reference
- configuration.md - Setup, deployment, wrangler config
- api.md - REST API + Worker runtime API + types
- patterns.md - Common patterns with working examples
- gotchas.md - Critical pitfalls, troubleshooting, limits
Architecture
Internet → MX Records → Cloudflare Email Routing
├─ Routing Rules (dashboard)
└─ Email Worker (your code)
├─ Forward to destination
├─ Reject with reason
├─ Store in R2/KV/D1
└─ Send outbound (SendEmail)See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/email-workers/README.md`)
Cloudflare Email Workers
Process incoming emails programmatically using Cloudflare Workers runtime.
Overview
Email Workers enable custom email processing logic at the edge. Build spam filters, auto-responders, ticket systems, notification handlers, and more using the same Workers runtime you use for HTTP requests.
Key capabilities:
- Process inbound emails with full message access
- Forward to verified destinations
- Send replies with proper threading
- Parse MIME content and attachments
- Integrate with KV, R2, D1, and external APIs
Quick Start
Minimal ES Modules Handler
export default {
async email(message, env, ctx) {
// Reject spam
if (message.from.includes('spam.com')) {
message.setReject('Blocked');
return;
}
// Forward to inbox
await message.forward('[email protected]');
}
};Core Operations
| Operation | Method | Use Case |
|---|---|---|
| Forward | message.forward(to, headers?) |
Route to verified destination |
| Reject | message.setReject(reason) |
Block with SMTP error |
| Reply | message.reply(emailMessage) |
Auto-respond with threading |
| Parse | postal-mime library | Extract subject, body, attachments |
Reading Order
For comprehensive understanding, read files in this order:
- README.md (this file) - Overview and quick start
- configuration.md - Setup, deployment, bindings
- api.md - Complete API reference
- patterns.md - Real-world implementation examples
- gotchas.md - Critical pitfalls and debugging
In This Reference
| File | Description | Key Topics |
|---|---|---|
| api.md | Complete API reference | ForwardableEmailMessage, SendEmail bindings, reply() method, postal-mime/mimetext APIs |
| configuration.md | Setup and configuration | wrangler.jsonc, bindings, deployment, dependencies |
| patterns.md | Real-world examples | Allowlists from KV, auto-reply with threading, attachment extraction, webhook notifications |
| gotchas.md | Pitfalls and debugging | Stream consumption, ctx.waitUntil errors, security, limits |
Architecture
Incoming Email → Email Routing → Email Worker
↓
Process + Decide
↓
┌───────────────┼───────────────┐
↓ ↓ ↓
Forward Reply RejectEvent flow:
- Email arrives at your domain
- Email Routing matches route (e.g.,
[email protected]) - Bound Email Worker receives
ForwardableEmailMessage - Worker processes and takes action (forward/reply/reject)
- Email delivered or rejected based on worker logic
Key Concepts
Envelope vs Headers
- Envelope addresses (
message.from,message.to): SMTP transport addresses (trusted) - Header addresses (parsed from body): Display addresses (can be spoofed)
Use envelope addresses for security decisions.
Single-Use Streams
message.raw is a ReadableStream that can only be read once. Buffer to ArrayBuffer for multiple uses.
// Buffer first
const buffer = await new Response(message.raw).arrayBuffer();
const email = await PostalMime.parse(buffer);See gotchas.md for details.
Verified Destinations
forward() only works with addresses verified in the Cloudflare Email Routing dashboard. Add destinations before deployment.
Use Cases
- Spam filtering: Block based on sender, content, or reputation
- Auto-responders: Send acknowledgment replies with threading
- Ticket creation: Parse emails and create support tickets
- Email archival: Store in KV, R2, or D1
- Notification routing: Forward to Slack, Discord, or webhooks
- Attachment processing: Extract files to R2 storage
- Multi-tenant routing: Route based on recipient subdomain
- Size filtering: Reject oversized attachments
Limits
| Limit | Value |
|---|---|
| Max message size | 25 MiB |
| Max routing rules | 200 |
| Max destinations | 200 |
| CPU time (free tier) | 10ms |
| CPU time (paid tier) | 50ms |
See gotchas.md for complete limits table.
Prerequisites
Before deploying Email Workers:
- Enable Email Routing in Cloudflare dashboard for your domain
- Verify destination addresses for forwarding
- Configure DMARC/SPF for sending domains (required for replies)
- Set up wrangler.jsonc with SendEmail binding
See configuration.md for detailed setup.
Service Worker Syntax (Deprecated)
Modern projects should use ES modules format shown above. Service Worker syntax (addEventListener('email', ...)) is deprecated but still supported.
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/hyperdrive/README.md`)
Hyperdrive
Accelerates database queries from Workers via connection pooling, edge setup, query caching.
Key Features
- Connection Pooling: Persistent connections eliminate TCP/TLS/auth handshakes (~7 round-trips)
- Edge Setup: Connection negotiation at edge, pooling near origin
- Query Caching: Auto-cache non-mutating queries (default 60s TTL)
- Support: PostgreSQL, MySQL + compatibles (CockroachDB, Timescale, PlanetScale, Neon, Supabase)
Architecture
Worker → Edge (setup) → Pool (near DB) → Origin
↓ cached reads
CacheQuick Start
# Create config
npx wrangler hyperdrive create my-db \
--connection-string="postgres://user:pass@host:5432/db"
# wrangler.jsonc
{
"compatibility_flags": ["nodejs_compat"],
"hyperdrive": [{"binding": "HYPERDRIVE", "id": ""}]
}import { Client } from "pg";
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
await client.connect();
const result = await client.query("SELECT * FROM users WHERE id = $1", [123]);
await client.end();
return Response.json(result.rows);
},
};When to Use
✅ Global access to single-region DBs, high read ratios, popular queries, connection-heavy loads
❌ Write-heavy, real-time data (<1s), single-region apps close to DB
💡 Pair with Smart Placement for Workers making multiple queries - executes near DB to minimize latency.
Driver Choice
| Driver | Use When | Notes |
|---|---|---|
| pg (recommended) | General use, TypeScript, ecosystem compatibility | Stable, widely used, works with most ORMs |
| postgres.js | Advanced features, template literals, streaming | Lighter than pg, prepare: true is default |
| mysql2 | MySQL/MariaDB/PlanetScale | MySQL only, less mature support |
Reading Order
| New to Hyperdrive | Implementing | Troubleshooting |
|---|---|---|
| 1. README (this) | 1. configuration.md | 1. gotchas.md |
| 2. configuration.md | 2. api.md | 2. patterns.md |
| 3. api.md | 3. patterns.md | 3. api.md |
In This Reference
- configuration.md - Setup, wrangler config, Smart Placement
- api.md - Binding APIs, query patterns, driver usage
- patterns.md - Use cases, ORMs, multi-query optimization
- gotchas.md - Limits, troubleshooting, connection management
See Also
- smart-placement - Optimize multi-query Workers near databases
- d1 - Serverless SQLite alternative for edge-native apps
- workers - Worker runtime with database bindings
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/images/README.md`)
Cloudflare Images Skill Reference
Cloudflare Images is an end-to-end image management solution providing storage, transformation, optimization, and delivery at scale via Cloudflare's global network.
Quick Decision Tree
Need to:
- Transform in Worker? → api.md (Workers Binding API)
- Upload from Worker? → api.md (REST API)
- Upload from client? → patterns.md (Direct Creator Upload)
- Set up variants? → configuration.md
- Serve responsive images? → patterns.md
- Add watermarks? → patterns.md
- Fix errors? → gotchas.md
Reading Order
For building image upload/transform feature:
- configuration.md - Setup Workers binding
- api.md - Learn transform API
- patterns.md - Direct upload pattern
- gotchas.md - Check limits and errors
For URL-based transforms:
- configuration.md - Create variants
- api.md - URL syntax
- patterns.md - Responsive patterns
For troubleshooting:
- gotchas.md - Error messages
- gotchas.md - Size/format limits
Core Methods
| Method | Use Case | Location |
|---|---|---|
env.IMAGES.input().transform() |
Transform in Worker | api.md:11 |
REST API /images/v1 |
Upload images | api.md:57 |
| Direct Creator Upload | Client-side upload | api.md:127 |
| URL transforms | Static image delivery | api.md:112 |
In This Reference
- api.md - Complete API: Workers binding, REST endpoints, URL transforms
- configuration.md - Setup: wrangler.toml, variants, auth, signed URLs
- patterns.md - Patterns: responsive images, watermarks, format negotiation, caching
- gotchas.md - Troubleshooting: limits, errors, best practices
Key Features
- Automatic Optimization - AVIF/WebP format negotiation
- On-the-fly Transforms - Resize, crop, blur, sharpen via URL or API
- Workers Binding - Transform images in Workers (2026 primary method)
- Direct Upload - Secure client-side uploads without backend proxy
- Global Delivery - Cached at 300+ Cloudflare data centers
- Watermarking - Overlay images programmatically
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/kv/README.md`)
Cloudflare Workers KV
Globally-distributed, eventually-consistent key-value store optimized for high read volume and low latency.
Overview
KV provides:
- Eventual consistency (60s global propagation)
- Read-optimized performance
- 25 MiB value limit per key
- Auto-replication to Cloudflare edge
- Metadata support (1024 bytes)
Use cases: Config storage, user sessions, feature flags, caching, A/B testing
When to Use KV
| Need | Recommendation |
|---|---|
| Strong consistency | → Durable Objects |
| SQL queries | → D1 |
| Object storage (files) | → R2 |
| High read, low write volume | → KV ✅ |
| Sub-10ms global reads | → KV ✅ |
Quick comparison:
| Feature | KV | D1 | Durable Objects |
|---|---|---|---|
| Consistency | Eventual | Strong | Strong |
| Read latency | <10ms | ~50ms | <1ms |
| Write limit | 1/s per key | Unlimited | Unlimited |
| Use case | Config, cache | Relational data | Coordination |
Quick Start
wrangler kv namespace create MY_NAMESPACE
# Add binding to wrangler.jsonc// Write
await env.MY_KV.put("key", "value", { expirationTtl: 300 });
// Read
const value = await env.MY_KV.get("key");
const json = await env.MY_KV.get<Config>("config", "json");Core Operations
| Method | Purpose | Returns |
|---|---|---|
get(key, type?) |
Single read | string | null |
get(keys, type?) |
Bulk read (≤100) | Map<string, T | null> |
put(key, value, options?) |
Write | Promise<void> |
delete(key) |
Delete | Promise<void> |
list(options?) |
List keys | { keys, list_complete, cursor? } |
getWithMetadata(key) |
Get + metadata | { value, metadata } |
Consistency Model
- Write visibility: Immediate in same location, ≤60s globally
- Read path: Eventually consistent
- Write rate: 1 write/second per key (429 on exceed)
Reading Order
| Task | Files to Read |
|---|---|
| Quick start | README → configuration.md |
| Implement feature | README → api.md → patterns.md |
| Debug issues | gotchas.md → api.md |
| Batch operations | api.md (bulk section) → patterns.md |
| Performance tuning | gotchas.md (performance) → patterns.md (caching) |
In This Reference
- configuration.md - wrangler.jsonc setup, namespace creation, TypeScript types
- api.md - KV methods, bulk operations, cacheTtl, content types
- patterns.md - Caching, sessions, rate limiting, A/B testing
- gotchas.md - Eventual consistency, concurrent writes, value limits
See Also
- workers - Worker runtime for KV access
- d1 - Use D1 for strong consistency needs
- durable-objects - Strongly consistent alternative
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/miniflare/README.md`)
Miniflare
Local simulator for Cloudflare Workers development/testing. Runs Workers in workerd sandbox implementing runtime APIs - no internet required.
Features
- Full-featured: KV, Durable Objects, R2, D1, WebSockets, Queues
- Fully-local: test without internet, instant reload
- TypeScript-native: detailed logging, source maps
- Advanced testing: dispatch events without HTTP, simulate Worker connections
When to Use
Decision tree for testing Workers:
Need to test Workers?
│
├─ Unit tests for business logic only?
│ └─ getPlatformProxy (Vitest/Jest) → [patterns.md](./patterns.md#getplatformproxy)
│ Fast, no HTTP, direct binding access
│
├─ Integration tests with full runtime?
│ ├─ Single Worker?
│ │ └─ Miniflare API → [Quick Start](#quick-start)
│ │ Full control, programmatic access
│ │
│ ├─ Multiple Workers + service bindings?
│ │ └─ Miniflare workers array → [configuration.md](./configuration.md#multiple-workers)
│ │ Shared storage, inter-worker calls
│ │
│ └─ Vitest test runner integration?
│ └─ vitest-pool-workers → [patterns.md](./patterns.md#vitest-pool-workers)
│ Full Workers env in Vitest
│
└─ Local dev server?
└─ wrangler dev (not Miniflare)
Hot reload, automatic configUse Miniflare for:
- Integration tests with full Worker runtime
- Testing bindings/storage locally
- Multiple Workers with service bindings
- Programmatic event dispatch (fetch, queue, scheduled)
Use getPlatformProxy for:
- Fast unit tests of business logic
- Testing without HTTP overhead
- Vitest/Jest environments
Use Wrangler for:
- Local development workflow
- Production deployments
Setup
npm i -D miniflareRequires ES modules in package.json:
{"type": "module"}Quick Start
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();Reading Order
New to Miniflare? Start here:
- Quick Start - Running in 2 minutes
- When to Use - Choose your testing approach
- patterns.md - Testing patterns (getPlatformProxy, Vitest, node:test)
- configuration.md - Configure bindings, storage, multiple workers
Troubleshooting:
- gotchas.md - Common errors and debugging
API reference:
- api.md - Complete method reference
See Also
- wrangler - CLI tool that embeds Miniflare for
wrangler dev - workerd - Runtime that powers Miniflare
- workers - Workers runtime API documentation
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/network-interconnect/README.md`)
Cloudflare Network Interconnect (CNI)
Private, high-performance connectivity to Cloudflare's network. Enterprise-only.
Connection Types
Direct: Physical fiber in shared datacenter. 10/100 Gbps. You order cross-connect.
Partner: Virtual via Console Connect, Equinix, Megaport, etc. Managed via partner SDN.
Cloud: AWS Direct Connect or GCP Cloud Interconnect. Magic WAN only.
Dataplane Versions
v1 (Classic): GRE tunnel support, VLAN/BFD/LACP, asymmetric MTU (1500↓/1476↑), peering support.
v2 (Beta): No GRE, 1500 MTU both ways, no VLAN/BFD/LACP yet, ECMP instead.
Use Cases
- Magic Transit DSR: DDoS protection, egress via ISP (v1/v2)
- Magic Transit + Egress: DDoS + egress via CF (v1/v2)
- Magic WAN + Zero Trust: Private backbone (v1 needs GRE, v2 native)
- Peering: Public routes at PoP (v1 only)
- App Security: WAF/Cache/LB (v1/v2 over Magic Transit)
Prerequisites
- Enterprise plan
- IPv4 /24+ or IPv6 /48+ prefixes
- BGP ASN for v1
- See locations PDF
Specs
- /31 point-to-point subnets
- 10km max optical distance
- 10G: 10GBASE-LR single-mode
- 100G: 100GBASE-LR4 single-mode
- No SLA (free service)
- Backup Internet required
Throughput
| Direction | 10G | 100G |
|---|---|---|
| CF → Customer | 10 Gbps | 100 Gbps |
| Customer → CF (peering) | 10 Gbps | 100 Gbps |
| Customer → CF (Magic) | 1 Gbps/tunnel or CNI | 1 Gbps/tunnel or CNI |
Timeline
2-4 weeks typical. Steps: request → config review → order connection → configure → test → enable health checks → activate → monitor.
In This Reference
- configuration.md - BGP, routing, setup
- api.md - API endpoints, SDKs
- patterns.md - HA, hybrid cloud, failover
- gotchas.md - Troubleshooting, limits
Reading Order by Task
| Task | Files to Load |
|---|---|
| Initial setup | README → configuration.md → api.md |
| Create interconnect via API | api.md → gotchas.md |
| Design HA architecture | patterns.md → README |
| Troubleshoot connection | gotchas.md → configuration.md |
| Cloud integration (AWS/GCP) | configuration.md → patterns.md |
| Monitor + alerts | configuration.md |
Automation Boundary
API-Automatable:
- List/create/delete interconnects (Direct, Partner)
- List available slots
- Get interconnect status
- Download LOA PDF
- Create/update CNI objects (BGP config)
- Query settings
Requires Account Team:
- Initial request approval
- AWS Direct Connect setup (send LOA+VLAN to CF)
- GCP Cloud Interconnect final activation
- Partner interconnect acceptance (Equinix, Megaport)
- VLAN assignment (v1)
- Configuration document generation (v1)
- Escalations + troubleshooting support
Cannot Be Automated:
- Physical cross-connect installation (Direct)
- Partner portal operations (virtual circuit ordering)
- AWS/GCP portal operations
- Maintenance window coordination
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/observability/README.md`)
Cloudflare Observability Skill Reference
Purpose: Comprehensive guidance for implementing observability in Cloudflare Workers, covering traces, logs, metrics, and analytics.
Scope: Cloudflare Observability features ONLY - Workers Logs, Traces, Analytics Engine, Logpush, Metrics & Analytics, and OpenTelemetry exports.
Decision Tree: Which File to Load?
Use this to route to the correct file without loading all content:
├─ "How do I enable/configure X?" → configuration.md
├─ "What's the API/method/binding for X?" → api.md
├─ "How do I implement X pattern?" → patterns.md
│ ├─ Usage tracking/billing → patterns.md
│ ├─ Error tracking → patterns.md
│ ├─ Performance monitoring → patterns.md
│ ├─ Multi-tenant tracking → patterns.md
│ ├─ Tail Worker filtering → patterns.md
│ └─ OpenTelemetry export → patterns.md
└─ "Why isn't X working?" / "Limits?" → gotchas.mdReading Order
Load files in this order based on task:
| Task Type | Load Order | Reason |
|---|---|---|
| Initial setup | configuration.md → gotchas.md | Setup first, avoid pitfalls |
| Implement feature | patterns.md → api.md → gotchas.md | Pattern → API details → edge cases |
| Debug issue | gotchas.md → configuration.md | Common issues first |
| Query data | api.md → patterns.md | API syntax → query examples |
Product Overview
Workers Logs
- What: Console output from Workers (console.log/warn/error)
- Access: Dashboard (Real-time Logs), Logpush, Tail Workers
- Cost: Free (included with all Workers)
- Retention: Real-time only (no historical storage in dashboard)
Workers Traces
- What: Execution traces with timing, CPU usage, outcome
- Access: Dashboard (Workers Analytics → Traces), Logpush
- Cost: $0.10/1M spans (GA pricing starts March 1, 2026), 10M free/month
- Retention: 14 days included
Analytics Engine
- What: High-cardinality event storage and SQL queries
- Access: SQL API, Dashboard (Analytics → Analytics Engine)
- Cost: $0.25/1M writes beyond 10M free/month
- Retention: 90 days (configurable up to 1 year)
Tail Workers
- What: Workers that receive logs/traces from other Workers
- Use Cases: Log filtering, transformation, external export
- Cost: Standard Workers pricing
Logpush
- What: Stream logs to external storage (S3, R2, Datadog, etc.)
- Access: Dashboard, API
- Cost: Requires Business/Enterprise plan
Pricing Summary (2026)
| Feature | Free Tier | Cost Beyond Free Tier | Plan Requirement |
|---|---|---|---|
| Workers Logs | Unlimited | Free | Any |
| Workers Traces | 10M spans/month | $0.10/1M spans | Paid Workers (GA: March 1, 2026) |
| Analytics Engine | 10M writes/month | $0.25/1M writes | Paid Workers |
| Logpush | N/A | Included in plan | Business/Enterprise |
In This Reference
- configuration.md - Setup, deployment, configuration (Logs, Traces, Analytics Engine, Tail Workers, Logpush)
- api.md - API endpoints, methods, interfaces (GraphQL, SQL, bindings, types)
- patterns.md - Common patterns, use cases, examples (billing, monitoring, error tracking, exports)
- gotchas.md - Troubleshooting, best practices, limitations (common errors, performance gotchas, pricing)
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pages-functions/README.md`)
Cloudflare Pages Functions
Serverless functions on Cloudflare Pages using Workers runtime. Full-stack dev with file-based routing.
Quick Navigation
Need to...
| Task | Go to |
|---|---|
| Set up TypeScript types | configuration.md - TypeScript Setup |
| Configure bindings (KV, D1, R2) | configuration.md - wrangler.jsonc |
| Access request/env/params | api.md - EventContext |
| Add middleware or auth | patterns.md - Middleware, Auth |
| Background tasks (waitUntil) | patterns.md - Background Tasks |
| Debug errors or check limits | gotchas.md - Common Errors, Limits |
Decision Tree: Is This Pages Functions?
Need serverless backend?
├─ Yes, for a static site → Pages Functions
├─ Yes, standalone API → Workers
└─ Just static hosting → Pages (no functions)
Have existing Worker?
├─ Complex routing logic → Use _worker.js (Advanced Mode)
└─ Simple routes → Migrate to /functions (File-Based)
Framework-based?
├─ Next.js/SvelteKit/Remix → Uses _worker.js automatically
└─ Vanilla/HTML/React SPA → Use /functionsFile-Based Routing
/functions
├── index.js → /
├── api.js → /api
├── users/
│ ├── index.js → /users/
│ ├── [user].js → /users/:user
│ └── [[catchall]].js → /users/*
└── _middleware.js → runs on all routesRules:
index.js→ directory root- Trailing slash optional
- Specific routes precede catch-alls
- Falls back to static if no match
Dynamic Routes
Single segment [param] → string:
// /functions/users/[user].js
export function onRequest(context) {
return new Response(`Hello ${context.params.user}`);
}
// Matches: /users/neviMulti-segment [[param]] → array:
// /functions/users/[[catchall]].js
export function onRequest(context) {
return new Response(JSON.stringify(context.params.catchall));
}
// Matches: /users/nevi/foobar → ["nevi", "foobar"]Key Features
- Method handlers:
onRequestGet,onRequestPost, etc. - Middleware:
_middleware.jsfor cross-cutting concerns - Bindings: KV, D1, R2, Durable Objects, Workers AI, Service bindings
- TypeScript: Full type support via
wrangler typescommand - Advanced mode: Use
_worker.jsfor custom routing logic
Reading Order
New to Pages Functions? Start here:
- README.md - Overview, routing, decision tree (you are here)
- configuration.md - TypeScript setup, wrangler.jsonc, bindings
- api.md - EventContext, handlers, bindings reference
- patterns.md - Middleware, auth, CORS, rate limiting, caching
- gotchas.md - Common errors, debugging, limits
Quick reference lookup:
- Bindings table → api.md
- Error diagnosis → gotchas.md
- TypeScript setup → configuration.md
See Also
- pages - Pages platform overview and static site deployment
- workers - Workers runtime API reference
- d1 - D1 database integration with Pages Functions
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pages/README.md`)
Cloudflare Pages
JAMstack platform for full-stack apps on Cloudflare's global network.
Key Features
- Git-based deploys: Auto-deploy from GitHub/GitLab
- Preview deployments: Unique URL per branch/PR
- Pages Functions: File-based serverless routing (Workers runtime)
- Static + dynamic: Smart asset caching + edge compute
- Smart Placement: Automatic function optimization based on traffic patterns
- Framework optimized: SvelteKit, Astro, Nuxt, Qwik, Solid Start
Deployment Methods
1. Git Integration (Production)
Dashboard → Workers & Pages → Create → Connect to Git → Configure build
2. Direct Upload
npx wrangler pages deploy ./dist --project-name=my-project
npx wrangler pages deploy ./dist --project-name=my-project --branch=staging3. C3 CLI
npm create cloudflare@latest my-app
# Select framework → auto-setup + deployvs Workers
- Pages: Static sites, JAMstack, frameworks, git workflow, file-based routing
- Workers: Pure APIs, complex routing, WebSockets, scheduled tasks, email handlers
- Combine: Pages Functions use Workers runtime, can bind to Workers
Quick Start
# Create
npm create cloudflare@latest
# Local dev
npx wrangler pages dev ./dist
# Deploy
npx wrangler pages deploy ./dist --project-name=my-project
# Types
npx wrangler types --path='./functions/types.d.ts'
# Secrets
echo "value" | npx wrangler pages secret put KEY --project-name=my-project
# Logs
npx wrangler pages deployment tail --project-name=my-projectResources
Reading Order
New to Pages? Start here:
- README.md (you are here) - Overview & quick start
- configuration.md - Project setup, wrangler.jsonc, bindings
- api.md - Functions API, routing, context
- patterns.md - Common implementations
- gotchas.md - Troubleshooting & pitfalls
Quick reference? Jump to relevant file above.
In This Reference
- configuration.md - wrangler.jsonc, build, env vars, Smart Placement
- api.md - Functions API, bindings, context, advanced mode
- patterns.md - Full-stack patterns, framework integration
- gotchas.md - Build issues, limits, debugging, framework warnings
See Also
- pages-functions - File-based routing, middleware
- d1 - SQL database for Pages Functions
- kv - Key-value storage for caching/state
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pipelines/README.md`)
Cloudflare Pipelines
ETL streaming platform for ingesting, transforming, and loading data into R2 with SQL transformations.
Overview
Pipelines provides:
- Streams: Durable event buffers (HTTP/Workers ingestion)
- Pipelines: SQL-based transformations
- Sinks: R2 destinations (Iceberg tables or Parquet/JSON files)
Status: Open beta (Workers Paid plan)
Pricing: No charge beyond standard R2 storage/operations
Architecture
Data Sources → Streams → Pipelines (SQL) → Sinks → R2
↑ ↓ ↓
HTTP/Workers Transform Iceberg/Parquet| Component | Purpose | Key Feature |
|---|---|---|
| Streams | Event ingestion | Structured (validated) or unstructured |
| Pipelines | Transform with SQL | Immutable after creation |
| Sinks | Write to R2 | Exactly-once delivery |
Quick Start
# Interactive setup (recommended)
npx wrangler pipelines setupMinimal Worker example:
interface Env {
STREAM: Pipeline;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const event = { user_id: "123", event_type: "purchase", amount: 29.99 };
// Fire-and-forget pattern
ctx.waitUntil(env.STREAM.send([event]));
return new Response('OK');
}
} satisfies ExportedHandler<Env>;Which Sink Type?
Need SQL queries on data?
→ R2 Data Catalog (Iceberg)
✅ ACID transactions, time-travel, schema evolution
❌ More setup complexity (namespace, table, catalog token)
Just file storage/archival?
→ R2 Storage (Parquet)
✅ Simple, direct file access
❌ No built-in SQL queries
Using external tools (Spark/Athena)?
→ R2 Storage (Parquet with partitioning)
✅ Standard format, partition pruning for performance
❌ Must manage schema compatibility yourselfCommon Use Cases
- Analytics pipelines: Clickstream, telemetry, server logs
- Data warehousing: ETL into queryable Iceberg tables
- Event processing: Mobile/IoT with enrichment
- Ecommerce analytics: User events, purchases, views
Reading Order
New to Pipelines? Start here:
- configuration.md - Setup streams, sinks, pipelines
- api.md - Send events, TypeScript types, SQL functions
- patterns.md - Best practices, integrations, complete example
- gotchas.md - Critical warnings, troubleshooting
Task-based routing:
- Setup pipeline → configuration.md
- Send/query data → api.md
- Implement pattern → patterns.md
- Debug issue → gotchas.md
In This Reference
- configuration.md - wrangler.jsonc bindings, schema definition, sink options, CLI commands
- api.md - Pipeline binding interface, send() method, HTTP ingest, SQL function reference
- patterns.md - Fire-and-forget, schema validation with Zod, integrations, performance tuning
- gotchas.md - Silent validation failures, immutable pipelines, latency expectations, limits
See Also
- r2 - R2 storage backend for sinks
- queues - Compare with Queues for async processing
- workers - Worker runtime for event ingestion
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pulumi/README.md`)
Cloudflare Pulumi Provider
Expert guidance for Cloudflare Pulumi Provider (@pulumi/cloudflare).
Overview
Programmatic management of Cloudflare resources: Workers, Pages, D1, KV, R2, DNS, Queues, etc.
Packages:
- TypeScript/JS:
@pulumi/cloudflare - Python:
pulumi-cloudflare - Go:
github.com/pulumi/pulumi-cloudflare/sdk/v6/go/cloudflare - .NET:
Pulumi.Cloudflare
Version: v6.x
Core Principles
- Use API tokens (not legacy API keys)
- Store accountId in stack config
- Match binding names across code/config
- Use
module: truefor ES modules - Set
compatibilityDateto lock behavior
Authentication
import * as cloudflare from "@pulumi/cloudflare";
// API Token (recommended): CLOUDFLARE_API_TOKEN env
const provider = new cloudflare.Provider("cf", { apiToken: process.env.CLOUDFLARE_API_TOKEN });
// API Key (legacy): CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL env
const provider = new cloudflare.Provider("cf", { apiKey: process.env.CLOUDFLARE_API_KEY, email: process.env.CLOUDFLARE_EMAIL });
// API User Service Key: CLOUDFLARE_API_USER_SERVICE_KEY env
const provider = new cloudflare.Provider("cf", { apiUserServiceKey: process.env.CLOUDFLARE_API_USER_SERVICE_KEY });Setup
Pulumi.yaml:
name: my-cloudflare-app
runtime: nodejs
config:
cloudflare:apiToken:
value: ${CLOUDFLARE_API_TOKEN}Pulumi.
config:
cloudflare:accountId: "abc123..."index.ts:
import * as pulumi from "@pulumi/pulumi";
import * as cloudflare from "@pulumi/cloudflare";
const accountId = new pulumi.Config("cloudflare").require("accountId");Common Resource Types
Provider- Provider configWorkerScript- WorkerWorkersKvNamespace- KVR2Bucket- R2D1Database- D1Queue- QueuePagesProject- PagesDnsRecord- DNSWorkerRoute- Worker routeWorkersDomain- Custom domain
Key Properties
accountId- Required for most resourceszoneId- Required for DNS/domainname/title- Resource identifier*Bindings- Connect resources to Workers
Reading Order
| Order | File | What | When to Read |
|---|---|---|---|
| 1 | configuration.md | Resource config for Workers/KV/D1/R2/Queues/Pages | First time setup, resource reference |
| 2 | patterns.md | Architecture patterns, multi-env, component resources | Building complex apps, best practices |
| 3 | api.md | Outputs, dependencies, imports, dynamic providers | Advanced features, integrations |
| 4 | gotchas.md | Common errors, troubleshooting, limits | Debugging, deployment issues |
In This Reference
- configuration.md - Provider config, stack setup, Workers/bindings
- api.md - Resource types, Workers script, KV/D1/R2/queues/Pages
- patterns.md - Multi-env, secrets, CI/CD, stack management
- gotchas.md - State issues, deployment failures, limits
See Also
- terraform - Alternative IaC for Cloudflare
- wrangler - CLI deployment alternative
- workers - Worker runtime documentation
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/queues/README.md`)
Cloudflare Queues
Flexible message queuing for async task processing with guaranteed at-least-once delivery and configurable batching.
Overview
Queues provide:
- At-least-once delivery guarantee
- Push-based (Worker) and pull-based (HTTP) consumers
- Configurable batching and retries
- Dead Letter Queues (DLQ)
- Delays up to 12 hours
Use cases: Async processing, API buffering, rate limiting, event workflows, deferred jobs
Quick Start
wrangler queues create my-queue
wrangler queues consumer add my-queue my-worker// Producer
await env.MY_QUEUE.send({ userId: 123, action: 'notify' });
// Consumer (with proper error handling)
export default {
async queue(batch: MessageBatch, env: Env): Promise<void> {
for (const msg of batch.messages) {
try {
await process(msg.body);
msg.ack();
} catch (error) {
msg.retry({ delaySeconds: 60 });
}
}
}
};Critical Warnings
Before using Queues, understand these production mistakes:
- Uncaught errors retry ENTIRE batch (not just failed message). Always use per-message try/catch.
- Messages not ack'd/retry'd will auto-retry forever until max_retries. Always explicitly handle each message.
See gotchas.md for detailed solutions.
Core Operations
| Operation | Purpose | Limit |
|---|---|---|
send(body, options?) |
Publish message | 128 KB |
sendBatch(messages) |
Bulk publish | 100 msgs/256 KB |
message.ack() |
Acknowledge success | - |
message.retry(options?) |
Retry with delay | - |
batch.ackAll() |
Ack entire batch | - |
Architecture
[Producer Worker] → [Queue] → [Consumer Worker/HTTP] → [Processing]- Max 10,000 queues per account
- 5,000 msgs/second per queue
- 4-14 day retention (configurable)
Reading Order
New to Queues? Start here:
- configuration.md - Set up queues, bindings, consumers
- api.md - Send messages, handle batches, ack/retry patterns
- patterns.md - Real-world examples and integrations
- gotchas.md - Critical warnings and troubleshooting
Task-based routing:
- Setup queue → configuration.md
- Send/receive messages → api.md
- Implement specific pattern → patterns.md
- Debug/troubleshoot → gotchas.md
In This Reference
- configuration.md - wrangler.jsonc setup, producer/consumer config, DLQ, content types
- api.md - Send/batch methods, queue handler, ack/retry rules, type-safe patterns
- patterns.md - Async tasks, buffering, rate limiting, D1/Workflows/DO integrations
- gotchas.md - Critical batch error handling, idempotency, error classification
See Also
- workers - Worker runtime for producers/consumers
- r2 - Process R2 event notifications via queues
- d1 - Batch write to D1 from queue consumers
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2-data-catalog/README.md`)
Cloudflare R2 Data Catalog Skill Reference
Expert guidance for Cloudflare R2 Data Catalog - Apache Iceberg catalog built into R2 buckets.
Reading Order
New to R2 Data Catalog? Start here:
- Read "What is R2 Data Catalog?" and "When to Use" below
- configuration.md - Enable catalog, create tokens
- patterns.md - PyIceberg setup and common patterns
- api.md - REST API reference as needed
- gotchas.md - Troubleshooting when issues arise
Quick reference? Jump to:
What is R2 Data Catalog?
R2 Data Catalog is a managed Apache Iceberg REST catalog built directly into R2 buckets. It provides:
- Apache Iceberg tables - ACID transactions, schema evolution, time-travel queries
- Zero-egress costs - Query from any cloud/region without data transfer fees
- Standard REST API - Works with Spark, PyIceberg, Snowflake, Trino, DuckDB
- No infrastructure - Fully managed, no catalog servers to run
- Public beta - Available to all R2 subscribers, no extra cost beyond R2 storage
What is Apache Iceberg?
Open table format for analytics datasets in object storage. Features:
- ACID transactions - Safe concurrent reads/writes
- Metadata optimization - Fast queries without full scans
- Schema evolution - Add/rename/delete columns without rewrites
- Time-travel - Query historical snapshots
- Partitioning - Organize data for efficient queries
When to Use
Use R2 Data Catalog for:
- Log analytics - Store and query application/system logs
- Data lakes/warehouses - Analytical datasets queried by multiple engines
- BI pipelines - Aggregate data for dashboards and reports
- Multi-cloud analytics - Share data across clouds without egress fees
- Time-series data - Event streams, metrics, sensor data
Don't use for:
- Transactional workloads - Use D1 or external database instead
- Sub-second latency - Iceberg optimized for batch/analytical queries
- Small datasets (<1GB) - Setup overhead not worth it
- Unstructured data - Store files directly in R2, not as Iceberg tables
Architecture
┌─────────────────────────────────────────────────┐
│ Query Engines │
│ (PyIceberg, Spark, Trino, Snowflake, DuckDB) │
└────────────────┬────────────────────────────────┘
│
│ REST API (OAuth2 token)
▼
┌─────────────────────────────────────────────────┐
│ R2 Data Catalog (Managed Iceberg REST Catalog)│
│ • Namespace/table metadata │
│ • Transaction coordination │
│ • Snapshot management │
└────────────────┬────────────────────────────────┘
│
│ Vended credentials
▼
┌─────────────────────────────────────────────────┐
│ R2 Bucket Storage │
│ • Parquet data files │
│ • Metadata files │
│ • Manifest files │
└─────────────────────────────────────────────────┘Key concepts:
- Catalog URI - REST endpoint for catalog operations (e.g.,
https://<account-id>.r2.cloudflarestorage.com/iceberg/<bucket>) - Warehouse - Logical grouping of tables (typically same as bucket name)
- Namespace - Schema/database containing tables (e.g.,
logs,analytics) - Table - Iceberg table with schema, data files, snapshots
- Vended credentials - Temporary S3 credentials catalog provides for data access
Limits
| Resource | Limit | Notes |
|---|---|---|
| Namespaces per catalog | No hard limit | Organize tables logically |
| Tables per namespace | <10,000 recommended | Performance degrades beyond this |
| Files per table | <100,000 recommended | Run compaction regularly |
| Snapshots per table | Configurable retention | Expire >7 days old |
| Partitions per table | 100-1,000 optimal | Too many = slow metadata ops |
| Table size | Same as R2 bucket | 10GB-10TB+ common |
| API rate limits | Standard R2 API limits | Shared with R2 storage operations |
| Target file size | 128-512 MB | After compaction |
Current Status
Public Beta (as of Jan 2026)
- Available to all R2 subscribers
- No extra cost beyond standard R2 storage/operations
- Production-ready, but breaking changes possible
- Supports: namespaces, tables, snapshots, compaction, time-travel, table maintenance
Decision Tree: Is R2 Data Catalog Right For You?
Start → Need analytics on object storage data?
│
├─ No → Use R2 directly for object storage
│
└─ Yes → Dataset >1GB with structured schema?
│
├─ No → Too small, use R2 + ad-hoc queries
│
└─ Yes → Need ACID transactions or schema evolution?
│
├─ No → Consider simpler solutions (Parquet on R2)
│
└─ Yes → Need multi-cloud/multi-tool access?
│
├─ No → D1 or external DB may be simpler
│
└─ Yes → ✅ Use R2 Data CatalogQuick check: If you answer "yes" to all:
- Dataset >1GB and growing
- Structured/tabular data (logs, events, metrics)
- Multiple query tools or cloud environments
- Need versioning, schema changes, or concurrent access
→ R2 Data Catalog is a good fit.
In This Reference
- configuration.md - Enable catalog, create API tokens, connect clients
- api.md - REST endpoints, operations, maintenance
- patterns.md - PyIceberg examples, common use cases
- gotchas.md - Troubleshooting, best practices, limitations
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2-sql/README.md`)
Cloudflare R2 SQL Skill Reference
Expert guidance for Cloudflare R2 SQL - serverless distributed query engine for Apache Iceberg tables.
Reading Order
New to R2 SQL? Start here:
- Read "What is R2 SQL?" and "When to Use" below
- configuration.md - Enable catalog, create tokens
- patterns.md - Wrangler CLI and integration examples
- api.md - SQL syntax and query reference
- gotchas.md - Limitations and troubleshooting
Quick reference? Jump to:
What is R2 SQL?
R2 SQL is Cloudflare's serverless distributed analytics query engine for querying Apache Iceberg tables in R2 Data Catalog. Features:
- Serverless - No clusters to manage, no infrastructure
- Distributed - Leverages Cloudflare's global network for parallel execution
- SQL interface - Familiar SQL syntax for analytics queries
- Zero egress fees - Query from any cloud/region without data transfer costs
- Open beta - Free during beta (standard R2 storage costs apply)
What is Apache Iceberg?
Open table format for large-scale analytics datasets in object storage:
- ACID transactions - Safe concurrent reads/writes
- Metadata optimization - Fast queries without full table scans
- Schema evolution - Add/rename/drop columns without rewrites
- Partitioning - Organize data for efficient pruning
When to Use
Use R2 SQL for:
- Log analytics - Query application/system logs with WHERE filters and aggregations
- BI dashboards - Generate reports from large analytical datasets
- Fraud detection - Analyze transaction patterns with GROUP BY/HAVING
- Multi-cloud analytics - Query data from any cloud without egress fees
- Ad-hoc exploration - Run SQL queries on Iceberg tables via Wrangler CLI
Don't use R2 SQL for:
- Workers/Pages runtime - R2 SQL has no Workers binding, use HTTP API from external systems
- Real-time queries (<100ms) - Optimized for analytical batch queries, not OLTP
- Complex joins/CTEs - Limited SQL feature set (no JOINs, subqueries, CTEs currently)
- Small datasets (<1GB) - Setup overhead not justified
Decision Tree: Need to Query R2 Data?
Do you need to query structured data in R2?
├─ YES, data is in Iceberg tables
│ ├─ Need SQL interface? → Use R2 SQL (this reference)
│ ├─ Need Python API? → See r2-data-catalog reference (PyIceberg)
│ └─ Need other engine? → See r2-data-catalog reference (Spark, Trino, etc.)
│
├─ YES, but not in Iceberg format
│ ├─ Streaming data? → Use Pipelines to write to Data Catalog, then R2 SQL
│ └─ Static files? → Use PyIceberg to create Iceberg tables, then R2 SQL
│
└─ NO, just need object storage → Use R2 reference (not R2 SQL)Architecture Overview
Query Planner:
- Top-down metadata investigation with multi-layer pruning
- Partition-level, column-level, and row-group pruning
- Streaming pipeline - execution starts before planning completes
- Early termination with LIMIT - stops when result complete
Query Execution:
- Coordinator distributes work to workers across Cloudflare network
- Workers run Apache DataFusion for parallel query execution
- Parquet column pruning - reads only required columns
- Ranged reads from R2 for efficiency
Aggregation Strategies:
- Scatter-gather - simple aggregations (SUM, COUNT, AVG)
- Shuffling - ORDER BY/HAVING on aggregates via hash partitioning
Quick Start
# 1. Enable R2 Data Catalog on bucket
npx wrangler r2 bucket catalog enable my-bucket
# 2. Create API token (Admin Read & Write)
# Dashboard: R2 → Manage API tokens → Create API token
# 3. Set environment variable
export WRANGLER_R2_SQL_AUTH_TOKEN=<your-token>
# 4. Run query
npx wrangler r2 sql query "my-bucket" "SELECT * FROM default.my_table LIMIT 10"Important Limitations
CRITICAL: No Workers Binding
- R2 SQL cannot be called directly from Workers/Pages code
- For programmatic access, use HTTP API from external systems
- Or query via PyIceberg, Spark, etc. (see r2-data-catalog reference)
SQL Feature Set:
- No JOINs, CTEs, subqueries, window functions
- ORDER BY supports aggregation columns (not just partition keys)
- LIMIT max 10,000 (default 500)
- See gotchas.md for complete limitations
In This Reference
- configuration.md - Enable catalog, create API tokens
- api.md - SQL syntax, functions, operators, data types
- patterns.md - Wrangler CLI, HTTP API, Pipelines, PyIceberg
- gotchas.md - Limitations, troubleshooting, performance tips
See Also
- r2-data-catalog - PyIceberg, REST API, external engines
- pipelines - Streaming ingestion to Iceberg tables
- r2 - R2 object storage fundamentals
- Cloudflare R2 SQL Docs
- R2 SQL Deep Dive Blog
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2/README.md`)
Cloudflare R2 Object Storage
S3-compatible object storage with zero egress fees, optimized for large file storage and delivery.
Overview
R2 provides:
- S3-compatible API (Workers API + S3 REST)
- Zero egress fees globally
- Strong consistency for writes/deletes
- Storage classes (Standard/Infrequent Access)
- SSE-C encryption support
Use cases: Media storage, backups, static assets, user uploads, data lakes
Quick Start
wrangler r2 bucket create my-bucket --location=enam
wrangler r2 object put my-bucket/file.txt --file=./local.txt// 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);Core Operations
| Method | Purpose | Returns |
|---|---|---|
put(key, value, options?) |
Upload object | R2Object | null |
get(key, options?) |
Download object | R2ObjectBody | R2Object | null |
head(key) |
Get metadata only | R2Object | null |
delete(keys) |
Delete object(s) | Promise<void> |
list(options?) |
List objects | R2Objects |
Storage Classes
- Standard: Frequent access, low latency reads
- InfrequentAccess: 30-day minimum storage, retrieval fees, lower storage cost
Event Notifications
R2 integrates with Cloudflare Queues for reactive workflows:
// wrangler.jsonc
{
"event_notifications": [{
"queue": "r2-notifications",
"actions": ["PutObject", "DeleteObject"]
}]
}
// Consumer
async queue(batch: MessageBatch, env: Env) {
for (const message of batch.messages) {
const event = message.body; // { action, bucket, object, timestamps }
if (event.action === 'PutObject') {
// Process upload: thumbnail generation, virus scan, etc.
}
}
}Reading Order
First-time users: README → configuration.md → api.md → patterns.md
Specific tasks:
- Setup: configuration.md
- Client uploads: patterns.md (presigned URLs)
- Public static site: patterns.md (public access + custom domain)
- Processing uploads: README (event notifications) + queues reference
- Debugging: gotchas.md
In This Reference
- configuration.md - Bindings, S3 SDK, CORS, lifecycles, token scopes
- api.md - Workers API, multipart, conditional requests, presigned URLs
- patterns.md - Streaming, caching, client uploads, public buckets
- gotchas.md - List truncation, etag format, stream length, S3 SDK region
See Also
- workers - Worker runtime and fetch handlers
- kv - Metadata storage for R2 objects
- d1 - Store R2 URLs in relational database
- queues - Process R2 uploads asynchronously
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/realtime-sfu/README.md`)
Cloudflare Realtime SFU Reference
Expert guidance for building real-time audio/video/data applications using Cloudflare Realtime SFU (Selective Forwarding Unit).
Reading Order
| Task | Files | ~Tokens |
|---|---|---|
| New project | README → configuration | ~1200 |
| Implement publish/subscribe | README → api | ~1600 |
| Add PartyTracks | patterns (PartyTracks section) | ~800 |
| Build presence system | patterns (DO section) | ~800 |
| Debug connection issues | gotchas | ~700 |
| Scale to millions | patterns (Cascading section) | ~600 |
| Add simulcast | patterns (Advanced section) | ~500 |
| Configure TURN | configuration (TURN section) | ~400 |
In This Reference
- configuration.md - Setup, deployment, environment variables, Wrangler config
- api.md - Sessions, tracks, endpoints, request/response patterns
- patterns.md - Architecture patterns, use cases, integration examples
- gotchas.md - Common issues, debugging, performance, security
Quick Start
Cloudflare Realtime SFU: WebRTC infrastructure on global network (310+ cities). Anycast routing, no regional constraints, pub/sub model.
Core concepts:
- Sessions: WebRTC PeerConnection to Cloudflare edge
- Tracks: Audio/video/data channels you publish or subscribe to
- No rooms: Build presence layer yourself via track sharing (see patterns.md)
Mental model: Your client establishes one WebRTC session, publishes tracks (audio/video), shares track IDs via your backend, others subscribe to your tracks using track IDs + your session ID.
Choose Your Approach
| Approach | When to Use | Complexity |
|---|---|---|
| PartyTracks | Production apps with device switching, React | Low - Observable-based, handles reconnections |
| Raw API | Custom requirements, non-browser, learning | Medium - Full control, manual WebRTC lifecycle |
| RealtimeKit | End-to-end SDK with UI components | Lowest - Managed state, React hooks |
Recommendation: Start with PartyTracks for most production applications. See patterns.md for PartyTracks examples.
SFU vs RealtimeKit
- Realtime SFU: WebRTC infrastructure (this reference). Build your own signaling, presence, UI.
- RealtimeKit: SDK layer on top of SFU. Includes React hooks, state management, UI components. Part of Cloudflare AI platform.
Use SFU directly when you need custom signaling or non-React framework. Use RealtimeKit for faster development with React.
Setup
Dashboard: https://dash.cloudflare.com/?to=/:account/calls
Get CALLS_APP_ID and CALLS_APP_SECRET from dashboard, then see configuration.md for deployment.
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/realtimekit/README.md`)
Cloudflare RealtimeKit
Expert guidance for building real-time video and audio applications using Cloudflare RealtimeKit - a comprehensive SDK suite for adding customizable live video and voice to web or mobile applications.
Overview
RealtimeKit is Cloudflare's SDK suite built on Realtime SFU, abstracting WebRTC complexity with fast integration, pre-built UI components, global performance (300+ cities), and production features (recording, transcription, chat, polls).
Use cases: Team meetings, webinars, social video, audio calls, interactive plugins
Core Concepts
- App: Workspace grouping meetings, participants, presets, recordings. Use separate Apps for staging/production
- Meeting: Re-usable virtual room. Each join creates new Session
- Session: Live meeting instance. Created on first join, ends after last leave
- Participant: User added via REST API. Returns
authTokenfor client SDK. Do not reuse tokens - Preset: Reusable permission/UI template (permissions, meeting type, theme). Applied at participant creation
- Peer ID (
id): Unique per session, changes on rejoin - Participant ID (
userId): Persistent across sessions
Quick Start
1. Create App & Meeting (Backend)
# Create app
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/apps' \
-H 'Authorization: Bearer <api_token>' \
-d '{"name": "My RealtimeKit App"}'
# Create meeting
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/<app_id>/meetings' \
-H 'Authorization: Bearer <api_token>' \
-d '{"title": "Team Standup"}'
# Add participant
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/<app_id>/meetings/<meeting_id>/participants' \
-H 'Authorization: Bearer <api_token>' \
-d '{"name": "Alice", "preset_name": "host"}'
# Returns: { authToken }2. Client Integration
React:
import { RtkMeeting } from '@cloudflare/realtimekit-react-ui';
function App() {
return <RtkMeeting authToken="" onLeave={() => {}} />;
}Core SDK:
import RealtimeKitClient from '@cloudflare/realtimekit';
const meeting = new RealtimeKitClient({ authToken: '<token>', video: true, audio: true });
await meeting.join();Reading Order
| Task | Files |
|---|---|
| Quick integration | README only |
| Custom UI | README → patterns → api |
| Backend setup | README → configuration |
| Debug issues | gotchas |
| Advanced features | patterns → api |
RealtimeKit vs Realtime SFU
| Choose | When |
|---|---|
| RealtimeKit | Need pre-built UI, fast integration, React/Angular/HTML |
| Realtime SFU | Building from scratch, custom WebRTC, full control |
RealtimeKit is built on Realtime SFU but abstracts WebRTC complexity with UI components and SDKs.
Which Package?
Need pre-built meeting UI?
- React →
@cloudflare/realtimekit-react-ui(<RtkMeeting>) - Angular →
@cloudflare/realtimekit-angular-ui - HTML/Vanilla →
@cloudflare/realtimekit-ui
Need custom UI?
- Core SDK →
@cloudflare/realtimekit(RealtimeKitClient) - full control
Need raw WebRTC control?
- See
realtime-sfu/reference
In This Reference
- Configuration - Setup, installation, wrangler config
- API - Meeting object, REST API, SDK methods
- Patterns - Common workflows, code examples
- Gotchas - Common issues, troubleshooting
See Also
- Workers - Backend integration
- D1 - Meeting metadata storage
- R2 - Recording storage
- KV - Session management
Reference Links
- Official Docs: https://developers.cloudflare.com/realtime/realtimekit/
- API Reference: https://developers.cloudflare.com/api/resources/realtime_kit/
- Examples: https://github.com/cloudflare/realtimekit-web-examples
- Dashboard: https://dash.cloudflare.com/?to=/:account/realtime/kit
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/sandbox/README.md`)
Cloudflare Sandbox SDK
Secure isolated code execution in containers on Cloudflare's edge. Run untrusted code, manage files, expose services, integrate with AI agents.
Use cases: AI code execution, interactive dev environments, data analysis, CI/CD, code interpreters, multi-tenant execution.
Architecture
- Each sandbox = Durable Object + Container
- Persistent across requests (same ID = same sandbox)
- Isolated filesystem/processes/network
- Configurable sleep/wake for cost optimization
Quick Start
import { getSandbox, proxyToSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
type Env = { Sandbox: DurableObjectNamespace<Sandbox>; };
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// CRITICAL: proxyToSandbox MUST be called first for preview URLs
const proxyResponse = await proxyToSandbox(request, env);
if (proxyResponse) return proxyResponse;
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
const result = await sandbox.exec('python3 -c "print(2 + 2)"');
return Response.json({ output: result.stdout });
}
};wrangler.jsonc:
{
"name": "my-sandbox-worker",
"main": "src/index.ts",
"compatibility_date": "2025-01-01", // Use current date for new projects
"containers": [{
"class_name": "Sandbox",
"image": "./Dockerfile",
"instance_type": "lite", // lite | standard | heavy
"max_instances": 5
}],
"durable_objects": {
"bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }]
},
"migrations": [{
"tag": "v1",
"new_sqlite_classes": ["Sandbox"]
}]
}Dockerfile:
FROM docker.io/cloudflare/sandbox:latest
RUN pip3 install --no-cache-dir pandas numpy matplotlib
EXPOSE 8080 3000 # Required for wrangler devCore APIs
getSandbox(namespace, id, options?)→ Get/create sandboxsandbox.exec(command, options?)→ Execute commandsandbox.readFile(path)/writeFile(path, content)→ File opssandbox.startProcess(command, options)→ Background processsandbox.exposePort(port, options)→ Get preview URLsandbox.createSession(options)→ Isolated sessionsandbox.wsConnect(request, port)→ WebSocket proxysandbox.destroy()→ Terminate containersandbox.mountBucket(bucket, path, options)→ Mount S3 storage
Critical Rules
- ALWAYS call
proxyToSandbox()first - Same ID = reuse sandbox
- Use
/workspacefor persistent files normalizeId: truefor preview URLs- Retry on
CONTAINER_NOT_READY
In This Reference
- configuration.md - Config, CLI, environment setup
- api.md - Programmatic API, testing patterns
- patterns.md - Common workflows, CI/CD integration
- gotchas.md - Issues, limits, best practices
See Also
- durable-objects - Sandbox runs on DO infrastructure
- containers - Container runtime fundamentals
- workers - Entry point for sandbox requests
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/secrets-store/README.md`)
Cloudflare Secrets Store
Account-level encrypted secret management for Workers and AI Gateway.
Overview
Secrets Store: Centralized, account-level secrets, reusable across Workers
Worker Secrets: Per-Worker secrets (wrangler secret put)
Architecture
- Store: Container (1/account in beta)
- Secret: String ≤1024 bytes
- Scopes: Permission boundaries controlling access
workers: For Workers runtime accessai-gateway: For AI Gateway access- Secrets must have correct scope for binding to work
- Bindings: Connect secrets via
envobject
Regional Availability: Global except China Network (unavailable)
Access Control
- Super Admin: Full access
- Admin: Create/edit/delete secrets, view metadata
- Deployer: View metadata + bindings
- Reporter: View metadata only
API Token permissions: Account Secrets Store Edit/Read
Limits (Beta)
- 100 secrets/account
- 1 store/account
- 1024 bytes max/secret
- Production secrets count toward limit
When to Use
Use Secrets Store when:
- Multiple Workers share same credential
- Centralized management needed
- Compliance requires audit trail
- Team collaboration on secrets
Use Worker Secrets when:
- Secret unique to one Worker
- Simple single-Worker project
- No cross-Worker sharing needed
In This Reference
Reading Order by Task
| Task | Start Here | Then Read |
|---|---|---|
| Quick overview | README.md | - |
| First-time setup | README.md → configuration.md | api.md |
| Add secret to Worker | configuration.md | api.md |
| Implement access pattern | api.md | patterns.md |
| Debug errors | gotchas.md | api.md |
| Secret rotation | patterns.md | configuration.md |
| Best practices | gotchas.md | patterns.md |
Files
- configuration.md - Wrangler commands, binding config
- api.md - Binding API, get/put/delete operations
- patterns.md - Rotation, encryption, access control
- gotchas.md - Security issues, limits, best practices
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/smart-placement/README.md`)
Cloudflare Workers Smart Placement
Automatic workload placement optimization to minimize latency by running Workers closer to backend infrastructure rather than end users.
Core Concept
Smart Placement automatically analyzes Worker request duration across Cloudflare's global network and intelligently routes requests to optimal data center locations. Instead of defaulting to the location closest to the end user, Smart Placement can forward requests to locations closer to backend infrastructure when this reduces overall request duration.
When to Use
Enable Smart Placement when:
- Worker makes multiple round trips to backend services/databases
- Backend infrastructure is geographically concentrated
- Request duration dominated by backend latency rather than network latency from user
- Running backend logic in Workers (APIs, data aggregation, SSR with DB calls)
- Worker uses
fetchhandler (not RPC methods)
Do NOT enable for:
- Workers serving only static content or cached responses
- Workers without significant backend communication
- Pure edge logic (auth checks, redirects, simple transformations)
- Workers without fetch event handlers
- Workers with RPC methods or named entrypoints (only
fetchhandlers are affected) - Pages/Assets Workers with
run_worker_first = true(degrades asset serving)
Decision Tree
Does your Worker have a fetch handler?
├─ No → Smart Placement won't work (skip)
└─ Yes
│
Does it make multiple backend calls (DB/API)?
├─ No → Don't enable (won't help)
└─ Yes
│
Is backend geographically concentrated?
├─ No (globally distributed) → Probably won't help
└─ Yes or uncertain
│
Does it serve static assets with run_worker_first=true?
├─ Yes → Don't enable (will hurt performance)
└─ No → Enable Smart Placement
│
After 15min, check placement_status
├─ SUCCESS → Monitor metrics
├─ INSUFFICIENT_INVOCATIONS → Need more traffic
└─ UNSUPPORTED_APPLICATION → Disable (hurting performance)Key Architecture Pattern
Recommended: Split full-stack applications into separate Workers:
User → Frontend Worker (at edge, close to user)
↓ Service Binding
Backend Worker (Smart Placement enabled, close to DB/API)
↓
Database/Backend ServiceThis maintains fast, reactive frontends while optimizing backend latency.
Quick Start
// wrangler.jsonc
{
"placement": {
"mode": "smart" // or "off" to explicitly disable
}
}Deploy and wait 15 minutes for analysis. Check status via API or dashboard metrics.
To disable: Set "mode": "off" or remove placement field entirely (both equivalent).
Requirements
- Wrangler 2.20.0+
- Analysis time: Up to 15 minutes after enabling
- Traffic requirements: Consistent traffic from multiple global locations
- Available on all Workers plans (Free, Paid, Enterprise)
Placement Status Values
type PlacementStatus =
| undefined // Not yet analyzed
| 'SUCCESS' // Successfully optimized
| 'INSUFFICIENT_INVOCATIONS' // Not enough traffic
| 'UNSUPPORTED_APPLICATION'; // Made Worker slower (reverted)CLI Commands
# Deploy with Smart Placement
wrangler deploy
# Check placement status
curl -H "Authorization: Bearer $TOKEN" \
https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \
| jq .result.placement_status
# Monitor
wrangler tail your-worker-name --header cf-placementReading Order
First time? Start here:
- This README - understand core concepts and when to use Smart Placement
- configuration.md - set up wrangler.jsonc and understand limitations
- patterns.md - see practical examples for your use case
- api.md - monitor and verify Smart Placement is working
- gotchas.md - troubleshoot common issues
Quick lookup:
- "Should I enable Smart Placement?" → See "When to Use" above
- "How do I configure it?" → configuration.md
- "How do I split frontend/backend?" → patterns.md
- "Why isn't it working?" → gotchas.md
In This Reference
- configuration.md - wrangler.jsonc setup, mode values, validation rules
- api.md - Placement Status API, cf-placement header, monitoring
- patterns.md - Frontend/backend split, database workers, SSR patterns
- gotchas.md - Troubleshooting INSUFFICIENT_INVOCATIONS, performance issues
See Also
- workers - Worker runtime and fetch handlers
- d1 - D1 database that benefits from Smart Placement
- durable-objects - Durable Objects with backend logic
- bindings - Service bindings for frontend/backend split
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/snippets/README.md`)
Cloudflare Snippets Skill Reference
Description
Expert guidance for Cloudflare Snippets ONLY - a lightweight JavaScript-based edge logic platform for modifying HTTP requests and responses. Snippets run as part of the Ruleset Engine and are included at no additional cost on paid plans (Pro, Business, Enterprise).
What Are Snippets?
Snippets are JavaScript functions executed at the edge as part of Cloudflare's Ruleset Engine. Key characteristics:
- Execution time: 5ms CPU limit per request
- Size limit: 32KB per snippet
- Runtime: V8 isolate (subset of Workers APIs)
- Subrequests: 2-5 fetch calls depending on plan
- Cost: Included with Pro/Business/Enterprise plans
Snippets vs Workers Decision Matrix
| Factor | Choose Snippets If... | Choose Workers If... |
|---|---|---|
| Complexity | Simple request/response modifications | Complex business logic, routing, middleware |
| Execution time | <5ms sufficient | Need >5ms or variable time |
| Subrequests | 2-5 fetch calls sufficient | Need >5 subrequests or complex orchestration |
| Code size | <32KB sufficient | Need >32KB or npm dependencies |
| Cost | Want zero additional cost | Can afford $5/mo + usage |
| APIs | Need basic fetch, headers, URL | Need KV, D1, R2, Durable Objects, cron triggers |
| Deployment | Need rule-based triggers | Want custom routing logic |
Rule of thumb: Use Snippets for modifications, Workers for applications.
Execution Model
- Request arrives at Cloudflare edge
- Ruleset Engine evaluates snippet rules (filter expressions)
- If rule matches, snippet executes within 5ms limit
- Modified request/response continues through pipeline
- Response returned to client
Snippets execute synchronously in the request path - performance is critical.
Reading Order
- configuration.md - Start here: setup, deployment methods (Dashboard/API/Terraform)
- api.md - Core APIs: Request, Response, headers,
request.cfproperties - patterns.md - Real-world examples: geo-routing, A/B tests, security headers
- gotchas.md - Troubleshooting: common errors, performance tips, API limitations
In This Reference
- configuration.md - Setup, deployment, configuration
- api.md - API endpoints, methods, interfaces
- patterns.md - Common patterns, use cases, examples
- gotchas.md - Troubleshooting, best practices, limitations
Quick Start
// Snippet: Add security headers
export default {
async fetch(request) {
const response = await fetch(request);
const newResponse = new Response(response.body, response);
newResponse.headers.set("X-Frame-Options", "DENY");
newResponse.headers.set("X-Content-Type-Options", "nosniff");
return newResponse;
}
}Deploy via Dashboard (Rules → Snippets) or API/Terraform. See configuration.md for details.
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/spectrum/README.md`)
Cloudflare Spectrum Skill Reference
Overview
Cloudflare Spectrum provides security and acceleration for ANY TCP or UDP-based application. It's a global Layer 4 (L4) reverse proxy running on Cloudflare's edge nodes that routes MQTT, email, file transfer, version control, games, and more through Cloudflare to mask origins and protect from DDoS attacks.
When to Use Spectrum: When your protocol isn't HTTP/HTTPS (use Cloudflare proxy for HTTP). Spectrum handles everything else: SSH, gaming, databases, MQTT, SMTP, RDP, custom protocols.
Plan Capabilities
| Capability | Pro/Business | Enterprise |
|---|---|---|
| TCP protocols | Selected ports only | All ports (1-65535) |
| UDP protocols | Selected ports only | All ports (1-65535) |
| Port ranges | ❌ | ✅ |
| Argo Smart Routing | ✅ | ✅ |
| IP Firewall | ✅ | ✅ |
| Load balancer origins | ✅ | ✅ |
Decision Tree
What are you trying to do?
Create/manage Spectrum app
- Via Dashboard → See Cloudflare Dashboard
- Via API → See api.md - REST endpoints
- Via SDK → See api.md - TypeScript/Python/Go examples
- Via IaC → See configuration.md - Terraform/Pulumi
Protect specific protocol
- SSH → See patterns.md
- Gaming (Minecraft, etc) → See patterns.md
- MQTT/IoT → See patterns.md
- SMTP/Email → See patterns.md
- Database → See patterns.md
- RDP → See patterns.md
Choose origin type
- Direct IP (single server) → See configuration.md
- CNAME (hostname) → See configuration.md
- Load balancer (HA/failover) → See configuration.md
Reading Order
- Start with patterns.md for your specific protocol
- Then configuration.md for your origin type
- Check gotchas.md before going to production
- Use api.md for programmatic access
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/static-assets/README.md`)
Cloudflare Static Assets Skill Reference
Expert guidance for deploying and configuring static assets with Cloudflare Workers. This skill covers configuration patterns, routing architectures, asset binding usage, and best practices for SPAs, SSG sites, and full-stack applications.
Quick Start
// wrangler.jsonc
{
"name": "my-app",
"main": "src/index.ts",
"compatibility_date": "2025-01-01",
"assets": {
"directory": "./dist"
}
}// src/index.ts
export default {
async fetch(request: Request, env: Env): Promise<Response> {
return env.ASSETS.fetch(request);
}
};Deploy: wrangler deploy
When to Use Workers Static Assets vs Pages
| Factor | Workers Static Assets | Cloudflare Pages |
|---|---|---|
| Use case | Hybrid apps (static + dynamic API) | Static sites, SSG |
| Worker control | Full control over routing | Limited (Functions) |
| Configuration | Code-first, flexible | Git-based, opinionated |
| Dynamic routing | Worker-first patterns | Functions (_functions/) |
| Best for | Full-stack apps, SPAs with APIs | Jamstack, static docs |
Decision tree:
- Need custom routing logic? → Workers Static Assets
- Pure static site or SSG? → Pages
- API routes + SPA? → Workers Static Assets
- Framework (Next, Nuxt, Remix)? → Pages
Reading Order
- configuration.md - Setup, wrangler.jsonc options, routing patterns
- api.md - ASSETS binding API, request/response handling
- patterns.md - Common patterns (SPA, API routes, auth, A/B testing)
- gotchas.md - Limits, errors, performance tips
In This Reference
- configuration.md - Setup, deployment, configuration
- api.md - API endpoints, methods, interfaces
- patterns.md - Common patterns, use cases, examples
- gotchas.md - Troubleshooting, best practices, limitations
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/stream/README.md`)
Cloudflare Stream
Serverless live and on-demand video streaming platform with one API.
Overview
Cloudflare Stream provides video upload, storage, encoding, and delivery without managing infrastructure. Runs on Cloudflare's global network.
Key Features
- On-demand video: Upload, encode, store, deliver
- Live streaming: RTMPS/SRT ingestion with ABR
- Direct creator uploads: End users upload without API keys
- Signed URLs: Token-based access control
- Analytics: Server-side metrics via GraphQL
- Webhooks: Processing notifications
- Captions: Upload or AI-generate subtitles
- Watermarks: Apply branding to videos
- Downloads: Enable MP4 offline viewing
Core Concepts
Video Upload Methods
- API Upload (TUS protocol): Direct server upload
- Upload from URL: Import from external source
- Direct Creator Uploads: User-generated content (recommended)
Playback Options
- Stream Player (iframe): Built-in, optimized player
- Custom Player (HLS/DASH): Video.js, HLS.js integration
- Thumbnails: Static or animated previews
Access Control
- Public: No restrictions
- requireSignedURLs: Token-based access
- allowedOrigins: Domain restrictions
- Access Rules: Geo/IP restrictions in tokens
Live Streaming
- RTMPS/SRT ingest from OBS, FFmpeg
- Automatic recording to on-demand
- Simulcast to YouTube, Twitch, etc.
- WebRTC support for browser streaming
Quick Start
Upload video via API
curl -X POST \
"https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/copy" \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/video.mp4"}'Embed player
.cloudflarestream.com/<VIDEO_ID>/iframe"
style="border: none;"
height="720" width="1280"
allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"
allowfullscreen="true"
>Create live input
curl -X POST \
"https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/live_inputs" \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{"recording": {"mode": "automatic"}}'Limits
- Max file size: 30 GB
- Max frame rate: 60 fps (recommended)
- Supported formats: MP4, MKV, MOV, AVI, FLV, MPEG-2 TS/PS, MXF, LXF, GXF, 3GP, WebM, MPG, QuickTime
Pricing
- $5/1000 min stored
- $1/1000 min delivered
Resources
- Dashboard: https://dash.cloudflare.com/?to=/:account/stream
- API Docs: https://developers.cloudflare.com/api/resources/stream/
- Stream Docs: https://developers.cloudflare.com/stream/
Reading Order
| Order | File | Purpose | When to Use |
|---|---|---|---|
| 1 | configuration.md | Setup SDKs, env vars, signing keys | Starting new project |
| 2 | api.md | On-demand video APIs | Implementing uploads/playback |
| 3 | api-live.md | Live streaming APIs | Building live streaming |
| 4 | patterns.md | Full-stack flows, TUS, JWT signing | Implementing workflows |
| 5 | gotchas.md | Errors, limits, troubleshooting | Debugging issues |
In This Reference
- configuration.md - Setup, environment variables, wrangler config
- api.md - On-demand video upload, playback, management APIs
- api-live.md - Live streaming (RTMPS/SRT/WebRTC), simulcast
- patterns.md - Full-stack flows, state management, best practices
- gotchas.md - Error codes, troubleshooting, limits
See Also
- workers - Deploy Stream APIs in Workers
- pages - Integrate Stream with Pages
- workers-ai - AI-generate captions
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/tail-workers/README.md`)
Cloudflare Tail Workers
Specialized Workers that consume execution events from producer Workers for logging, debugging, analytics, and observability.
When to Use This Reference
- Implementing observability/logging for Cloudflare Workers
- Processing Worker execution events, logs, exceptions
- Building custom analytics or error tracking
- Configuring real-time event streaming
- Working with tail handlers or tail consumers
Core Concepts
What Are Tail Workers?
Tail Workers automatically process events from producer Workers (the Workers being monitored). They receive:
- HTTP request/response info
- Console logs (
console.log/error/warn/debug) - Uncaught exceptions
- Execution outcomes (
ok,exception,exceededCpu, etc.) - Diagnostic channel events
Key characteristics:
- Invoked AFTER producer finishes executing
- Capture entire request lifecycle including Service Bindings and Dynamic Dispatch sub-requests
- Billed by CPU time, not request count
- Available on Workers Paid and Enterprise tiers
Alternative: OpenTelemetry Export
Before using Tail Workers, consider OpenTelemetry:
For batch exports to observability tools (Sentry, Grafana, Honeycomb):
- OTEL export sends logs/traces in batches (more efficient)
- Built-in integrations with popular platforms
- Lower overhead than Tail Workers
- Use Tail Workers only for custom real-time processing
Decision Tree
Need observability for Workers?
├─ Batch export to known tools (Sentry/Grafana/Honeycomb)?
│ └─ Use OpenTelemetry export (not Tail Workers)
├─ Custom real-time processing needed?
│ ├─ Aggregated metrics?
│ │ └─ Use Tail Worker + Analytics Engine
│ ├─ Error tracking?
│ │ └─ Use Tail Worker + external service
│ ├─ Custom logging/debugging?
│ │ └─ Use Tail Worker + KV/HTTP endpoint
│ └─ Complex event processing?
│ └─ Use Tail Worker + Durable Objects
└─ Quick debugging?
└─ Use `wrangler tail` (different from Tail Workers)Reading Order
- configuration.md - Set up Tail Workers
- api.md - Handler signature, types, redaction
- patterns.md - Common use cases and integrations
- gotchas.md - Pitfalls and debugging tips
Quick Example
export default {
async tail(events, env, ctx) {
// Process events from producer Worker
ctx.waitUntil(
fetch(env.LOG_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(events),
})
);
}
};Related Skills
- observability - General Workers observability patterns, OTEL export
- analytics-engine - Aggregated metrics storage for tail event data
- durable-objects - Stateful event processing, batching tail events
- logpush - Alternative for batch log export (non-real-time)
- workers-for-platforms - Dynamic dispatch with tail consumers
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/terraform/README.md`)
Cloudflare Terraform Provider
Expert guidance for Cloudflare Terraform Provider - infrastructure as code for Cloudflare resources.
Core Principles
- Provider-first: Use Terraform provider for ALL infrastructure - never mix with wrangler.jsonc for the same resources
- State management: Always use remote state (S3, Terraform Cloud, etc.) for team environments
- Modular architecture: Create reusable modules for common patterns (zones, workers, pages)
- Version pinning: Always pin provider version with
~>for predictable upgrades - Secret management: Use variables + environment vars for sensitive data - never hardcode API tokens
Provider Version
| Version | Status | Notes |
|---|---|---|
| 5.x | Current | Auto-generated from OpenAPI, breaking changes from v4 |
| 4.x | Legacy | Manual maintenance, deprecated |
Critical: v5 renamed many resources (cloudflare_record → cloudflare_dns_record, cloudflare_worker_* → cloudflare_workers_*). See gotchas.md for migration details.
Provider Setup
Basic Configuration
terraform {
required_version = ">= 1.0"
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 5.15.0"
}
}
}
provider "cloudflare" {
api_token = var.cloudflare_api_token # or CLOUDFLARE_API_TOKEN env var
}Authentication Methods (priority order)
API Token (RECOMMENDED):
api_tokenorCLOUDFLARE_API_TOKEN- Create: Dashboard → My Profile → API Tokens
- Scope to specific accounts/zones for security
Global API Key (LEGACY):
api_key+api_emailorCLOUDFLARE_API_KEY+CLOUDFLARE_EMAIL- Less secure, use tokens instead
User Service Key:
user_service_keyfor Origin CA certificates
Quick Reference: Common Commands
terraform init # Initialize provider
terraform plan # Plan changes
terraform apply # Apply changes
terraform destroy # Destroy resources
terraform import cloudflare_zone.example <zone-id> # Import existing
terraform state list # List resources in state
terraform output # Show outputs
terraform fmt -recursive # Format code
terraform validate # Validate configurationImport Existing Resources
Use cf-terraforming to generate configs from existing Cloudflare resources:
# Install
brew install cloudflare/cloudflare/cf-terraforming
# Generate HCL from existing resources
cf-terraforming generate --resource-type cloudflare_dns_record --zone <zone-id>
# Import into Terraform state
cf-terraforming import --resource-type cloudflare_dns_record --zone <zone-id>Reading Order
- Start with README.md for provider setup and authentication
- Review configuration.md for resource configurations
- Check api.md for data sources and existing resource queries
- See patterns.md for multi-environment and CI/CD patterns
- Read gotchas.md for state drift, v5 breaking changes, and troubleshooting
In This Reference
- configuration.md - Resources for zones, DNS, workers, KV, R2, D1, Pages, rulesets
- api.md - Data sources for existing resources
- patterns.md - Architecture patterns, multi-env setup, CI/CD integration
- gotchas.md - Common issues, security, best practices
See Also
- pulumi - Alternative IaC tool for Cloudflare
- wrangler - CLI deployment alternative
- workers - Worker runtime documentation
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/tunnel/README.md`)
Cloudflare Tunnel
Secure outbound-only connections between infrastructure and Cloudflare's global network.
Overview
Cloudflare Tunnel (formerly Argo Tunnel) enables:
- Outbound-only connections - No inbound ports or firewall changes
- Public hostname routing - Expose local services to internet
- Private network access - Connect internal networks via WARP
- Zero Trust integration - Built-in access policies
Architecture: Tunnel (persistent object) → Replica (cloudflared process) → Origin services
Terminology:
- Tunnel: Named persistent object with UUID
- Replica: Individual
cloudflaredprocess connected to tunnel - Config Source: Where ingress rules stored (local file vs Cloudflare dashboard)
- Connector: Legacy term for replica
Quick Start
Local Config
# Install cloudflared
brew install cloudflared # macOS
# Authenticate
cloudflared tunnel login
# Create tunnel
cloudflared tunnel create my-tunnel
# Route DNS
cloudflared tunnel route dns my-tunnel app.example.com
# Run tunnel
cloudflared tunnel run my-tunnelDashboard Config (Recommended)
- Zero Trust > Networks > Tunnels > Create
- Name tunnel, copy token
- Configure routes in dashboard
- Run:
cloudflared tunnel --no-autoupdate run --token <TOKEN>
Decision Tree
Choose config source:
Need centralized config updates?
├─ Yes → Token-based (dashboard config)
└─ No → Local config file
Multiple environments (dev/staging/prod)?
├─ Yes → Local config (version controlled)
└─ No → Either works
Need firewall approval?
└─ See networking.md firstCore Commands
# Tunnel lifecycle
cloudflared tunnel create <name>
cloudflared tunnel list
cloudflared tunnel info <name>
cloudflared tunnel delete <name>
# DNS routing
cloudflared tunnel route dns <tunnel> <hostname>
cloudflared tunnel route list
# Private network
cloudflared tunnel route ip add 10.0.0.0/8 <tunnel>
# Run tunnel
cloudflared tunnel run <name>Configuration Example
# ~/.cloudflared/config.yml
tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef
credentials-file: /root/.cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json
ingress:
- hostname: app.example.com
service: http://localhost:8000
- hostname: api.example.com
service: https://localhost:8443
originRequest:
noTLSVerify: true
- service: http_status:404Reading Order
New to Cloudflare Tunnel:
- This README (overview, quick start)
- networking.md - Firewall rules, connectivity pre-checks
- configuration.md - Config file options, ingress rules
- patterns.md - Docker, Kubernetes, production deployment
- gotchas.md - Troubleshooting, best practices
Enterprise deployment:
- networking.md - Corporate firewall requirements
- gotchas.md - HA setup, security best practices
- patterns.md - Kubernetes, rolling updates
Programmatic control:
- api.md - REST API, TypeScript SDK
In This Reference
- networking.md - Firewall rules, ports, connectivity pre-checks
- configuration.md - Config file options, ingress rules, TLS settings
- api.md - REST API, TypeScript SDK, token-based tunnels
- patterns.md - Docker, Kubernetes, Terraform, HA, use cases
- gotchas.md - Troubleshooting, limitations, best practices
See Also
- workers - Workers with Tunnel integration
- access - Zero Trust access policies
- warp - WARP client for private networks
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/turn/README.md`)
Cloudflare TURN Service
Expert guidance for implementing Cloudflare TURN Service in WebRTC applications.
Overview
Cloudflare TURN (Traversal Using Relays around NAT) Service is a managed relay service for WebRTC applications. TURN acts as a relay point for traffic between WebRTC clients and SFUs, particularly when direct peer-to-peer communication is obstructed by NATs or firewalls. The service runs on Cloudflare's global anycast network across 310+ cities.
Key Characteristics
- Anycast Architecture: Automatically connects clients to the closest Cloudflare location
- Global Network: Available across Cloudflare's entire network (excluding China Network)
- Zero Configuration: No need to manually select regions or servers
- Protocol Support: STUN/TURN over UDP, TCP, and TLS
- Free Tier: Free when used with Cloudflare Calls SFU, otherwise $0.05/GB outbound
In This Reference
| File | Purpose |
|---|---|
| api.md | Credentials API, TURN key management, types, constraints |
| configuration.md | Worker setup, wrangler.jsonc, env vars, IP allowlisting |
| patterns.md | Implementation patterns, use cases, integration examples |
| gotchas.md | Troubleshooting, limits, security, common mistakes |
Reading Order
| Task | Files to Read | Est. Tokens |
|---|---|---|
| Quick start | README only | ~500 |
| Generate credentials | README → api | ~1300 |
| Worker integration | README → configuration → patterns | ~2000 |
| Debug connection | gotchas | ~700 |
| Security review | api → gotchas | ~1500 |
| Enterprise firewall | configuration | ~600 |
Service Addresses and Ports
STUN over UDP
- Primary:
stun.cloudflare.com:3478/udp - Alternate:
stun.cloudflare.com:53/udp(blocked by browsers, not recommended)
TURN over UDP
- Primary:
turn.cloudflare.com:3478/udp - Alternate:
turn.cloudflare.com:53/udp(blocked by browsers)
TURN over TCP
- Primary:
turn.cloudflare.com:3478/tcp - Alternate:
turn.cloudflare.com:80/tcp
TURN over TLS
- Primary:
turn.cloudflare.com:5349/tcp - Alternate:
turn.cloudflare.com:443/tcp
Quick Start
- Create TURN key via API: see api.md#create-turn-key
- Generate credentials: see api.md#generate-temporary-credentials
- Configure Worker: see configuration.md#cloudflare-worker-integration
- Implement client: see patterns.md#basic-turn-configuration-browser
When to Use TURN
- Restrictive NATs: Symmetric NATs that block direct connections
- Corporate firewalls: Environments blocking WebRTC ports
- Mobile networks: Carrier-grade NAT scenarios
- Predictable connectivity: When reliability > efficiency
Related Cloudflare Services
- Cloudflare Calls SFU: Managed Selective Forwarding Unit (TURN free when used with SFU)
- Cloudflare Stream: Video streaming with WHIP/WHEP support
- Cloudflare Workers: Backend for credential generation
- Cloudflare KV: Credential caching
- Cloudflare Durable Objects: Session state management
Additional Resources
- Cloudflare Calls Documentation
- Cloudflare TURN Service Docs
- Cloudflare API Reference
- Orange Meets (Open Source Example)
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/turnstile/README.md`)
Cloudflare Turnstile Implementation Skill Reference
Expert guidance for implementing Cloudflare Turnstile - a smart CAPTCHA alternative that protects websites from bots without showing traditional CAPTCHA puzzles.
Overview
Turnstile is a user-friendly CAPTCHA alternative that runs challenges in the background without user interaction. It validates visitors automatically using signals like browser behavior, device fingerprinting, and machine learning.
Widget Types
| Type | Interaction | Use Case |
|---|---|---|
| Managed (default) | Shows checkbox when needed | Forms, logins - balance UX and security |
| Non-Interactive | Invisible, runs automatically | Frictionless UX, low-risk actions |
| Invisible | Hidden, triggered programmatically | Pre-clearance, API calls, headless |
Quick Start
Implicit Rendering (HTML-based)
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<form action="/submit" method="POST">
Submit
</form>Explicit Rendering (JavaScript-based)
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"></script>
<script>
window.turnstile.render('#turnstile-container', {
sitekey: 'YOUR_SITE_KEY',
callback: (token) => console.log('Token:', token)
});
</script>Server Validation (Required)
// Cloudflare Workers
export default {
async fetch(request) {
const formData = await request.formData();
const token = formData.get('cf-turnstile-response');
const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
secret: env.TURNSTILE_SECRET,
response: token,
remoteip: request.headers.get('CF-Connecting-IP')
})
});
const validation = await result.json();
if (!validation.success) {
return new Response('Invalid CAPTCHA', { status: 400 });
}
// Process form...
}
}Testing Keys
Critical for development/testing:
| Type | Key | Behavior |
|---|---|---|
| Site Key (Always Passes) | 1x00000000000000000000AA |
Widget succeeds, token validates |
| Site Key (Always Blocks) | 2x00000000000000000000AB |
Widget fails visibly |
| Site Key (Force Challenge) | 3x00000000000000000000FF |
Always shows interactive challenge |
| Secret Key (Testing) | 1x0000000000000000000000000000000AA |
Validates test tokens |
Note: Test keys work on localhost and any domain. Do NOT use in production.
Key Constraints
- Token expiry: 5 minutes after generation
- Single-use: Each token can only be validated once
- Server validation required: Client-side checks are insufficient
Reading Order
- configuration.md - Setup, widget options, script loading
- api.md - JavaScript API, siteverify endpoints, TypeScript types
- patterns.md - Form integration, framework examples, validation patterns
- gotchas.md - Common errors, debugging, limitations
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/vectorize/README.md`)
Cloudflare Vectorize
Globally distributed vector database for AI applications. Store and query vector embeddings for semantic search, recommendations, RAG, and classification.
Status: Generally Available (GA) | Last Updated: 2026-01-27
Quick Start
// 1. Create index
// npx wrangler vectorize create my-index --dimensions=768 --metric=cosine
// 2. Configure binding (wrangler.jsonc)
// { "vectorize": [{ "binding": "VECTORIZE", "index_name": "my-index" }] }
// 3. Query vectors
const matches = await env.VECTORIZE.query(queryVector, { topK: 5 });Key Features
- 10M vectors per index (V2)
- Dimensions up to 1536 (32-bit float)
- Three distance metrics: cosine, euclidean, dot-product
- Metadata filtering (up to 10 indexes)
- Namespace support (50K namespaces paid, 1K free)
- Seamless Workers AI integration
- Global distribution
Reading Order
| Task | Files to Read |
|---|---|
| New to Vectorize | README only |
| Implement feature | README + api + patterns |
| Setup/configure | README + configuration |
| Debug issues | gotchas |
| Integrate with AI | README + patterns |
| RAG implementation | README + patterns |
File Guide
- README.md (this file): Overview, quick decisions
- api.md: Runtime API, types, operations (query/insert/upsert)
- configuration.md: Setup, CLI, metadata indexes
- patterns.md: RAG, Workers AI, OpenAI, LangChain, multi-tenant
- gotchas.md: Limits, pitfalls, troubleshooting
Distance Metric Selection
Choose based on your use case:
What are you building?
├─ Text/semantic search → cosine (most common)
├─ Image similarity → euclidean
├─ Recommendation system → dot-product
└─ Pre-normalized vectors → dot-product| Metric | Best For | Score Interpretation |
|---|---|---|
cosine |
Text embeddings, semantic similarity | Higher = closer (1.0 = identical) |
euclidean |
Absolute distance, spatial data | Lower = closer (0.0 = identical) |
dot-product |
Recommendations, normalized vectors | Higher = closer |
Note: Index configuration is immutable. Cannot change dimensions or metric after creation.
Multi-Tenancy Strategy
How many tenants?
├─ < 50K tenants → Use namespaces (recommended)
│ ├─ Fastest (filter before vector search)
│ └─ Strict isolation
├─ > 50K tenants → Use metadata filtering
│ ├─ Slower (post-filter after vector search)
│ └─ Requires metadata index
└─ Per-tenant indexes → Only if compliance mandated
└─ 50K index limit per account (paid plan)Common Workflows
Semantic Search
// 1. Generate embedding
const result = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: [query] });
// 2. Query Vectorize
const matches = await env.VECTORIZE.query(result.data[0], {
topK: 5,
returnMetadata: "indexed"
});RAG Pattern
// 1. Generate query embedding
const embedding = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: [query] });
// 2. Search Vectorize
const matches = await env.VECTORIZE.query(embedding.data[0], { topK: 5 });
// 3. Fetch full documents from R2/D1/KV
const docs = await Promise.all(matches.matches.map(m =>
env.R2.get(m.metadata.key).then(obj => obj?.text())
));
// 4. Generate LLM response with context
const answer = await env.AI.run("@cf/meta/llama-3-8b-instruct", {
prompt: `Context: ${docs.join("\n\n")}\n\nQuestion: ${query}\n\nAnswer:`
});Critical Gotchas
See gotchas.md for details. Most important:
- Async mutations: Inserts take 5-10s to be queryable
- 500 batch limit: Workers API enforces 500 vectors per call (undocumented)
- Metadata truncation:
"indexed"returns first 64 bytes only - topK with metadata: Max 20 (not 100) when using returnValues or returnMetadata: "all"
- Metadata indexes first: Must create before inserting vectors
Resources
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/waf/README.md`)
Cloudflare WAF Expert Skill Reference
Expertise: Cloudflare Web Application Firewall (WAF) configuration, custom rules, managed rulesets, rate limiting, attack detection, and API integration
Overview
Cloudflare WAF protects web applications from attacks through managed rulesets and custom rules.
Detection (Managed Rulesets)
- Pre-configured rules maintained by Cloudflare
- CVE-based rules, OWASP Top 10 coverage
- Three main rulesets: Cloudflare Managed, OWASP CRS, Exposed Credentials
- Actions: log, block, challenge, js_challenge, managed_challenge
Mitigation (Custom Rules & Rate Limiting)
- Custom expressions using Wirefilter syntax
- Attack score-based blocking (
cf.waf.score) - Rate limiting with per-IP, per-user, or custom characteristics
- Actions: block, challenge, js_challenge, managed_challenge, log, skip
Quick Start
Deploy Cloudflare Managed Ruleset
import Cloudflare from 'cloudflare';
const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN });
// Deploy managed ruleset to zone
await client.rulesets.create({
zone_id: 'zone_id',
kind: 'zone',
phase: 'http_request_firewall_managed',
name: 'Deploy Cloudflare Managed Ruleset',
rules: [{
action: 'execute',
action_parameters: {
id: 'efb7b8c949ac4650a09736fc376e9aee', // Cloudflare Managed Ruleset
},
expression: 'true',
enabled: true,
}],
});Create Custom Rule
// Block requests with attack score >= 40
await client.rulesets.create({
zone_id: 'zone_id',
kind: 'zone',
phase: 'http_request_firewall_custom',
name: 'Custom WAF Rules',
rules: [{
action: 'block',
expression: 'cf.waf.score gt 40',
enabled: true,
}],
});Create Rate Limit
await client.rulesets.create({
zone_id: 'zone_id',
kind: 'zone',
phase: 'http_ratelimit',
name: 'API Rate Limits',
rules: [{
action: 'block',
expression: 'http.request.uri.path eq "/api/login"',
action_parameters: {
ratelimit: {
characteristics: ['cf.colo.id', 'ip.src'],
period: 60,
requests_per_period: 10,
mitigation_timeout: 600,
},
},
enabled: true,
}],
});Managed Ruleset Quick Reference
| Ruleset Name | ID | Coverage |
|---|---|---|
| Cloudflare Managed | efb7b8c949ac4650a09736fc376e9aee |
OWASP Top 10, CVEs |
| OWASP Core Ruleset | 4814384a9e5d4991b9815dcfc25d2f1f |
OWASP ModSecurity CRS |
| Exposed Credentials Check | c2e184081120413c86c3ab7e14069605 |
Credential stuffing |
Phases
WAF rules execute in specific phases:
http_request_firewall_managed- Managed rulesetshttp_request_firewall_custom- Custom ruleshttp_ratelimit- Rate limiting ruleshttp_request_sbfm- Super Bot Fight Mode (Pro+)
Reading Order
- api.md - SDK methods, expressions, actions, parameters
- configuration.md - Setup with Wrangler, Terraform, Pulumi
- patterns.md - Common patterns: deploy managed, rate limiting, skip, override
- gotchas.md - Execution order, limits, expression errors
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/web-analytics/README.md`)
Cloudflare Web Analytics
Privacy-first web analytics providing Core Web Vitals, traffic metrics, and user insights without compromising visitor privacy.
Overview
Cloudflare Web Analytics provides:
- Core Web Vitals - LCP, FID, CLS, INP, TTFB monitoring
- Page views & visits - Traffic patterns without cookies
- Referrers & paths - Traffic sources and popular pages
- Device & browser data - User agent breakdown
- Geographic data - Country-level visitor distribution
- Privacy-first - No cookies, fingerprinting, or PII collection
- Free - No cost, unlimited pageviews
Important: Web Analytics is dashboard-only. No API exists for programmatic data access.
Quick Start Decision Tree
Is your site proxied through Cloudflare?
├─ YES → Use automatic injection (configuration.md)
│ ├─ Enable auto-injection in dashboard
│ └─ No code changes needed (unless Cache-Control: no-transform)
│
└─ NO → Use manual beacon integration (integration.md)
├─ Add JS snippet to HTML
├─ Use spa: true for React/Vue/Next.js
└─ Configure CSP if neededReading Order
- configuration.md - Setup for proxied vs non-proxied sites
- integration.md - Framework-specific beacon integration (React, Next.js, Vue, Nuxt, etc.)
- patterns.md - Common use cases (performance monitoring, GDPR consent, multi-site tracking)
- gotchas.md - Troubleshooting (SPA tracking, CSP issues, hash routing limitations)
When to Use Each File
- Setting up for first time? → Start with configuration.md
- Using React/Next.js/Vue/Nuxt? → Go to integration.md for framework code
- Need GDPR consent loading? → See patterns.md
- Beacon not loading or no data? → Check gotchas.md
- SPA not tracking navigation? → See integration.md for
spa: trueconfig
Key Concepts
Proxied vs Non-Proxied Sites
| Type | Description | Beacon Injection | Limit |
|---|---|---|---|
| Proxied | DNS through Cloudflare (orange cloud) | Automatic or manual | Unlimited |
| Non-proxied | External hosting, manual beacon | Manual only | 10 sites max |
SPA Mode
Critical for modern frameworks:
{"token": "YOUR_TOKEN", "spa": true}Without spa: true, client-side navigation (React Router, Vue Router, Next.js routing) will NOT be tracked. Only initial page loads will register.
CSP Requirements
If using Content Security Policy, allow both domains:
script-src https://static.cloudflareinsights.com https://cloudflareinsights.com;Features
Core Web Vitals Debugging
- LCP (Largest Contentful Paint) - Identifies slow-loading hero images/elements
- FID (First Input Delay) - Interaction responsiveness (legacy metric)
- INP (Interaction to Next Paint) - Modern interaction responsiveness metric
- CLS (Cumulative Layout Shift) - Visual stability issues
- TTFB (Time to First Byte) - Server response performance
Dashboard shows top 5 problematic elements with CSS selectors for debugging.
Traffic Filters
- Bot filtering - Exclude automated traffic from metrics
- Date ranges - Custom time period analysis
- Geographic - Country-level filtering
- Device type - Desktop, mobile, tablet breakdown
- Browser/OS - User agent filtering
Rules (Advanced - Plan-dependent)
Create custom tracking rules for advanced configurations:
Sample Rate Rules:
- Reduce data collection percentage for high-traffic sites
- Example: Track only 50% of visitors to reduce volume
Path-Based Rules:
- Different behavior per route
- Example: Exclude
/admin/*or/internal/*from tracking
Host-Based Rules:
- Multi-domain configurations
- Example: Separate tracking for staging vs production subdomains
Availability: Rules feature depends on your Cloudflare plan. Check dashboard under Web Analytics → Rules to see if available. Free plans may have limited or no access.
Plan Limits
| Feature | Free | Notes |
|---|---|---|
| Proxied sites | Unlimited | DNS through Cloudflare |
| Non-proxied sites | 10 | External hosting |
| Pageviews | Unlimited | No volume limits |
| Data retention | 6 months | Rolling window |
| Rules | Plan-dependent | Check dashboard |
Privacy & Compliance
- No cookies - Zero client-side storage
- No fingerprinting - No tracking across sites
- No PII - IP addresses not stored
- GDPR-friendly - Minimal data collection
- CCPA-compliant - No personal data sale
EU opt-out: Dashboard option to exclude EU visitor data entirely.
Limitations
- Dashboard-only - No API for programmatic access
- No real-time - 5-10 minute data delay
- No custom events - Automatic pageview/navigation tracking only
- History API only - Hash-based routing (
#/path) not supported - No session replay - Metrics only, no user recordings
- No form tracking - Page navigation tracking only
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workerd/README.md`)
Workerd Runtime
V8-based JS/Wasm runtime powering Cloudflare Workers. Use as app server, dev tool, or HTTP proxy.
⚠️ IMPORTANT SECURITY NOTICE
workerd is NOT a hardened sandbox. Do not run untrusted code. It's designed for deploying YOUR code locally/self-hosted, not multi-tenant SaaS. Cloudflare production adds security layers not present in open-source workerd.
Decision Tree: When to Use What
95% of users: Use Wrangler
- Local development:
wrangler dev(uses workerd internally) - Deployment:
wrangler deploy(deploys to Cloudflare) - Types:
wrangler types(generates TypeScript types)
Use raw workerd directly only if:
- Self-hosting Workers runtime in production
- Embedding runtime in C++ application
- Custom tooling/testing infrastructure
- Debugging workerd-specific behavior
Never use workerd for:
- Running untrusted/user-submitted code
- Multi-tenant isolation (not hardened)
- Production without additional security layers
Key Features
- Standards-based: Fetch API, Web Crypto, Streams, WebSocket
- Nanoservices: Service bindings with local call performance
- Capability security: Explicit bindings prevent SSRF
- Backwards compatible: Version = max compat date supported
Architecture
Config (workerd.capnp)
├── Services (workers/endpoints)
├── Sockets (HTTP/HTTPS listeners)
└── Extensions (global capabilities)Quick Start
workerd serve config.capnp
workerd compile config.capnp myConfig -o binary
workerd test config.capnpPlatform Support & Beta Status
| Platform | Status | Notes |
|---|---|---|
| Linux (x64) | Stable | Primary platform |
| macOS (x64/ARM) | Stable | Full support |
| Windows | Beta | Use WSL2 for best results |
| Linux (ARM64) | Experimental | Limited testing |
workerd is in active development. Breaking changes possible. Pin versions in production.
Core Concepts
- Service: Named endpoint (worker/network/disk/external)
- Binding: Capability-based resource access (KV/DO/R2/services)
- Compatibility date: Feature gate (always set!)
- Modules: ES modules (recommended) or service worker syntax
Reading Order (Progressive Disclosure)
Start here:
- This README (overview, decision tree)
- patterns.md - Common workflows, framework examples
When you need details:
3. configuration.md - Config format, services, bindings
4. api.md - Runtime APIs, TypeScript types
5. gotchas.md - Common errors, debugging
Related References
- workers - Workers runtime API documentation
- miniflare - Testing tool built on workerd
- wrangler - CLI that uses workerd for local dev
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-ai/README.md`)
Cloudflare Workers AI
Expert guidance for Cloudflare Workers AI - serverless GPU-powered AI inference at the edge.
Overview
Workers AI provides:
- 50+ pre-trained models (LLMs, embeddings, image generation, speech-to-text, translation)
- Native Workers binding (no external API calls)
- Pay-per-use pricing (neurons consumed per inference)
- OpenAI-compatible REST API
- Streaming support for text generation
- Function calling with compatible models
Architecture: Inference runs on Cloudflare's GPU network. Models load on first request (cold start 1-3s), subsequent requests are faster.
Quick Start
interface Env {
AI: Ai;
}
export default {
async fetch(request: Request, env: Env) {
const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [{ role: 'user', content: 'What is Cloudflare?' }]
});
return Response.json(response);
}
};# Setup - add binding to wrangler.jsonc
wrangler dev --remote # Must use --remote for AI
wrangler deployModel Selection Decision Tree
Text Generation (Chat/Completion)
Quality Priority:
- Best quality:
@cf/meta/llama-3.1-70b-instruct(expensive, ~2000 neurons) - Balanced:
@cf/meta/llama-3.1-8b-instruct(good quality, ~200 neurons) - Fastest/cheapest:
@cf/mistral/mistral-7b-instruct-v0.1(~50 neurons)
Function Calling:
- Use
@cf/meta/llama-3.1-8b-instructor@cf/meta/llama-3.1-70b-instruct(native tool support)
Code Generation:
- Use
@cf/deepseek-ai/deepseek-coder-6.7b-instruct(specialized for code)
Embeddings (Semantic Search/RAG)
English text:
- Best:
@cf/baai/bge-large-en-v1.5(1024 dims, highest quality) - Balanced:
@cf/baai/bge-base-en-v1.5(768 dims, good quality) - Fast:
@cf/baai/bge-small-en-v1.5(384 dims, lower quality but fast)
Multilingual:
- Use
@hf/sentence-transformers/paraphrase-multilingual-minilm-l12-v2
Image Generation
- Stable Diffusion:
@cf/stabilityai/stable-diffusion-xl-base-1.0(~10,000 neurons) - Portraits:
@cf/lykon/dreamshaper-8-lcm(optimized for faces)
Other Tasks
- Speech-to-text:
@cf/openai/whisper - Translation:
@cf/meta/m2m100-1.2b(100 languages) - Image classification:
@cf/microsoft/resnet-50
SDK Approach Decision Tree
Native Binding (Recommended)
When: Building Workers/Pages with TypeScript
Why: Zero external dependencies, best performance, native types
await env.AI.run(model, input);REST API
When: External services, non-Workers environments, testing
Why: Standard HTTP, works anywhere
curl https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai/run/@cf/meta/llama-3.1-8b-instruct \
-H "Authorization: Bearer <API_TOKEN>" \
-d '{"messages":[{"role":"user","content":"Hello"}]}'Vercel AI SDK Integration
When: Using Vercel AI SDK features (streaming UI, tool calling abstractions)
Why: Unified interface across providers
import { openai } from '@ai-sdk/openai';
const model = openai('model-name', {
baseURL: 'https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai/v1',
headers: { Authorization: 'Bearer <API_TOKEN>' }
});RAG vs Direct Generation
Use RAG (Vectorize + Workers AI) When:
- Answering questions about specific documents/data
- Need factual accuracy from known corpus
- Context exceeds model's window (>4K tokens)
- Building knowledge base chat
Use Direct Generation When:
- Creative writing, brainstorming
- General knowledge questions
- Small context fits in prompt (<4K tokens)
- Cost optimization (RAG adds embedding + vector search costs)
Platform Limits
| Limit | Free Tier | Paid Plans |
|---|---|---|
| Neurons/day | 10,000 | Pay per use |
| Rate limit | Varies by model | Higher (contact support) |
| Context window | Model dependent (2K-8K) | Same |
| Streaming | ✅ Supported | ✅ Supported |
| Function calling | ✅ Supported (select models) | ✅ Supported |
Pricing: Free 10K neurons/day, then pay per neuron consumed (varies by model)
Common Tasks
// Streaming text generation
const stream = await env.AI.run(model, { messages, stream: true });
for await (const chunk of stream) {
console.log(chunk.response);
}
// Embeddings for RAG
const { data } = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
text: ['Query text', 'Document 1', 'Document 2']
});
// Function calling
const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [{ role: 'user', content: 'What is the weather?' }],
tools: [{
type: 'function',
function: { name: 'getWeather', parameters: { ... } }
}]
});Development Workflow
# Always use --remote for AI (local doesn't have models)
wrangler dev --remote
# Deploy to production
wrangler deploy
# View model catalog
# https://developers.cloudflare.com/workers-ai/models/Reading Order
Start here: Quick Start above → configuration.md (setup)
Common tasks:
- First time setup: configuration.md → Add binding + deploy
- Choose model: Model Selection Decision Tree (above) → api.md
- Build RAG: patterns.md → Vectorize integration
- Optimize costs: Model Selection + gotchas.md (rate limits)
- Debugging: gotchas.md → Common errors
In This Reference
- configuration.md - wrangler.jsonc setup, TypeScript types, bindings, environment variables
- api.md - env.AI.run(), streaming, function calling, REST API, response types
- patterns.md - RAG with Vectorize, prompt engineering, batching, error handling, caching
- gotchas.md - Deprecated @cloudflare/ai package, rate limits, pricing, common errors
See Also
- vectorize - Vector database for RAG patterns
- ai-gateway - Caching, rate limiting, analytics for AI requests
- workers - Worker runtime and fetch handler patterns
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-for-platforms/README.md`)
Cloudflare Workers for Platforms
Multi-tenant platform with isolated customer code execution at scale.
Use Cases
- Multi-tenant SaaS running customer code
- AI-generated code execution in secure sandboxes
- Programmable platforms with isolated compute
- Edge functions/serverless platforms
- Website builders with static + dynamic content
- Unlimited app deployment at scale
NOT for general Workers - only for Workers for Platforms architecture.
Quick Start
One-click deploy: Platform Starter Kit deploys complete WfP setup with dispatch namespace, dispatch worker, and user worker example.
Manual setup: See configuration.md for namespace creation and dispatch worker configuration.
Key Features
- Unlimited Workers per namespace (no script limits)
- Automatic tenant isolation
- Custom CPU/subrequest limits per customer
- Hostname routing (subdomains/vanity domains)
- Egress/ingress control
- Static assets support
- Tags for bulk operations
Architecture
4 Components:
- Dispatch Namespace - Container for unlimited customer Workers, automatic isolation (untrusted mode by default - no request.cf access, no shared cache)
- Dynamic Dispatch Worker - Entry point, routes requests, enforces platform logic (auth, limits, validation)
- User Workers - Customer code in isolated sandboxes, API-deployed, optional bindings (KV/D1/R2/DO)
- Outbound Worker (optional) - Intercepts external fetch, controls egress, logs subrequests (blocks TCP socket connect() API)
Request Flow:
Request → Dispatch Worker → Determines user Worker → env.DISPATCHER.get("customer")
→ User Worker executes (Outbound Worker for external fetch) → Response → Dispatch Worker → ClientDecision Trees
When to Use Workers for Platforms
Need to run code?
├─ Your code only → Regular Workers
├─ Customer/AI code → Workers for Platforms
└─ Untrusted code in sandbox → Workers for Platforms OR Sandbox APIRouting Strategy Selection
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 parsingIsolation Mode Selection
Worker mode?
├─ Running customer code → Untrusted (default)
├─ Need request.cf geolocation → Trusted mode
├─ Internal platform, controlled code → Trusted mode with cache key prefixes
└─ Maximum isolation → Untrusted + unique resources per customerIn This Reference
| File | Purpose | When to Read |
|---|---|---|
| configuration.md | Namespace setup, dispatch worker config | First-time setup, changing limits |
| api.md | User worker API, dispatch API, outbound worker | Deploying workers, SDK integration |
| patterns.md | Multi-tenancy, routing, egress control | Planning architecture, scaling |
| gotchas.md | Limits, isolation issues, best practices | Debugging, production prep |
See Also
- workers - Core Workers runtime documentation
- durable-objects - Stateful multi-tenant patterns
- sandbox - Alternative for untrusted code execution
- Reference Architecture: Programmable Platforms
- Reference Architecture: AI Vibe Coding Platform
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-playground/README.md`)
Cloudflare Workers Playground Skill Reference
Overview
Cloudflare Workers Playground is a browser-based sandbox for instantly experimenting with, testing, and deploying Cloudflare Workers without authentication or setup. This skill provides patterns, APIs, and best practices specifically for Workers Playground development.
URL: workers.cloudflare.com/playground
⚠️ Playground Constraints
Playground is NOT production-equivalent:
- ✅ Real Workers runtime, instant testing, shareable URLs
- ❌ No TypeScript (JavaScript only)
- ❌ No bindings (KV, D1, R2, Durable Objects)
- ❌ No environment variables or secrets
- ❌ ES modules only (no Service Worker format)
- ⚠️ Safari broken (use Chrome/Firefox)
For production: Use wrangler CLI. Playground is for rapid prototyping.
Quick Start
Minimal Worker:
export default {
async fetch(request, env, ctx) {
return new Response('Hello World');
}
};JSON API:
export default {
async fetch(request, env, ctx) {
const data = { message: 'Hello', timestamp: Date.now() };
return Response.json(data);
}
};Proxy with modification:
export default {
async fetch(request, env, ctx) {
const response = await fetch('https://example.com');
const modified = new Response(response.body, response);
modified.headers.set('X-Custom-Header', 'added-by-worker');
return modified;
}
};Import from CDN:
import { Hono } from 'https://esm.sh/hono@3';
export default {
async fetch(request) {
const app = new Hono();
app.get('/', (c) => c.text('Hello Hono!'));
return app.fetch(request);
}
};Reading Order
- configuration.md - Start here: playground setup, constraints, deployment
- api.md - Core APIs: Request, Response, ExecutionContext, fetch, Cache
- patterns.md - Common use cases: routing, proxying, A/B testing, multi-module code
- gotchas.md - Troubleshooting: errors, browser issues, limits, best practices
In This Reference
- configuration.md - Setup, deployment, configuration
- api.md - API endpoints, methods, interfaces
- patterns.md - Common patterns, use cases, examples
- gotchas.md - Troubleshooting, best practices, limitations
Key Features
No Setup Required:
- Open URL and start coding
- No CLI, no account, no config files
- Code executes in real Cloudflare Workers runtime
Instant Preview:
- Live preview pane with browser tab or HTTP tester
- Auto-reload on code changes
- DevTools integration (right-click → Inspect)
Share & Deploy:
- Copy Link generates permanent shareable URL
- Deploy button publishes to production in ~30 seconds
- Get
*.workers.devsubdomain immediately
Common Use Cases
- API development: Test endpoints before wrangler setup
- Learning Workers: Experiment with APIs without local environment
- Prototyping: Quick POCs for edge logic
- Sharing examples: Generate shareable links for bug reports or demos
- Framework testing: Import from CDN (Hono, itty-router, etc.)
Limitations vs Production
| Feature | Playground | Production (wrangler) |
|---|---|---|
| Language | JavaScript only | JS + TypeScript |
| Bindings | None | KV, D1, R2, DO, AI, etc. |
| Environment vars | None | Full support |
| Module format | ES only | ES + Service Worker |
| CPU time | 10ms (Free plan) | 10ms Free / 50ms Paid |
| Custom domains | No | Yes |
| Analytics | No | Yes |
See Also
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-vpc/README.md`)
Workers VPC Connectivity
Connect Cloudflare Workers to private networks and internal infrastructure using TCP Sockets.
Overview
Workers VPC connectivity enables outbound TCP connections from Workers to private resources in AWS, Azure, GCP, on-premises datacenters, or any private network. This is achieved through the TCP Sockets API (cloudflare:sockets), which provides low-level network access for custom protocols and services.
Key capabilities:
- Direct TCP connections to private IPs and hostnames
- TLS/StartTLS support for encrypted connections
- Integration with Cloudflare Tunnel for secure private network access
- Full control over wire protocols (database protocols, SSH, MQTT, custom TCP)
Note: This reference documents the TCP Sockets API. For the newer Workers VPC Services product (HTTP-only service bindings with built-in SSRF protection), refer to separate documentation when available. VPC Services is currently in beta (2025+).
Quick Decision: Which Technology?
Need private network connectivity from Workers?
| Requirement | Use | Why |
|---|---|---|
| HTTP/HTTPS APIs in private network | VPC Services (beta, separate docs) | SSRF-safe, declarative bindings |
| PostgreSQL/MySQL databases | Hyperdrive | Connection pooling, caching, optimized |
| Custom TCP protocols (SSH, MQTT, proprietary) | TCP Sockets (this doc) | Full protocol control |
| Simple HTTP with lowest latency | TCP Sockets + Smart Placement | Manual optimization |
| Expose on-prem to internet (inbound) | Cloudflare Tunnel | Not Worker-specific |
When to Use TCP Sockets
Use TCP Sockets when you need:
- ✅ Direct control over wire protocols (e.g., Postgres wire protocol, SSH, Redis RESP)
- ✅ Non-HTTP protocols (MQTT, SMTP, custom binary protocols)
- ✅ StartTLS or custom TLS negotiation
- ✅ Streaming binary data over TCP
Don't use TCP Sockets when:
- ❌ You just need HTTP/HTTPS (use
fetch()or VPC Services) - ❌ You need PostgreSQL/MySQL (use Hyperdrive for pooling)
- ❌ You need WebSocket (use native Workers WebSocket)
Quick Start
import { connect } from 'cloudflare:sockets';
export default {
async fetch(req: Request): Promise<Response> {
// Connect to private service
const socket = connect(
{ hostname: "db.internal.company.net", port: 5432 },
{ secureTransport: "on" }
);
try {
await socket.opened; // Wait for connection
const writer = socket.writable.getWriter();
await writer.write(new TextEncoder().encode("QUERY\r\n"));
await writer.close();
const reader = socket.readable.getReader();
const { value } = await reader.read();
return new Response(value);
} finally {
await socket.close();
}
}
};Architecture Pattern: Workers + Tunnel
Most private network connectivity combines TCP Sockets with Cloudflare Tunnel:
┌─────────┐ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ Worker │────▶│ TCP Socket │────▶│ Tunnel │────▶│ Private │
│ │ │ (this API) │ │ (cloudflared)│ │ Network │
└─────────┘ └─────────────┘ └──────────────┘ └─────────────┘- Worker opens TCP socket to Tunnel hostname
- Tunnel endpoint routes to private IP
- Response flows back through Tunnel to Worker
See configuration.md for Tunnel setup details.
Reading Order
- Start here (README.md) - Overview and decision guide
- api.md - Socket interface, types, methods
- configuration.md - Wrangler setup, Tunnel integration
- patterns.md - Real-world examples (databases, protocols, error handling)
- gotchas.md - Limits, blocked ports, common errors
Key Limits
| Limit | Value |
|---|---|
| Max concurrent sockets per request | 6 |
| Blocked destinations | Cloudflare IPs, localhost, port 25 |
| Scope requirement | Must create in handler (not global) |
See gotchas.md for complete limits and troubleshooting.
Best Practices
- Always close sockets - Use try/finally blocks
- Validate destinations - Prevent SSRF by allowlisting hosts
- Use Hyperdrive for databases - Better performance than raw TCP
- Prefer fetch() for HTTP - Only use TCP when necessary
- Combine with Smart Placement - Reduce latency to private networks
Related Technologies
- Hyperdrive - PostgreSQL/MySQL with connection pooling
- Cloudflare Tunnel - Secure private network access
- Smart Placement - Auto-locate Workers near backends
- VPC Services (beta) - HTTP-only service bindings with SSRF protection (separate docs)
Reference
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers/README.md`)
Cloudflare Workers
Expert guidance for building, deploying, and optimizing Cloudflare Workers applications.
Overview
Cloudflare Workers run on V8 isolates (NOT containers/VMs):
- Extremely fast cold starts (< 1ms)
- Global deployment across 300+ locations
- Web standards compliant (fetch, URL, Headers, Request, Response)
- Support JS/TS, Python, Rust, and WebAssembly
Key principle: Workers use web platform APIs wherever possible for portability.
Module Worker Pattern (Recommended)
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello World!');
},
};Handler parameters:
request: Incoming HTTP request (standard Request object)env: Environment bindings (KV, D1, R2, secrets, vars)ctx: Execution context (waitUntil,passThroughOnException)
Essential Commands
npx wrangler dev # Local dev
npx wrangler dev --remote # Remote dev (actual resources)
npx wrangler deploy # Production
npx wrangler deploy --env staging # Specific environment
npx wrangler tail # Stream logs
npx wrangler secret put API_KEY # Set secretWhen to Use Workers
- API endpoints at the edge
- Request/response transformation
- Authentication/authorization layers
- Static asset optimization
- A/B testing and feature flags
- Rate limiting and security
- Proxy/routing logic
- WebSocket applications
Quick Start
npm create cloudflare@latest my-worker -- --type hello-world
cd my-worker
npx wrangler devHandler Signatures
// HTTP requests
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>
// Cron triggers
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void>
// Queue consumer
async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext): Promise<void>
// Tail consumer
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext): Promise<void>Resources
Docs: https://developers.cloudflare.com/workers/
Examples: https://developers.cloudflare.com/workers/examples/
Runtime APIs: https://developers.cloudflare.com/workers/runtime-apis/
In This Reference
- Configuration - wrangler.jsonc setup, bindings, environments
- API - Runtime APIs, bindings, execution context
- Patterns - Common workflows, testing, optimization
- Frameworks - Hono, routing, validation
- Gotchas - Common issues, limits, troubleshooting
Reading Order
| Task | Start With | Then Read |
|---|---|---|
| First Worker | README → Configuration → API | Patterns |
| Add framework | Frameworks | Configuration (bindings) |
| Add storage/bindings | Configuration → API (binding usage) | See Also links |
| Debug issues | Gotchas | API (specific binding docs) |
| Production optimization | Patterns | API (caching, streaming) |
| Type safety | Configuration (TypeScript) | Frameworks (Hono typing) |
See Also
- KV - Key-value storage
- D1 - SQL database
- R2 - Object storage
- Durable Objects - Stateful coordination
- Queues - Message queues
- Wrangler - CLI tool reference
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workflows/README.md`)
Cloudflare Workflows
Durable multi-step applications with automatic retries, state persistence, and long-running execution.
What It Does
- Chain steps with automatic retry logic
- Persist state between steps (minutes → weeks)
- Handle failures without losing progress
- Wait for external events/approvals
- Sleep without consuming resources
Available: Free & Paid Workers plans
Core Concepts
Workflow: Class extending WorkflowEntrypoint with run method
Instance: Single execution with unique ID & independent state
Steps: Independently retriable units via step.do() - API calls, DB queries, AI invocations
State: Persisted from step returns; step name = cache key
Quick Start
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';
type Env = { MY_WORKFLOW: Workflow; DB: D1Database };
type Params = { userId: string };
export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
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.params.userId).first();
});
await step.sleep('wait 7 days', '7 days');
await step.do('send reminder', async () => {
await sendEmail(user.email, 'Reminder!');
});
}
}Key Features
- Durability: Failed steps don't re-run successful ones
- Retries: Configurable backoff (constant/linear/exponential)
- Events:
waitForEvent()for webhooks/approvals (timeout: 1h → 365d) - Sleep:
sleep()/sleepUntil()for scheduling (max 365d) - Parallel:
Promise.all()for concurrent steps - Idempotency: Check-then-execute patterns
Reading Order
Getting Started: configuration.md → api.md → patterns.md
Troubleshooting: gotchas.md
In This Reference
- configuration.md - wrangler.jsonc setup, step config, bindings
- api.md - Step APIs, instance management, sleep/parameters
- patterns.md - Common workflows, testing, orchestration
- gotchas.md - Timeouts, limits, debugging strategies
See Also
- durable-objects - Alternative stateful approach
- queues - Message-driven workflows
- workers - Entry point for workflow instances
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/wrangler/README.md`)
Cloudflare Wrangler
Official CLI for Cloudflare Workers - develop, manage, and deploy Workers from the command line.
What is Wrangler?
Wrangler is the Cloudflare Developer Platform CLI that allows you to:
- Create, develop, and deploy Workers
- Manage bindings (KV, D1, R2, Durable Objects, etc.)
- Configure routing and environments
- Run local development servers
- Execute migrations and manage resources
- Perform integration testing
Installation
npm install wrangler --save-dev
# or globally
npm install wranglerRun commands: npx wrangler <command> (or pnpm/yarn wrangler)
Reading Order
| If you want to... | Start here |
|---|---|
| Create/deploy Worker quickly | Essential Commands below → patterns.md §New Worker |
| Configure bindings (KV, D1, R2) | configuration.md §Bindings |
| Write integration tests | api.md §startWorker |
| Debug production issues | gotchas.md + Essential Commands §Monitoring |
| Set up multi-environment workflow | configuration.md §Environments |
Essential Commands
Project & Development
wrangler init [name] # Create new project
wrangler dev # Local dev server (fast, simulated)
wrangler dev --remote # Dev with remote resources (production-like)
wrangler deploy # Deploy to production
wrangler deploy --env staging # Deploy to environment
wrangler versions list # List versions
wrangler rollback [id] # Rollback deployment
wrangler login # OAuth login
wrangler whoami # Check auth statusResource Management
KV
wrangler kv namespace create NAME
wrangler kv key put "key" "value" --namespace-id=
wrangler kv key get "key" --namespace-id=D1
wrangler d1 create NAME
wrangler d1 execute NAME --command "SQL"
wrangler d1 migrations create NAME "description"
wrangler d1 migrations apply NAMER2
wrangler r2 bucket create NAME
wrangler r2 object put BUCKET/key --file path
wrangler r2 object get BUCKET/keyOther Resources
wrangler queues create NAME
wrangler vectorize create NAME --dimensions N --metric cosine
wrangler hyperdrive create NAME --connection-string "..."
wrangler workflows create NAME
wrangler constellation create NAME
wrangler pages project create NAME
wrangler pages deployment create --project NAME --branch mainSecrets
wrangler secret put NAME # Set Worker secret
wrangler secret list # List Worker secrets
wrangler secret delete NAME # Delete Worker secret
wrangler secret bulk FILE.json # Bulk upload from JSON
# Secrets Store (centralized, reusable across Workers)
wrangler secret-store:secret put STORE_NAME SECRET_NAME
wrangler secret-store:secret list STORE_NAMEMonitoring
wrangler tail # Real-time logs
wrangler tail --env production # Tail specific env
wrangler tail --status error # Filter by statusIn This Reference
- auth.md - Authentication setup (
wrangler login, API tokens) - configuration.md - wrangler.jsonc setup, environments, bindings
- api.md - Programmatic API (
startWorker,getPlatformProxy, events) - patterns.md - Common workflows and development patterns
- gotchas.md - Common pitfalls, limits, and troubleshooting
Quick Decision Tree
Need to test your Worker?
├─ Testing full Worker with bindings → api.md §startWorker
├─ Testing individual functions → api.md §getPlatformProxy
└─ Testing with Vitest → patterns.md §Testing with Vitest
Need to configure something?
├─ Bindings (KV, D1, R2, etc.) → configuration.md §Bindings
├─ Multiple environments → configuration.md §Environments
├─ Static files → configuration.md §Workers Assets
└─ Routing → configuration.md §Routing
Development not working?
├─ Local differs from production → Use `wrangler dev --remote`
├─ Bindings not available → gotchas.md §Binding Not Available
└─ Auth issues → auth.md
Authentication issues?
├─ "Not logged in" / "Unauthorized" → auth.md
├─ First time deploying → `wrangler login` (one-time OAuth)
└─ CI/CD setup → auth.md §API TokenSee Also
- workers - Workers runtime API reference
- miniflare - Local testing with Miniflare
- workerd - Runtime that powers
wrangler dev
Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/zaraz/README.md`)
Cloudflare Zaraz
Expert guidance for Cloudflare Zaraz - server-side tag manager for loading third-party tools at the edge.
What is Zaraz?
Zaraz offloads third-party scripts (analytics, ads, chat, marketing) to Cloudflare's edge, improving site speed, privacy, and security. Zero client-side performance impact.
Core Concepts:
- Server-side execution - Scripts run on Cloudflare, not user's browser
- Single HTTP request - All tools loaded via one endpoint
- Privacy-first - Control data sent to third parties
- No client-side JS overhead - Minimal browser impact
Quick Start
- Navigate to domain > Zaraz in Cloudflare dashboard
- Click "Start setup"
- Add tools (Google Analytics, Facebook Pixel, etc.)
- Configure triggers (when tools fire)
- Add tracking code to your site:
// Track page view
zaraz.track('page_view');
// Track custom event
zaraz.track('button_click', { button_id: 'cta' });
// Set user properties
zaraz.set('userId', 'user_123');When to Use Zaraz
Use Zaraz when:
- Adding multiple third-party tools (analytics, ads, marketing)
- Site performance is critical (no client-side JS overhead)
- Privacy compliance required (GDPR, CCPA)
- Non-technical teams need to manage tools
Use Workers directly when:
- Building custom server-side tracking logic
- Need full control over data processing
- Integrating with complex backend systems
- Zaraz's tool library doesn't meet needs
In This Reference
| File | Purpose | When to Read |
|---|---|---|
| api.md | Web API, zaraz object, consent methods | Implementing tracking calls |
| configuration.md | Dashboard setup, triggers, tools | Initial setup, adding tools |
| patterns.md | SPA, e-commerce, Worker integration | Best practices, common scenarios |
| gotchas.md | Troubleshooting, limits, pitfalls | Debugging issues |
Reading Order by Task
| Task | Files to Read |
|---|---|
| Add analytics to site | README → configuration.md |
| Track custom events | README → api.md |
| Debug tracking issues | gotchas.md |
| SPA tracking | api.md → patterns.md (SPA section) |
| E-commerce tracking | api.md#ecommerce → patterns.md#ecommerce |
| Worker integration | patterns.md#worker-integration |
| GDPR compliance | api.md#consent → configuration.md#consent |
Decision Tree
What do you need?
├─ Track events in browser → api.md
│ ├─ Page views, clicks → zaraz.track()
│ ├─ User properties → zaraz.set()
│ └─ E-commerce → zaraz.ecommerce()
│
├─ Configure Zaraz → configuration.md
│ ├─ Add GA4/Facebook → tools setup
│ ├─ When tools fire → triggers
│ └─ GDPR consent → consent purposes
│
├─ Integrate with Workers → patterns.md#worker-integration
│ ├─ Enrich context → Context Enrichers
│ └─ Inject tracking → HTML rewriting
│
└─ Debug issues → gotchas.md
├─ Events not firing → troubleshooting
├─ Consent issues → consent debugging
└─ Performance → debugging toolsKey Features
- 100+ Pre-built Tools - GA4, Facebook, Google Ads, TikTok, etc.
- Zero Client Impact - Runs at Cloudflare's edge, not browser
- Privacy Controls - Consent management, data filtering
- Custom Tools - Build Managed Components for proprietary systems
- Worker Integration - Enrich context, compute dynamic values
- Debug Mode - Real-time event inspection
Reference
This skill focuses exclusively on Zaraz. For Workers development, see cloudflare-workers skill.
Overview (`packages/autoskills/skills-registry/cloudflare/references/ai-gateway/README.md`)
Cloudflare AI Gateway
Use AI Gateway to observe and control requests to AI providers through caching, rate limiting, logging, and routing.
Fetch the linked documentation before choosing endpoints, authentication headers, SDK options, model names, or limits. Keep implementation details in the current docs.
Choose a task
| Task | Reference |
|---|---|
| Create a gateway or choose authentication and provider credentials | Configuration |
| Integrate an SDK, direct HTTP, or a Worker binding | SDK integration |
| Configure caching, rate limits, security, billing, or logging | Features |
| Add fallbacks, conditional routing, or traffic splits | Dynamic routing |
| Diagnose failed requests, caching, or missing logs | Troubleshooting |
For new single-model calls, start with the REST API or Workers bindings, depending on the runtime. Preserve provider-native integrations when their API shape is needed; use the corresponding provider guide.
The legacy Unified API is deprecated for single-model calls but remains required for dynamic routes. Check the task before changing an existing endpoint.
Gateway authentication and upstream provider credentials are separate concerns. Choose the endpoint first, then follow its authentication and billing requirements in configuration.
Related references
- Workers AI — model inference.
- Agents SDK documentation — stateful agents.
- Vectorize — vector search.
Overview (`packages/autoskills/skills-registry/cloudflare/references/ai-search/README.md`)
Cloudflare AI Search
Use AI Search for managed content indexing and retrieval, with optional answer generation. Start with How AI Search works.
Choose the right product
- Managed search or RAG over your content: AI Search.
- Custom embeddings and vector-index management: Vectorize.
- Model inference without a managed retrieval pipeline: Workers AI.
For freshness requirements, read Syncing for your data source before choosing an architecture. Use the current limits and pricing instead of assuming a fixed indexing interval or account limit.
Find the right documentation
Read the linked page before implementing; these references route to the maintained documentation instead of copying API examples or configuration.
| Task | Start here |
|---|---|
| Build a new Worker integration | Workers binding quick start |
| Choose an API or maintain an existing integration | API routes |
| Connect data, configure indexing, or manage environments | Configuration routes |
| Choose retrieval, generation, or tenant isolation patterns | Pattern routes |
| Diagnose indexing, authentication, filters, or limits | Troubleshooting routes |
Existing env.AI.autorag() integrations can continue to work. Use the migration guide when upgrading; migration is not required just to maintain an existing integration.
Overview (`packages/autoskills/skills-registry/cloudflare/references/analytics-engine/README.md`)
Cloudflare Workers Analytics Engine Reference
Expert guidance for implementing unlimited-cardinality analytics at scale using Cloudflare Workers Analytics Engine.
What is Analytics Engine?
Time-series analytics database designed for high-cardinality data (millions of unique dimensions). Write data points from Workers, query via SQL API. Use for:
- Custom user-facing analytics dashboards
- Usage-based billing & metering
- Per-customer/per-feature monitoring
- High-frequency instrumentation without performance impact
Key Capability: Track metrics with unlimited unique values (e.g., millions of user IDs, API keys) without performance degradation.
Core Concepts
| Concept | Description | Example |
|---|---|---|
| Dataset | Logical table for related metrics | api_requests, user_events |
| Data Point | Single measurement with timestamp | One API request's metrics |
| Blobs | String dimensions (max 20) | endpoint, method, status, user_id |
| Doubles | Numeric values (max 20) | latency_ms, request_count, bytes |
| Indexes | Filtered blobs for efficient queries | customer_id, api_key |
Reading Order
| Task | Start Here | Then Read |
|---|---|---|
| First-time setup | configuration.md → api.md → patterns.md | |
| Writing data | api.md → gotchas.md (sampling) | |
| Querying data | api.md (SQL API) → patterns.md (examples) | |
| Debugging | gotchas.md → api.md (limits) | |
| Optimization | patterns.md (anti-patterns) → gotchas.md |
When to Use Analytics Engine
Need to track metrics? → Yes
↓
Millions of unique dimension values? → Yes
↓
Need real-time queries? → Yes
↓
Use Analytics Engine ✓
Alternative scenarios:
- Low cardinality (<10k unique values) → Workers Analytics (free tier)
- Complex joins/relations → D1 Database
- Logs/debugging → Tail Workers (logpush)
- External tools → Send to external analytics (Datadog, etc.)Quick Start
- Add binding to
wrangler.jsonc:
{
"analytics_engine_datasets": [
{ "binding": "ANALYTICS", "dataset": "my_events" }
]
}- Write data points (fire-and-forget, no await):
env.ANALYTICS.writeDataPoint({
blobs: ["/api/users", "GET", "200"],
doubles: [145.2, 1], // latency_ms, count
indexes: [customerId]
});- Query via SQL API (HTTP):
SELECT blob1, SUM(double2) AS total_requests
FROM my_events
WHERE index1 = 'customer_123'
AND timestamp >= NOW() - INTERVAL '7' DAY
GROUP BY blob1
ORDER BY total_requests DESCIn This Reference
- configuration.md - Setup, bindings, TypeScript types, limits
- api.md -
writeDataPoint(), SQL API, query syntax - patterns.md - Use cases, examples, anti-patterns
- gotchas.md - Sampling, index selection, troubleshooting
See Also
- Cloudflare Analytics Engine Docs
- GraphQL Analytics API Reference - Query built-in Cloudflare analytics (HTTP, Workers, DNS, Firewall, etc.)
- Observability Reference - Workers Logs, Traces, and real-time debugging
Overview (`packages/autoskills/skills-registry/cloudflare/references/bindings/README.md`)
Cloudflare Workers Bindings
Bindings grant a Worker access to configured resources through its environment. Prefer a product's binding for supported operations inside Workers; use the REST API when the caller or operation requires it.
Read the relevant current documentation before implementing. These references route to maintained APIs and configuration rather than copying binding catalogs, type tables, or limits.
Start here
- Bindings overview and catalog: capability model, available products, environment access, and binding lifecycle.
- Storage options: choose storage from consistency, query, and coordination requirements.
- api.md: environment access, generated types, and product APIs.
- configuration.md: binding configuration, environments, secrets, and local development.
- patterns.md: Worker-to-Worker calls, testing, and resource selection.
- gotchas.md: missing bindings, stale clients, development differences, and limits.
Treat each binding as a capability granted to code. Select only the resources the Worker needs, and confirm which environment and resource each binding targets before using it.
Overview (`packages/autoskills/skills-registry/cloudflare/references/browser-rendering/README.md`)
Browser Run (formerly Browser Rendering)
Use Browser Run for screenshots, PDFs, rendered content extraction, and browser automation. Read the relevant current documentation before implementing; use the documentation index to discover additional guides.
Choose the integration by the work and runtime:
- For a self-contained screenshot, PDF, or extraction, start with Quick Actions. They are available through REST and Workers bindings; check the chosen action's supported interface.
- For multi-step interactions or persistent state, use browser sessions. In Workers, use Cloudflare's Puppeteer or Playwright package; from external scripts or CI, use the CDP integration.
- When adapting existing automation, preserve its library where supported and check installed versions against the corresponding guide.
Read only the reference needed for the task:
| Task | Reference |
|---|---|
| Set up bindings, dependencies, or development | configuration.md |
| Select an endpoint or browser client API | api.md |
| Implement a workflow or manage reusable sessions | patterns.md |
| Diagnose failures or plan capacity and cost | gotchas.md |
Overview (`packages/autoskills/skills-registry/cloudflare/references/c3/README.md`)
C3 (create-cloudflare)
Official CLI for scaffolding Cloudflare Workers and Pages projects with templates, TypeScript, and instant deployment.
Quick Start
# Interactive (recommended for first-time)
npm create cloudflare@latest my-app
# Worker (API/WebSocket/Cron)
npm create cloudflare@latest my-api -- --type=hello-world --ts
# Pages (static/SSG)
npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pagesPlatform Decision Tree
What are you building?
├─ API / WebSocket / Cron / Email handler
│ └─ Workers (default) - no --platform flag needed
│ npm create cloudflare@latest my-api -- --type=hello-world
├─ Static site / SSG / Documentation
│ └─ Pages - requires --platform=pages
│ npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages
├─ Full-stack app (Next.js/Remix/SvelteKit)
│ └─ Follow the current framework guide below
└─ Convert existing project
└─ npm create cloudflare@latest . -- --type=pre-existing --existing-script=./src/worker.tsCritical: Pages projects require --platform=pages flag. Without it, C3 defaults to Workers.
Framework Setup
Fetch the Workers framework guide for the chosen framework before scaffolding or adapting an existing app. For Next.js, follow Next.js on Workers; use the Pages static export guide only when targeting a Next.js static export on Pages.
Interactive Flow
When run without flags, C3 prompts in this order:
- Project name - Directory to create (defaults to current dir with
.) - Application type -
hello-world,web-app,demo,pre-existing,remote-template - Platform -
workers(default) orpages(for web apps only) - Framework - If web-app:
next,remix,astro,react-router,solid,svelte, etc. - TypeScript -
yes(recommended) orno - Git - Initialize repository?
yesorno - Deploy - Deploy now?
yesorno(requireswrangler login)
Installation Methods
# NPM
npm create cloudflare@latest
# Yarn
yarn create cloudflare
# PNPM
pnpm create cloudflare@latestIn This Reference
| File | Purpose | Use When |
|---|---|---|
| api.md | Complete CLI flag reference | Scripting, CI/CD, advanced usage |
| configuration.md | Generated files, bindings, types | Understanding output, customization |
| patterns.md | Workflows, CI/CD, monorepos | Real-world integration |
| gotchas.md | Troubleshooting failures | Deployment blocked, errors |
Reading Order
| Task | Read |
|---|---|
| Create first project | README only |
| Set up CI/CD | README → api → patterns |
| Debug failed deploy | gotchas |
| Understand generated files | configuration |
| Full CLI reference | api |
| Create custom template | patterns → configuration |
| Convert existing project | README → patterns |
Post-Creation
cd my-app
# Local dev with hot reload
npm run dev
# Generate TypeScript types for bindings
npm run cf-typegen
# Deploy to Cloudflare
npm run deploySee Also
- workers/README.md - Workers runtime, bindings, APIs
- workers-ai/README.md - AI/ML models
- pages/README.md - Pages-specific features
- wrangler/README.md - Wrangler CLI beyond initial setup
- d1/README.md - SQLite database
- r2/README.md - Object storage
Overview (`packages/autoskills/skills-registry/cloudflare/references/containers/README.md`)
Cloudflare Containers
Use this reference for containerized applications on the Workers platform, including container-enabled Durable Objects, lifecycle management, and request routing.
Choose the runtime
Use Containers for existing container images, custom runtimes, system dependencies, full filesystem access, or workloads needing additional CPU and memory. Use Workers when the application fits the Workers runtime without those requirements.
Containers are controlled through Durable Objects. An instance's identity does not make its filesystem persistent: design for restarts and store durable data outside the container disk. Read Container lifecycle and Container interface for the relationship between the process, its Durable Object, and persistent storage.
Find the documentation for the task
Read the linked page before writing code or configuration; use its current API, examples, and constraints rather than reconstructing them from memory.
| Task | Start here |
|---|---|
| Create a project and deploy the first container | Get started |
| Configure images, bindings, instance sizes, and deployments | Configuration |
| Control startup, requests, lifecycle, and scheduling | API |
| Choose routing or connect other services | Patterns |
| Diagnose startup, persistence, capacity, or rollout issues | Gotchas |
For additional topics, consult the Containers documentation index.
Overview (`packages/autoskills/skills-registry/cloudflare/references/cron-triggers/README.md`)
Cloudflare Cron Triggers
Use Cron Triggers to start periodic Worker jobs. Fetch the relevant current documentation before implementing; configuration, API signatures, examples, and limits belong in the docs.
- Set up a recurring job: Cron Triggers covers scheduling, deployment, and execution history.
- Implement the job: Scheduled handler covers controller properties, asynchronous work, and multiple schedules.
- Schedule durable work: Trigger Workflows covers direct Workflow schedules and starting instances from a Worker. Check this before introducing a Worker whose only job is to start a Workflow.
- Check capacity: fetch Workers limits for the target plan and invocation type.
In This Reference
- configuration.md — schedule setup, environments, removal, and Green Compute
- api.md — handler implementation, asynchronous completion, and tests
- patterns.md — choosing execution boundaries and integrations
- gotchas.md — investigating timing, failures, and repeated work
See Also
Overview (`packages/autoskills/skills-registry/cloudflare/references/d1/README.md`)
Cloudflare D1 Database
Use D1 for managed relational application data with SQLite semantics. For an existing external database, consider Hyperdrive; for per-entity coordination, consider Durable Objects. See storage options before choosing a product.
Read the relevant current documentation before implementing. These references route tasks to the source of truth rather than maintaining copies of APIs, configuration, or plan tables.
Start here
- Get started: create a database, bind it to a Worker, and run a first query.
- configuration.md: bindings, environments, migrations, local development, and ORM integration.
- api.md: parameterized queries, batches, sessions, HTTP access, and testing.
- patterns.md: query design, caching, tenant isolation, replication, and recovery.
- gotchas.md: errors, types, constraints, performance, and limits.
Check limits and pricing for capacity, allowances, and plan availability; do not infer them from old examples.
Overview (`packages/autoskills/skills-registry/cloudflare/references/graphql-api/README.md`)
Cloudflare GraphQL Analytics API
Query analytics data across all Cloudflare products via a single GraphQL endpoint. Covers HTTP requests, Workers metrics, DNS, Firewall events, Network Analytics, and 70+ other datasets.
Overview
- Single endpoint for all analytics:
https://api.cloudflare.com/client/v4/graphql - 1,400+ schema types spanning every Cloudflare product
- Two scopes: zone-level (per-domain) and account-level (cross-domain)
- Adaptive sampling on high-traffic datasets with confidence intervals
- No mutations - read-only analytics (the Mutation type is a stub)
- Cost-based rate limiting - default 300 queries per 5 minutes per user (max 320, varies by query cost)
Quick Decision Tree
Need analytics data from Cloudflare?
├─ HTTP traffic (requests, bandwidth, cache) → httpRequestsAdaptiveGroups (zone or account)
├─ Workers performance (CPU, wall time, errors) → workersInvocationsAdaptive (account)
├─ Firewall/WAF events → firewallEventsAdaptive / firewallEventsAdaptiveGroups (zone or account)
├─ DNS query analytics → dnsAnalyticsAdaptive / dnsAnalyticsAdaptiveGroups (zone or account)
├─ Network layer (DDoS, Magic Transit) → *NetworkAnalyticsAdaptiveGroups (account)
├─ Storage (R2, KV, D1, DO) → r2OperationsAdaptiveGroups / kvOperationsAdaptiveGroups / etc. (account)
├─ AI (Workers AI, AI Gateway) → aiInferenceAdaptive / aiGatewayRequestsAdaptiveGroups (account)
├─ Load Balancing → loadBalancingRequestsAdaptiveGroups (zone)
├─ Custom high-cardinality metrics → Workers Analytics Engine (see ../analytics-engine/)
└─ Need raw logs, not aggregates → Logpush (see Cloudflare docs)Core Concepts
| Concept | Description |
|---|---|
| Endpoint | POST https://api.cloudflare.com/client/v4/graphql |
| Explorer | graphql.cloudflare.com - interactive query builder |
| Viewer | Root query object: viewer { zones(...) { ... } } or viewer { accounts(...) { ... } } |
| Dataset (Node) | A queryable table under a zone or account (e.g., httpRequestsAdaptiveGroups) |
| Dimensions | Fields to group by (time buckets, country, status code, script name, etc.) |
| Metrics | Aggregation fields: count, sum { ... }, avg { ... }, quantiles { ... }, ratio { ... } |
| Filter | Input object constraining results by time range, dimensions, etc. |
| Limit | Maximum rows returned per dataset node (required, max varies by dataset) |
| OrderBy | Enum-based sorting: [field_ASC] or [field_DESC] |
| Adaptive Sampling | Nodes with Adaptive in the name use ABR sampling; results are statistically representative |
Query Structure
Every query follows this pattern:
{
viewer {
# Zone-scoped
zones(filter: { zoneTag: "ZONE_ID" }) {
datasetName(
filter: { datetime_gt: "...", datetime_lt: "..." }
limit: 1000
orderBy: [datetimeFiveMinutes_DESC]
) {
count
dimensions { ... }
sum { ... }
}
}
# Account-scoped
accounts(filter: { accountTag: "ACCOUNT_ID" }) {
datasetName(filter: { ... }, limit: 100) {
count
dimensions { ... }
sum { ... }
}
}
}
}Dataset Naming Convention
Dataset names follow a consistent pattern visible in the schema:
| Pattern | Meaning | Example |
|---|---|---|
*Adaptive |
Raw rows with adaptive sampling; some (e.g., workersInvocationsAdaptive) also support aggregation fields (sum, quantiles, avg) |
httpRequestsAdaptive, workersInvocationsAdaptive |
*AdaptiveGroups |
Aggregated data with adaptive sampling | httpRequestsAdaptiveGroups |
*1hGroups |
Hourly rollups (pre-aggregated) | httpRequests1hGroups |
*1dGroups |
Daily rollups (pre-aggregated) | httpRequests1dGroups |
*1mGroups |
Minutely rollups | httpRequests1mGroups |
Zone* prefix |
Zone-scoped dataset | ZoneHttpRequestsAdaptiveGroups |
Account* prefix |
Account-scoped dataset | AccountWorkersInvocationsAdaptive |
Prefer *AdaptiveGroups nodes for most use cases - they support flexible time grouping via dimension fields (datetimeFiveMinutes, datetimeHour, etc.) and are the most commonly used.
Key Datasets by Product
Zone-Scoped (per-domain)
| Dataset | Description |
|---|---|
httpRequestsAdaptiveGroups |
HTTP traffic: requests, bytes, cache status, bot scores, WAF scores |
httpRequests1hGroups / 1dGroups / 1mGroups |
Pre-aggregated HTTP rollups (hourly/daily/minutely) |
firewallEventsAdaptiveGroups |
WAF, rate limiting, bot management, firewall rule events |
dnsAnalyticsAdaptiveGroups |
DNS query volumes, response codes, query types |
loadBalancingRequestsAdaptiveGroups |
Load Balancer origin request metrics |
pageShieldReportsAdaptiveGroups |
Page Shield CSP reports |
Account-Scoped (cross-domain)
| Dataset | Description |
|---|---|
workersInvocationsAdaptive |
Workers: requests, errors, CPU time, wall time, subrequests |
durableObjectsInvocationsAdaptiveGroups |
DO invocations |
durableObjectsStorageGroups / durableObjectsPeriodicGroups |
DO storage and periodic metrics |
d1AnalyticsAdaptiveGroups / d1QueriesAdaptiveGroups |
D1 database analytics |
r2OperationsAdaptiveGroups / r2StorageAdaptiveGroups |
R2 operations and storage |
kvOperationsAdaptiveGroups / kvStorageAdaptiveGroups |
KV operations and storage |
aiInferenceAdaptiveGroups |
Workers AI inference metrics |
aiGatewayRequestsAdaptiveGroups |
AI Gateway request analytics |
pagesFunctionsInvocationsAdaptiveGroups |
Pages Functions metrics |
magicTransitNetworkAnalyticsAdaptiveGroups |
Magic Transit packet/byte analytics |
spectrumNetworkAnalyticsAdaptiveGroups |
Spectrum TCP/UDP analytics |
gatewayL7RequestsAdaptiveGroups |
Zero Trust Gateway HTTP metrics |
gatewayResolverQueriesAdaptiveGroups |
Zero Trust Gateway DNS metrics |
Reading Order
| Task | Start Here | Then Read |
|---|---|---|
| First query | configuration.md (auth) -> this README (structure) | api.md |
| Build a dashboard | patterns.md (time-series, top-N) | api.md (aggregation fields) |
| Debug query issues | gotchas.md | api.md (filtering) |
| Understand sampling | gotchas.md (sampling section) | api.md (confidence intervals) |
| Product-specific metrics | patterns.md (per-product examples) | api.md (dataset reference) |
In This Reference
- api.md - Query structure, aggregation fields (sum/avg/quantiles/count), filtering operators, dimensions, dataset details
- configuration.md - Authentication, API tokens, client setup (curl, JS, Python), introspection
- patterns.md - Common queries: time-series, top-N, Workers metrics, HTTP analytics, firewall events, multi-zone
- gotchas.md - Rate limits, sampling caveats, query cost, common errors, plan-based limits
See Also
- GraphQL Analytics API Docs
- GraphQL API Explorer
- Observability Reference - Workers Logs, Tail Workers, console logging
- Analytics Engine Reference - Custom high-cardinality analytics via Workers
- Web Analytics docs - Client-side (RUM) analytics
- Cloudflare API docs - REST API, SDKs, authentication basics
Overview (`packages/autoskills/skills-registry/cloudflare/references/hyperdrive/README.md`)
Hyperdrive
Use Hyperdrive to connect Workers to an existing PostgreSQL or MySQL database with connection pooling and optional query caching. It does not replace the origin database or replicate its data. Start with how Hyperdrive works and supported databases and features to assess fit.
Retrieve current documentation
Fetch the relevant official page before implementing. Driver versions, compatibility settings, API shapes, CLI flags, cache settings, and limits belong in the docs rather than this reference. Use the Hyperdrive documentation index to discover additional pages. Retrieve a page as Markdown by sending Accept: text/markdown to its URL.
Choose the next reference
| Task | Reference |
|---|---|
| Create a configuration, bind it, connect privately, or develop locally | configuration.md |
| Choose a driver, use binding credentials, or integrate an ORM | api.md |
| Decide read freshness, connection lifetime, or query placement | patterns.md |
| Diagnose connection, cache, latency, or capacity problems | gotchas.md |
Decisions to preserve
- Choose a driver for the database engine and existing application stack; verify supported versions and Worker requirements in its guide.
- Create database clients inside each handler invocation. Hyperdrive manages the underlying origin pool; consult connection lifecycle for cleanup behavior.
- Choose caching by read freshness. Disabling caching still allows connection pooling; a write does not invalidate cached reads. See query caching.
See also
Overview (`packages/autoskills/skills-registry/cloudflare/references/images/README.md`)
Cloudflare Images
Choose the image source and operation before selecting an API. Hosted-image management, remote URL transformations, and the Workers optimization binding have different contracts. Retrieve the documentation for the path the project uses.
| Task | Start here |
|---|---|
| Optimize image bytes in a Worker or manage hosted images | API selection |
| Configure a binding, variants, or private delivery | Configuration |
| Accept client uploads, serve responsive images, watermark, or store results in R2 | Patterns |
| Diagnose failures, check limits, or investigate caching | Troubleshooting |
For new work, inspect the project's installed Wrangler version, compatibility settings, existing image storage, and public/private access requirements. Read only the relevant linked pages and adapt them to the project; preserve existing conventions and verify behavior with representative images.
Overview (`packages/autoskills/skills-registry/cloudflare/references/kv/README.md`)
Cloudflare Workers KV
Use KV for read-heavy configuration, preferences, and application caches that tolerate stale data. Read how KV works before choosing it: reads are eventually consistent, including cached missing keys, and immediate visibility is not guaranteed even in the location of a write.
For atomic updates or coordination, consider Durable Objects; for relational queries, D1; for large objects, R2. Use the storage comparison to choose based on requirements.
Read the current documentation for the task before implementing. Use the KV documentation index to discover additional guides; these files preserve task routes rather than copies of APIs, commands, or numeric limits.
Start here
- Get started: create a namespace, bind it, and read and write data.
- configuration.md: bindings, environments, types, local development, CLI, and REST access.
- api.md: reads, writes, metadata, deletion, bulk operations, and pagination.
- patterns.md: caching, sessions, key design, versioning, and fallback decisions.
- gotchas.md: stale reads, concurrent writes, missing values, performance, limits, and pricing.
Overview (`packages/autoskills/skills-registry/cloudflare/references/miniflare/README.md`)
Miniflare
Miniflare provides programmatic control of local Workers simulation. Read the linked documentation before choosing APIs, configuration, or a migration path.
Choose the testing tool
| Need | Start here |
|---|---|
| Unit tests that execute in the Workers runtime | Workers Vitest setup |
| Integration tests against built Workers | Integration test harness |
| Low-level simulator control for a custom harness | Miniflare testing guide |
| Binding access from a Node.js process | Wrangler getPlatformProxy |
For interactive local development, use the project's Wrangler or Cloudflare Vite workflow. Direct Miniflare is useful when the higher-level testing tools do not expose the control needed.
Read for the task
- Get started — installation, scripts, lifecycle, and event dispatch.
- API routing — events and access to local resources.
- Configuration — modules, bindings, compatibility, and multiple Workers.
- Testing patterns — runtime choice, mocking, and test lifecycle.
- Troubleshooting and migrations — build/configuration differences and existing test suites.
Overview (`packages/autoskills/skills-registry/cloudflare/references/observability/README.md`)
Cloudflare Observability
Use this reference to choose a telemetry signal and find the maintained implementation guide. Fetch the linked documentation before writing configuration, queries, or export code; it is the source of truth for APIs, availability, retention, limits, and pricing.
Choose a signal
| Need | Start here |
|---|---|
| Store, search, and investigate historical Worker logs | Workers Logs |
| Watch a deployment or reproduce an issue live | Real-time logs and Wrangler tail |
| Understand request flows and dependency latency | Workers Traces |
| Monitor built-in request, error, and CPU metrics | Metrics and analytics |
| Record custom events and tenant-level usage for SQL analysis | Analytics Engine |
| Export logs and traces to an observability provider | OpenTelemetry export |
| Apply custom filtering, transformation, or delivery logic | Tail Workers |
| Deliver Workers Trace Events to a supported log storage destination | Workers Logpush |
Workers Logs supports retained historical data; live tailing is a separate debugging workflow. Choose persistence, sampling, and export destinations deliberately rather than assuming that every signal is stored or included without usage charges.
Load only what the task needs
- configuration.md: enable collection, bindings, environments, and exports.
- api.md: logging, telemetry types, SQL, GraphQL, and Logpush APIs.
- patterns.md: billing, performance, errors, tenant tracking, and export decisions.
- gotchas.md: missing data, sampling, timing, privacy, and cost checks.
For broader product tasks, see Analytics Engine, GraphQL API, and Tail Workers.
Overview (`packages/autoskills/skills-registry/cloudflare/references/pages-functions/README.md`)
Cloudflare Pages Functions
Use this reference for server-side behavior in an existing Pages project. For new applications, follow the Workers recommendation in the Pages framework guidance.
| Task | Documentation |
|---|---|
| Identify filesystem routes and invocation boundaries | Routing |
| Implement request handlers | API reference |
| Understand generated Worker output | Advanced mode |
Inspect whether the project uses a Functions directory or framework-generated advanced mode before selecting a routing approach. Fetch current documentation for signatures, supported bindings, configuration, and examples.
In This Reference
- api.md — handlers, context, middleware, and assets
- configuration.md — bindings, environments, types, and local development
- patterns.md — request ownership and shared logic
- gotchas.md — route, binding, and runtime investigation
See Pages for builds and deployment decisions.
Overview (`packages/autoskills/skills-registry/cloudflare/references/pages/README.md`)
Cloudflare Pages
Use this reference when maintaining an existing Pages project. For new applications, start with Workers as recommended in the Pages framework guidance. Fetch current documentation before implementing.
| Task | Documentation |
|---|---|
| Configure the existing build | Build configuration |
| Manage automatic deployments from a repository | Git integration |
| Deploy prebuilt output | Direct Upload |
| Implement server-side requests | Functions API reference |
| Plan a move to Workers | Migrate from Pages to Workers |
In This Reference
- configuration.md — build output, environments, and static rules
- api.md — request handling and framework integration
- patterns.md — project decisions and migration
- gotchas.md — build, routing, and deployment investigation
See Pages Functions for handler-focused navigation. Identify the existing deployment method and framework before proposing changes.
Overview (`packages/autoskills/skills-registry/cloudflare/references/queues/README.md`)
Cloudflare Queues
Use Queues to decouple producers from asynchronous consumers and buffer bursts of work. Design consumers for duplicate delivery; use Workflows when the task needs durable multi-step orchestration.
Fetch the relevant documentation below before implementing. Treat current Cloudflare docs as the source of truth for API signatures, acknowledgement semantics, configuration, limits, and pricing.
Choose a consumer
- Use a Worker push consumer when processing runs on Workers.
- Use an HTTP pull consumer when processing runs in another environment; plan for polling, visibility timeouts, and acknowledgement leases.
- Choose a message encoding the consumer can decode. Check serialization and compatibility-date behavior before sending existing application objects.
See How Queues works and delivery guarantees before choosing ordering or deduplication strategies.
Read by task
| Task | Reference |
|---|---|
| Create queues, bind producers, and configure consumers | configuration.md |
| Send messages and implement acknowledgement or retries | api.md |
| Buffer APIs, defer jobs, or integrate with storage and orchestration | patterns.md |
| Diagnose delivery failures, duplicates, or capacity issues | gotchas.md |
For a first application, fetch Getting started. Retrieve limits and pricing before sizing throughput, retention, or cost; plan-specific values are not maintained here.
Overview (`packages/autoskills/skills-registry/cloudflare/references/r2/README.md`)
Cloudflare R2 Object Storage
Use R2 for objects such as uploads, media, backups, and static assets. Fetch the linked documentation before implementing; API signatures, configuration, limits, and pricing belong in the current docs.
Choose an access path
- Use a Workers binding for object access inside a Worker: Workers API setup.
- Use the S3-compatible API for existing S3 clients or direct client access through presigned URLs: S3 setup. Check supported operations rather than assuming full S3 parity.
- Decide whether objects need application authorization, temporary access, or public delivery before exposing the bucket. See patterns.md.
Find the task
| Task | Reference |
|---|---|
| Bindings, credentials, local development, bucket settings | configuration.md |
| Object operations, metadata, conditions, multipart, CLI | api.md |
| Uploads, streaming, caching, public delivery, event processing | patterns.md |
| Pagination, conditional responses, failed uploads, limits | gotchas.md |
For other topics, discover pages through the R2 documentation index. Check pricing before estimating costs.
See also
- Workers for request handling.
- KV or D1 for application metadata associated with objects.
- Queues for asynchronous processing of object events.
Overview (`packages/autoskills/skills-registry/cloudflare/references/secrets-store/README.md`)
Cloudflare Secrets Store
Use Secrets Store for account-level credentials shared across Workers or supported integrations. Use Worker secrets when credentials belong to one Worker and do not need centralized sharing.
Fetch the relevant documentation before implementing. Current Cloudflare docs are the source of truth for binding APIs, management commands, permissions, availability, and quotas. Use the Secrets Store documentation index to discover additional guidance.
Choose the scope
- Share a secret only among services that should use the same credential and rotate together.
- Separate development, staging, and production credentials; select the intended account and environment before managing or binding a secret.
- Grant only the management permissions and consuming-service scopes needed. Permission to view metadata does not imply permission to bind or retrieve a value; fetch access control for the current rules.
Read by task
| Task | Reference |
|---|---|
| Create secrets, configure bindings, or prepare local development | configuration.md |
| Read a secret in a Worker or automate management | api.md |
| Plan rotation, migration, encryption, or auditing | patterns.md |
| Diagnose access, deployment, or quota failures | gotchas.md |
Fetch the product overview for current availability and supported integrations. For AI Gateway provider credentials, use Bring your own keys.
Overview (`packages/autoskills/skills-registry/cloudflare/references/smart-placement/README.md`)
Cloudflare Workers Smart Placement
Automatic workload placement optimization to minimize latency by running Workers closer to backend infrastructure rather than end users.
Core Concept
Smart Placement automatically analyzes Worker request duration across Cloudflare's global network and intelligently routes requests to optimal data center locations. Instead of defaulting to the location closest to the end user, Smart Placement can forward requests to locations closer to backend infrastructure when this reduces overall request duration.
When to Use
Enable Smart Placement when:
- Worker makes multiple round trips to backend services/databases
- Backend infrastructure is geographically concentrated
- Request duration dominated by backend latency rather than network latency from user
- Running backend logic in Workers (APIs, data aggregation, SSR with DB calls)
- Worker uses
fetchhandler (not RPC methods)
Do NOT enable for:
- Workers serving only static content or cached responses
- Workers without significant backend communication
- Pure edge logic (auth checks, redirects, simple transformations)
- Workers without fetch event handlers
- Workers with RPC methods or named entrypoints (only
fetchhandlers are affected) - Pages/Assets Workers with
run_worker_first = true(degrades asset serving)
Decision Tree
Does your Worker have a fetch handler?
├─ No → Smart Placement won't work (skip)
└─ Yes
│
Does it make multiple backend calls (DB/API)?
├─ No → Don't enable (won't help)
└─ Yes
│
Is backend geographically concentrated?
├─ No (globally distributed) → Probably won't help
└─ Yes or uncertain
│
Does it serve static assets with run_worker_first=true?
├─ Yes → Don't enable (will hurt performance)
└─ No → Enable Smart Placement
│
After 15min, check placement_status
├─ SUCCESS → Monitor metrics
├─ INSUFFICIENT_INVOCATIONS → Need more traffic
└─ UNSUPPORTED_APPLICATION → Disable (hurting performance)Key Architecture Pattern
Recommended: Split full-stack applications into separate Workers:
User → Frontend Worker (at edge, close to user)
↓ Service Binding
Backend Worker (Smart Placement enabled, close to DB/API)
↓
Database/Backend ServiceThis maintains fast, reactive frontends while optimizing backend latency.
Quick Start
// wrangler.jsonc
{
"placement": {
"mode": "smart" // or "off" to explicitly disable
}
}Deploy and wait 15 minutes for analysis. Check status via API or dashboard metrics.
To disable: Set "mode": "off" or remove placement field entirely (both equivalent).
Requirements
- Wrangler 2.20.0+
- Analysis time: Up to 15 minutes after enabling
- Traffic requirements: Consistent traffic from multiple global locations
- Available on all Workers plans (Free, Paid, Enterprise)
Placement Status Values
type PlacementStatus =
| undefined // Not yet analyzed
| 'SUCCESS' // Successfully optimized
| 'INSUFFICIENT_INVOCATIONS' // Not enough traffic
| 'UNSUPPORTED_APPLICATION'; // Made Worker slower (reverted)CLI Commands
# Deploy with Smart Placement
wrangler deploy
# Check placement status
curl -H "Authorization: Bearer $TOKEN" \
https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \
| jq .result.placement_status
# Monitor
wrangler tail your-worker-name --header cf-placementReading Order
First time? Start here:
- This README - understand core concepts and when to use Smart Placement
- configuration.md - set up wrangler.jsonc and understand limitations
- patterns.md - see practical examples for your use case
- api.md - monitor and verify Smart Placement is working
- gotchas.md - troubleshoot common issues
Quick lookup:
- "Should I enable Smart Placement?" → See "When to Use" above
- "How do I configure it?" → configuration.md
- "How do I split frontend/backend?" → patterns.md
- "Why isn't it working?" → gotchas.md
In This Reference
- configuration.md - wrangler.jsonc setup, mode values, validation rules
- api.md - Placement Status API, cf-placement header, monitoring
- patterns.md - Frontend/backend split, database workers, SSR patterns
- gotchas.md - Troubleshooting INSUFFICIENT_INVOCATIONS, performance issues
See Also
- workers - Worker runtime and fetch handlers
- d1 - D1 database that benefits from Smart Placement
- durable-objects - Durable Objects with backend logic
- bindings - Service bindings for frontend/backend split
Overview (`packages/autoskills/skills-registry/cloudflare/references/static-assets/README.md`)
Workers Static Assets
Use Workers Static Assets for new static sites, SPAs, generated sites, and applications combining assets with server logic. Inspect the framework, build output, and existing deployment configuration before changing routing.
| Task | Documentation |
|---|---|
| Set up and deploy a static site or application | Get started |
| Choose configuration and an optional asset binding | Configuration and bindings |
| Serve a client-rendered application | SPA routing |
| Serve generated HTML and custom error pages | SSG routing |
| Use a full-stack framework | Full-stack application guides |
| Evaluate moving an existing Pages project | Pages migration guide |
Do not choose a platform solely from the framework name. For an existing Pages project, inspect its current features and migration requirements before proposing a move.
Reading Order
- configuration.md — build output and routing configuration.
- api.md — fetch assets and handle responses.
- patterns.md — choose a routing design.
- gotchas.md — diagnose routing, caching, and deployment issues.
Overview (`packages/autoskills/skills-registry/cloudflare/references/stream/README.md`)
Cloudflare Stream
Use Stream for on-demand video upload and playback or live broadcasting. Start with the application's upload source, player, and access requirements, then read the corresponding documentation before writing code.
Choose a Workflow
| Task | Read |
|---|---|
| Let users upload without exposing an API token | Direct creator uploads |
| Choose server upload, resumable upload, or import from a URL | Upload methods and supported formats |
| Embed playback or integrate an existing player | Stream Player or HLS/DASH players |
| Restrict viewing to authorized users or embedding origins | Secure your Stream |
| Broadcast live, replay recordings, or simulcast | Live workflow routing |
| Check usage, costs, or upload constraints | Analytics, pricing, and upload requirements |
In This Reference
- configuration.md: project setup and access decisions.
- api.md: upload, playback, editing, and library operations.
- api-live.md: live inputs, outputs, recording, and WebRTC.
- patterns.md: application workflow decisions.
- gotchas.md: troubleshooting routes.
Overview (`packages/autoskills/skills-registry/cloudflare/references/tail-workers/README.md`)
Cloudflare Tail Workers
Use Tail Workers when execution events need custom processing. Fetch the current documentation before implementing handlers, configuration, or integrations.
| Task | Documentation |
|---|---|
| Decide whether custom processing is needed | Tail Workers |
| Export logs and traces to an observability destination | OpenTelemetry export |
| Inspect a deployment interactively | Real-time logs |
| Implement the consumer | Tail handler |
Before adding a Tail Worker, check whether built-in OpenTelemetry export meets the destination’s needs. Use the Tail Workers guide for the tradeoff, then identify the custom filtering or transformation that remains necessary.
In This Reference
- configuration.md — producer, consumer, destination, and environment setup
- api.md — event fields, execution outcomes, and redaction
- patterns.md — destination and filtering decisions
- gotchas.md — connection, data, and delivery investigation
See observability for broader logging and tracing choices.
Overview (`packages/autoskills/skills-registry/cloudflare/references/tunnel/README.md`)
Cloudflare Tunnel
Use Tunnel to connect origin services to Cloudflare. Inspect the existing tunnel, management mode, and intended audience before choosing a setup. Fetch current docs for commands, configuration, and limits.
| Task | Documentation |
|---|---|
| Create a remotely-managed tunnel or a temporary development tunnel | Setup |
| Maintain a tunnel managed through local files | Create a locally-managed tunnel |
| Publish an application and check protocol requirements | Routing |
| Choose private networking, Workers VPC, or Access integration | Integrations |
Decide whether the goal is a public application, authenticated private access, or connectivity from a Worker. Then identify who owns configuration and how it will be deployed; multiple environments alone do not require local management.
In This Reference
- configuration.md — management mode, ingress, and origin settings
- networking.md — firewall, connectivity, and private-network investigation
- api.md — programmatic setup and tunnel operations
- patterns.md — deployment and availability decisions
- gotchas.md — troubleshooting and operational checks
Overview (`packages/autoskills/skills-registry/cloudflare/references/turn/README.md`)
Cloudflare TURN Service
Expert guidance for implementing Cloudflare TURN Service in WebRTC applications.
Overview
Cloudflare TURN (Traversal Using Relays around NAT) Service is a managed relay service for WebRTC applications. TURN acts as a relay point for traffic between WebRTC clients and SFUs, particularly when direct peer-to-peer communication is obstructed by NATs or firewalls. The service runs on Cloudflare's global anycast network across 310+ cities.
Key Characteristics
- Anycast Architecture: Automatically connects clients to the closest Cloudflare location
- Global Network: Available across Cloudflare's entire network (excluding China Network)
- Zero Configuration: No need to manually select regions or servers
- Protocol Support: STUN/TURN over UDP, TCP, and TLS
- Free Tier: Free when used with Cloudflare Calls SFU, otherwise $0.05/GB outbound
In This Reference
| File | Purpose |
|---|---|
| api.md | Credentials API, TURN key management, types, constraints |
| configuration.md | Worker setup, wrangler.jsonc, env vars, IP allowlisting |
| patterns.md | Implementation patterns, use cases, integration examples |
| gotchas.md | Troubleshooting, limits, security, common mistakes |
Reading Order
| Task | Files to Read | Est. Tokens |
|---|---|---|
| Quick start | README only | ~500 |
| Generate credentials | README → api | ~1300 |
| Worker integration | README → configuration → patterns | ~2000 |
| Debug connection | gotchas | ~700 |
| Security review | api → gotchas | ~1500 |
| Enterprise firewall | configuration | ~600 |
Service Addresses and Ports
STUN over UDP
- Primary:
stun.cloudflare.com:3478/udp - Alternate:
stun.cloudflare.com:53/udp(blocked by browsers, not recommended)
TURN over UDP
- Primary:
turn.cloudflare.com:3478/udp - Alternate:
turn.cloudflare.com:53/udp(blocked by browsers)
TURN over TCP
- Primary:
turn.cloudflare.com:3478/tcp - Alternate:
turn.cloudflare.com:80/tcp
TURN over TLS
- Primary:
turn.cloudflare.com:5349/tcp - Alternate:
turn.cloudflare.com:443/tcp
Quick Start
- Create TURN key via API: see api.md#create-turn-key
- Generate credentials: see api.md#generate-temporary-credentials
- Configure Worker: see configuration.md#cloudflare-worker-integration
- Implement client: see patterns.md#basic-turn-configuration-browser
When to Use TURN
- Restrictive NATs: Symmetric NATs that block direct connections
- Corporate firewalls: Environments blocking WebRTC ports
- Mobile networks: Carrier-grade NAT scenarios
- Predictable connectivity: When reliability > efficiency
Related Cloudflare Services
- Cloudflare Calls SFU: Managed Selective Forwarding Unit (TURN free when used with SFU)
- Cloudflare Stream: Video streaming with WHIP/WHEP support
- Cloudflare Workers: Backend for credential generation
- Cloudflare KV: Credential caching
- Cloudflare Durable Objects: Session state management
Additional Resources
- Cloudflare Calls Documentation
- Cloudflare TURN Service Docs
- Cloudflare API Reference
- Orange Meets (Open Source Example)
Overview (`packages/autoskills/skills-registry/cloudflare/references/vectorize/README.md`)
Cloudflare Vectorize
Use Vectorize when you need to control embeddings, vector indexing, and retrieval for semantic search, recommendations, or RAG. For a managed retrieval pipeline, see AI Search.
Fetch current documentation before implementing. Start with the Vectorize documentation index to discover pages; load only those relevant to the task. Treat the docs as the source of truth for APIs, configuration, models, limits, and pricing.
Task routing
| Task | Read |
|---|---|
| Create an index and connect a Worker | Configuration and Introduction to Vectorize |
| Insert, update, query, retrieve, or delete vectors | API routes |
| Generate embeddings, build RAG, or partition tenant data | Patterns |
| Diagnose missing matches, metadata, or rejected requests | Gotchas |
Decisions to make first
- Use a consistent embedding model and preprocessing for stored vectors and queries. Matching dimensions alone does not make different models' embeddings compatible.
- Choose dimensions from the embedding output and a distance metric appropriate to that model. Changing either requires a new index; check index configuration and scoring semantics before choosing thresholds.
- Plan filterable metadata before ingestion. Adding an index later requires re-upserting existing vectors to index that metadata; see metadata filtering.
- A namespace partitions search; your application must authorize access and derive tenant scope from trusted identity. See tenant patterns.
- Design for asynchronous mutation visibility rather than assuming a completed write is already searchable. See mutation semantics.
Overview (`packages/autoskills/skills-registry/cloudflare/references/waf/README.md`)
Cloudflare WAF
Use this reference for managed protection, custom request policies, rate limiting, and investigation of blocked traffic. Read the relevant developer documentation before implementing; it owns schemas, expressions, ruleset IDs, phase order, and plan availability.
| Task | Start here |
|---|---|
| Choose and enable WAF protections | Get started |
| Deploy managed protection | Managed rules deployment |
| Match application-specific requests | Custom rules |
| Limit request volume | Rate limiting |
| Understand score-based detection | Attack score |
| Diagnose blocked or unmitigated requests | Managed rules troubleshooting |
Identify the target account or zone and inspect existing rules before planning a change. Keep the requested traffic scope explicit, especially for exceptions and account-wide deployments.
Reading Order
- configuration.md — deployment method and existing configuration.
- api.md — API workflows and expression references.
- patterns.md — choose a protection or exception workflow.
- gotchas.md — diagnose ordering, scope, and false positives.
Overview (`packages/autoskills/skills-registry/cloudflare/references/workerd/README.md`)
Workerd Runtime
V8-based JS/Wasm runtime powering Cloudflare Workers. Use as app server, dev tool, or HTTP proxy.
⚠️ IMPORTANT SECURITY NOTICE
workerd is NOT a hardened sandbox. Do not run untrusted code. It's designed for deploying YOUR code locally/self-hosted, not multi-tenant SaaS. Cloudflare production adds security layers not present in open-source workerd.
Decision Tree: When to Use What
95% of users: Use Wrangler
- Local development:
wrangler dev(uses workerd internally) - Deployment:
wrangler deploy(deploys to Cloudflare) - Types:
wrangler types(generates TypeScript types)
Use raw workerd directly only if:
- Self-hosting Workers runtime in production
- Embedding runtime in C++ application
- Custom tooling/testing infrastructure
- Debugging workerd-specific behavior
Never use workerd for:
- Running untrusted/user-submitted code
- Multi-tenant isolation (not hardened)
- Production without additional security layers
Key Features
- Standards-based: Fetch API, Web Crypto, Streams, WebSocket
- Nanoservices: Service bindings with local call performance
- Capability security: Explicit bindings prevent SSRF
- Backwards compatible: Version = max compat date supported
Architecture
Config (workerd.capnp)
├── Services (workers/endpoints)
├── Sockets (HTTP/HTTPS listeners)
└── Extensions (global capabilities)Quick Start
workerd serve config.capnp
workerd compile config.capnp myConfig -o binary
workerd test config.capnpPlatform Support & Beta Status
| Platform | Status | Notes |
|---|---|---|
| Linux (x64) | Stable | Primary platform |
| macOS (x64/ARM) | Stable | Full support |
| Windows | Beta | Use WSL2 for best results |
| Linux (ARM64) | Experimental | Limited testing |
workerd is in active development. Breaking changes possible. Pin versions in production.
Core Concepts
- Service: Named endpoint (worker/network/disk/external)
- Binding: Capability-based resource access (KV/DO/R2/services)
- Compatibility date: Feature gate (always set!)
- Modules: ES modules (recommended) or service worker syntax
Reading Order (Progressive Disclosure)
Start here:
- This README (overview, decision tree)
- patterns.md - Common workflows, framework examples
When you need details:
3. configuration.md - Config format, services, bindings
4. api.md - Runtime APIs, TypeScript types
5. gotchas.md - Common errors, debugging
Related References
- workers - Workers runtime API documentation
- miniflare - Testing tool built on workerd
- wrangler - CLI that uses workerd for local dev
Overview (`packages/autoskills/skills-registry/cloudflare/references/workers-ai/README.md`)
Cloudflare Workers AI
Use Workers AI for managed model inference from Workers or an external service. Fetch the relevant documentation before choosing a model or writing integration code; model availability, schemas, capabilities, limits, and prices change independently.
Choose a model
Start with the model catalog and open the selected model's page for its exact identifier, input/output schema, context window, and supported features. Compare candidates on the user's task, language, quality requirements, latency, and current pricing. Evaluate with representative inputs rather than treating model size as a quality or cost ranking.
For tool use, streaming, or structured output, confirm support for the selected model and integration. For embeddings, check output dimensions and compatibility with the existing index; changing the model may require re-embedding stored documents, even if dimensions match.
Route by task
- configuration.md: choose an integration, configure bindings and types, or set up development.
- api.md: find inference schemas, streaming, tool calling, and structured output.
- patterns.md: choose direct generation or RAG, and find integration examples.
- gotchas.md: diagnose binding, schema, limit, pricing, and SDK issues.
If a topic is missing, use the Workers AI documentation index to find its current page.
Related products
- Vectorize: vector storage and retrieval.
- AI Gateway: inference analytics, caching, and request controls.
- Workers: runtime and application hosting.
Overview (`packages/autoskills/skills-registry/cloudflare/references/workflows/README.md`)
Cloudflare Workflows
Use Workflows for durable, multi-step jobs that must retry, wait, and resume without losing completed work. An instance is one execution; steps define persistence and retry boundaries.
Fetch the relevant current documentation before implementing. API shapes, configuration, testing helpers, limits, and examples belong in the docs rather than in this reference.
- Start a project: Build your first Workflow covers scaffolding, configuration, deployment, and a first instance.
- Design durable execution: Rules of Workflows covers step boundaries, replay, state, and idempotency.
- Implement or manage an instance: Workers API covers steps, instance operations, parameters, and return types.
- Check capacity and cost: fetch limits and pricing for the target plan.
In This Reference
- configuration.md — setup, bindings, retry configuration, and local development
- api.md — steps, instance lifecycle, events, CLI, and REST operations
- patterns.md — design decisions, examples, orchestration, and tests
- gotchas.md — failures, timeouts, replay, and capacity investigation
See Also
- Durable Objects — stateful coordination
- Queues — asynchronous message delivery
- Workers — application entry points that trigger instances
Overview (`packages/autoskills/skills-registry/cloudflare/references/zaraz/README.md`)
Cloudflare Zaraz
Expert guidance for Cloudflare Zaraz - server-side tag manager for loading third-party tools at the edge.
What is Zaraz?
Zaraz offloads third-party scripts (analytics, ads, chat, marketing) to Cloudflare's edge, improving site speed, privacy, and security. Zero client-side performance impact.
Core Concepts:
- Server-side execution - Scripts run on Cloudflare, not user's browser
- Single HTTP request - All tools loaded via one endpoint
- Privacy-first - Control data sent to third parties
- No client-side JS overhead - Minimal browser impact
Quick Start
- Navigate to domain > Zaraz in Cloudflare dashboard
- Click "Start setup"
- Add tools (Google Analytics, Facebook Pixel, etc.)
- Configure triggers (when tools fire)
- Add tracking code to your site:
// Track page view
zaraz.track('page_view');
// Track custom event
zaraz.track('button_click', { button_id: 'cta' });
// Set user properties
zaraz.set('userId', 'user_123');When to Use Zaraz
Use Zaraz when:
- Adding multiple third-party tools (analytics, ads, marketing)
- Site performance is critical (no client-side JS overhead)
- Privacy compliance required (GDPR, CCPA)
- Non-technical teams need to manage tools
Use Workers directly when:
- Building custom server-side tracking logic
- Need full control over data processing
- Integrating with complex backend systems
- Zaraz's tool library doesn't meet needs
In This Reference
| File | Purpose | When to Read |
|---|---|---|
| api.md | Web API, zaraz object, consent methods | Implementing tracking calls |
| configuration.md | Dashboard setup, triggers, tools | Initial setup, adding tools |
| patterns.md | SPA, e-commerce, Worker integration | Best practices, common scenarios |
| gotchas.md | Troubleshooting, limits, pitfalls | Debugging issues |
Reading Order by Task
| Task | Files to Read |
|---|---|
| Add analytics to site | README → configuration.md |
| Track custom events | README → api.md |
| Debug tracking issues | gotchas.md |
| SPA tracking | api.md → patterns.md (SPA section) |
| E-commerce tracking | api.md#ecommerce → patterns.md#ecommerce |
| Worker integration | patterns.md#worker-integration |
| GDPR compliance | api.md#consent → configuration.md#consent |
Decision Tree
What do you need?
├─ Track events in browser → api.md
│ ├─ Page views, clicks → zaraz.track()
│ ├─ User properties → zaraz.set()
│ └─ E-commerce → zaraz.ecommerce()
│
├─ Configure Zaraz → configuration.md
│ ├─ Add GA4/Facebook → tools setup
│ ├─ When tools fire → triggers
│ └─ GDPR consent → consent purposes
│
├─ Integrate with Workers → patterns.md#worker-integration
│ ├─ Enrich context → Context Enrichers
│ └─ Inject tracking → HTML rewriting
│
└─ Debug issues → gotchas.md
├─ Events not firing → troubleshooting
├─ Consent issues → consent debugging
└─ Performance → debugging toolsKey Features
- 100+ Pre-built Tools - GA4, Facebook, Google Ads, TikTok, etc.
- Zero Client Impact - Runs at Cloudflare's edge, not browser
- Privacy Controls - Consent management, data filtering
- Custom Tools - Build Managed Components for proprietary systems
- Worker Integration - Enrich context, compute dynamic values
- Debug Mode - Real-time event inspection
Reference
This skill focuses exclusively on Zaraz. For Workers development, see cloudflare-workers skill.
Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/azcli/README.md`)
Azure CLI Deploy Recipe
Deploy to Azure using Azure CLI.
Prerequisites
azCLI installed → Runmcp_azure_mcp_extension_cli_installwithcli-type: azif needed.azure/deployment-plan.mdexists with statusValidated- Bicep/ARM templates exist in
infra/ - Subscription and location confirmed → See Pre-Deploy Checklist
Workflow
| Step | Task | Command |
|---|---|---|
| 1 | Pre-deploy checklist | Confirm subscription/location with user |
| 2 | Deploy infrastructure | az deployment sub create |
| 3 | Deploy application | Service-specific commands |
| 4 | Verify | az resource list |
| 5 | Report | Present deployed endpoint URLs to the user — see Verification |
Infrastructure Deployment
Subscription-Level (Recommended)
az deployment sub create \
--location eastus2 \
--template-file ./infra/main.bicep \
--parameters environmentName=devResource Group Level
az group create --name rg-myapp-dev --location eastus2
az deployment group create \
--resource-group rg-myapp-dev \
--template-file ./infra/main.bicep \
--parameters environmentName=devApplication Deployment
Container Apps
az containerapp update \
--name <app-name> \
--resource-group <rg-name> \
--image <acr-name>.azurecr.io/myapp:latestApp Service
az webapp deploy \
--name <app-name> \
--resource-group <rg-name> \
--src-path ./publish.zipAzure Functions
func azure functionapp publish <function-app-name>References
Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/azd/README.md`)
AZD Deploy Recipe
Deploy to Azure using Azure Developer CLI (azd).
💡 Note: azd supports both Bicep and Terraform as IaC providers. The deployment workflow is identical regardless of which you use.
Prerequisites
azdCLI installed → Runmcp_azure_mcp_extension_cli_installwithcli-type: azdif needed.azure/deployment-plan.mdexists with statusValidatedazure.yamlexists and validated- Infrastructure files exist (Bicep:
infra/main.bicep, Terraform:infra/*.tf) - AZD environment configured → Done in azure-validate
- Subscription and location confirmed → See Pre-deploy Checklist
Workflow
| Step | Task | Command |
|---|---|---|
| 1 | Verify environment | azd env get-values — Confirm AZURE_SUBSCRIPTION_ID and AZURE_LOCATION set |
| 2 | Provision infrastructure | azd provision --no-prompt |
| 3 | RBAC health check (Container Apps + ACR only) | After provisioning, verify AcrPull role has propagated before deploying — see Pre-Deploy Checklist |
| 4 | Deploy application | azd deploy --no-prompt |
| 5 | Post-Deploy | Post-Deployment Steps — If using SQL + managed identity |
| 6 | Verify | See Verification |
| 7 | Report | Present deployed endpoint URLs to the user — see Verification Step 3 |
⚠️ Important: For Container Apps that use a managed identity to pull from ACR, always run
azd provisionandazd deployas separate steps (notazd up) and complete the RBAC health check between them. This ensures the managed identityAcrPullrole assignment has propagated before the Container App revision attempts to pull the image.
⚠️ Important: For .NET Aspire projects or projects using azd "limited mode" (no explicit
infra/folder), verify thatazd provisionpopulated all required environment variables. Ifazd deployfails with errors about missingAZURE_CONTAINER_REGISTRY_ENDPOINT,AZURE_CONTAINER_REGISTRY_MANAGED_IDENTITY_ID, orMANAGED_IDENTITY_CLIENT_ID, see Error Handling for the resolution.
Common Mistakes
| ❌ Wrong | Why It Fails |
|---|---|
azd up --location eastus2 |
--location is not a valid flag for azd up |
azd up without azd env new |
Prompts for input, fails with --no-prompt |
mkdir .azure then azd env new --no-prompt |
Creates env folder structure incorrectly |
| Setting AZURE_LOCATION without checking RG | "Invalid resource group location" if RG exists elsewhere |
Ignoring azd-service-name tag conflicts in same RG |
"found '2' resources tagged with..." error |
language: html or language: static |
Not valid - use language: js with dist: . for static sites |
Deployment Commands
⚠️
azd uptakes 5-15 min. Run with output streamed visibly to the user — do NOT run silently or suppress output. The user must see provisioning progress in real time.
Full Deployment
Provisions infrastructure AND deploys application:
azd up --no-promptInfrastructure Only
azd provision --no-promptApplication Only
Deploy code to existing infrastructure:
azd deploy --no-promptSingle Service
azd deploy api --no-promptReferences
- Pre-deploy Checklist — REQUIRED
- Post-Deployment Steps — SQL + managed identity setup
- Azure Functions Deployment
- Verification
- Error Handling
Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/bicep/README.md`)
Bicep Deploy Recipe
Deploy to Azure using Bicep templates directly.
Prerequisites
azCLI installed with Bicep extension.azure/deployment-plan.mdexists with statusValidated- Bicep templates exist in
infra/ - Subscription and location confirmed → See Pre-Deploy Checklist
Workflow
| Step | Task | Command |
|---|---|---|
| 1 | Pre-deploy checklist | Confirm subscription/location with user |
| 2 | Build (optional) | az bicep build --file main.bicep |
| 3 | Deploy | az deployment sub create |
| 4 | Verify | az resource list |
| 5 | Report | Present deployed endpoint URLs to the user — see Verification |
Deployment Commands
Subscription-Level Deployment
az deployment sub create \
--location eastus2 \
--template-file ./infra/main.bicep \
--parameters ./infra/main.parameters.jsonResource Group Deployment
az deployment group create \
--resource-group rg-myapp-dev \
--template-file ./infra/main.bicep \
--parameters ./infra/main.parameters.jsonWith Inline Parameters
az deployment sub create \
--location eastus2 \
--template-file ./infra/main.bicep \
--parameters environmentName=dev location=eastus2What-If (Preview Changes)
az deployment sub what-if \
--location eastus2 \
--template-file ./infra/main.bicep \
--parameters environmentName=devGet Deployment Outputs
az deployment sub show \
--name main \
--query properties.outputsReferences
MCP Tools
| Tool | Purpose |
|---|---|
mcp_bicep_get_bicep_best_practices |
Best practices |
mcp_bicep_get_az_resource_type_schema |
Resource schemas |
mcp_bicep_list_avm_metadata |
Azure Verified Modules |
AVM Verification Before Deploy
Before running deployment commands, verify generated templates followed AVM-first module selection:
- AVM Bicep Pattern Modules (prefer AVM+AZD patterns)
- AVM Bicep Resource Modules
- AVM Bicep Utility Modules
If no AVM+AZD pattern module is available, fallback must remain within AVM modules (resource -> utility).
Cleanup (DESTRUCTIVE)
az group delete --name <rg-name> --yes⚠️ Permanently deletes ALL resources in the group.
Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/cicd/README.md`)
CI/CD Deploy Recipe
Deploy to Azure using automated pipelines.
Prerequisites
.azure/deployment-plan.mdexists with statusValidated- Azure Service Principal or federated credentials configured
- Pipeline file exists (
.github/workflows/orazure-pipelines.yml)
GitHub Actions
| Example | Description |
|---|---|
| github-azd.yml | AZD deployment workflow |
| github-bicep.yml | Bicep infrastructure deployment |
Azure DevOps
| Example | Description |
|---|---|
| azdo-azd.yml | Basic AZD pipeline |
| azdo-multistage.yml | Multi-stage with approvals |
Setup Requirements
GitHub Actions
- Create Azure Service Principal with federated credentials
- Add secrets:
AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_SUBSCRIPTION_ID - Add variables:
AZURE_ENV_NAME,AZURE_LOCATION - Create environments with protection rules
Azure DevOps
- Create Service Connection to Azure
- Create Variable Groups per environment
- Create Environments with approval gates
References
Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/terraform/README.md`)
Terraform Deploy Recipe
Deploy to Azure using Terraform.
Prerequisites
- Terraform CLI installed
.azure/deployment-plan.mdexists with statusValidated- Terraform initialized (
terraform init) - Plan validated (
terraform plan) - Subscription and location confirmed → See Pre-Deploy Checklist
Workflow
| Step | Task | Command |
|---|---|---|
| 1 | Pre-deploy checklist | Confirm subscription/location with user |
| 2 | Select workspace | terraform workspace select <env> |
| 3 | Apply | terraform apply tfplan |
| 4 | Get outputs | terraform output |
| 5 | Deploy app | Service-specific commands |
| 6 | Report | Present deployed endpoint URLs to the user — see Verification |
Deployment Commands
Apply with Plan File (Recommended)
terraform plan -out=tfplan
terraform apply tfplanAuto-Approve (CI/CD)
terraform apply -auto-approveWith Variables
terraform apply \
-var="environment=prod" \
-var="location=westus2" \
-auto-approveTarget Specific Resource
terraform apply -target=azurerm_container_app.apiGet Outputs
terraform output
terraform output -json
terraform output api_urlApplication Deployment
After infrastructure is deployed:
Container Apps (Two-Phase Deployment)
Container Apps with ACR require a two-phase flow because the app image doesn't exist in ACR during initial terraform apply. See the azure-prepare skill's references/services/container-apps/terraform.md for the full pattern.
ACR_NAME=$(terraform output -raw acr_name)
ACR_SERVER=$(terraform output -raw acr_login_server)
APP_NAME=$(terraform output -raw container_app_name)
RG_NAME=$(terraform output -raw resource_group_name)
# 1. Build and push the application image to ACR
az acr build --registry $ACR_NAME --image myapp:latest ./src/api
# 2. Configure the registry/identity link (managed identity, no passwords)
az containerapp registry set \
--name $APP_NAME \
--resource-group $RG_NAME \
--server $ACR_SERVER \
--identity system
# 3. Update the Container App to use the real image
az containerapp update \
--name $APP_NAME \
--resource-group $RG_NAME \
--image $ACR_SERVER/myapp:latestPowerShell:
$AcrName = terraform output -raw acr_name
$AcrServer = terraform output -raw acr_login_server
$AppName = terraform output -raw container_app_name
$RgName = terraform output -raw resource_group_name
az acr build --registry $AcrName --image myapp:latest ./src/api
az containerapp registry set `
--name $AppName `
--resource-group $RgName `
--server $AcrServer `
--identity system
az containerapp update `
--name $AppName `
--resource-group $RgName `
--image "$AcrServer/myapp:latest"⚠️ Warning: Step 2 requires the
AcrPullrole assignment to have propagated (1–5 minutes). If the update fails, wait and retry. See the RBAC propagation health check.
References
--- METRICS ---
- Files Extracted: 111
- Estimated Token Budget: ~94095 tokens
- Canonical Reference: https://codewiki.google/github.com/midudev/autoskills