cloudflare-workers-expert

Expert in Cloudflare Workers and the Edge Computing ecosystem. Covers Wrangler, KV, D1, Durable Objects, and R2 storage.

31,392 stars
Complexity: medium

About this skill

This skill transforms an AI agent into a senior Cloudflare Workers Engineer, providing deep expertise in edge computing architectures, performance optimization, and the comprehensive Cloudflare developer ecosystem. It covers essential tools and services like Wrangler for CLI operations, KV for key-value storage, D1 for serverless databases, Durable Objects for unique, stateful entities, R2 for object storage, and Queues for asynchronous messaging. The skill is designed to guide the AI in designing, deploying, and optimizing serverless functions at the edge, implementing edge-side data storage solutions, building full-stack applications with Cloudflare Pages, and handling edge-side request/response modifications, security configurations, and caching strategies.

Best use case

Developing and optimizing serverless applications on Cloudflare's global network, leveraging edge computing for low-latency data processing and storage, and integrating with Cloudflare's suite of developer tools and services.

Expert in Cloudflare Workers and the Edge Computing ecosystem. Covers Wrangler, KV, D1, Durable Objects, and R2 storage.

The agent will generate accurate, efficient, and well-structured solutions, code snippets, architectural recommendations, or deployment strategies for Cloudflare Workers-based projects, adhering to best practices for edge computing performance, scalability, and security.

Practical example

Example input

I need to build a serverless API endpoint that fetches data from a database, caches it at the edge, and responds with low latency. How would I implement this using Cloudflare Workers, D1, and KV?

Example output

As a Cloudflare Workers expert, I'd recommend the following architecture and conceptual code structure for your low-latency serverless API using Cloudflare Workers, D1, and KV:

1.  **Cloudflare D1 for Primary Data**: Set up a D1 serverless SQL database to store your application's primary data.
2.  **Cloudflare KV for Edge Caching**: Utilize Cloudflare KV to cache frequently accessed data closer to users at the edge.
3.  **Cloudflare Worker for API Endpoint**: The Worker will act as your API gateway, handling requests, interacting with D1, and managing KV cache.

Here's a simplified conceptual code example for a Worker (`src/index.ts`):

```typescript
import { Router } from 'itty-router';

const router = Router();

router.get('/api/data/:id', async (request, env) => {
    const { id } = request.params;
    const cacheKey = `data_cache:${id}`;

    // 1. Try to fetch from KV cache first
    let cachedData = await env.KV_NAMESPACE.get(cacheKey);
    if (cachedData) {
        console.log('Serving from KV cache');
        return new Response(cachedData, {
            headers: { 'Content-Type': 'application/json', 'X-Cache': 'HIT' }
        });
    }

    // 2. If not in cache, fetch from D1
    console.log('Fetching from D1');
    const { results } = await env.D1_DATABASE.prepare('SELECT * FROM your_table WHERE id = ?')
        .bind(id)
        .all();

    if (results.length === 0) {
        return new Response('Not Found', { status: 404 });
    }

    const data = JSON.stringify(results[0]);

    // 3. Store in KV cache for future requests (e.g., for 5 minutes)
    await env.KV_NAMESPACE.put(cacheKey, data, { expirationTtl: 300 });

    return new Response(data, {
        headers: { 'Content-Type': 'application/json', 'X-Cache': 'MISS' }
    });
});

// Catch-all for other routes
router.all('*', () => new Response('Not Found', { status: 404 }));

export default {
    async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
        return router.handle(request, env, ctx);
    },
};

interface Env {
    KV_NAMESPACE: KVNamespace;
    D1_DATABASE: D1Database;
}
```

**Wrangler Configuration (`wrangler.toml`)**:

```toml
name = "my-edge-api"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[[kv_namespaces]]
binding = "KV_NAMESPACE"
id = "<YOUR_KV_NAMESPACE_ID>"

[[d1_databases]]
binding = "D1_DATABASE"
database_name = "your_database_name"
database_id = "<YOUR_D1_DATABASE_ID>"
```

**Steps to Implement**:

1.  **Initialize Worker**: Use `npx wrangler init my-edge-api` to create a new Worker project.
2.  **Set up D1**: Create your D1 database using `npx wrangler d1 create your_database_name` and then define your schema with `npx wrangler d1 execute your_database_name --file=./schema.sql`.
3.  **Create KV Namespace**: Create a KV namespace with `npx wrangler kv namespace create MY_KV_NAMESPACE`.
4.  **Update `wrangler.toml`**: Populate your `wrangler.toml` file with the generated `id`s for your KV namespace and D1 database.
5.  **Develop Worker Logic**: Implement your API logic within `src/index.ts` as conceptually shown above, integrating with D1 and KV.
6.  **Deploy**: Deploy your Worker to Cloudflare's edge network using `npx wrangler deploy`.

This setup ensures data is fetched efficiently, cached at the edge for optimal performance, and served quickly to users globally, leveraging the power of Cloudflare's developer platform.

When to use this skill

  • Designing and deploying serverless functions to Cloudflare's Edge.
  • Implementing edge-side data storage using KV, D1, or Durable Objects.
  • Optimizing application latency by moving logic and data processing to the edge.
  • Building full-stack applications with Cloudflare Pages and Workers.

When not to use this skill

  • When the task does not involve Cloudflare Workers or the Cloudflare ecosystem.
  • For applications requiring traditional server-based deployments or cloud providers other than Cloudflare.
  • For tasks focused solely on backend services without an edge computing component or a need for global distribution.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/cloudflare-workers-expert/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/cloudflare-workers-expert/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/cloudflare-workers-expert/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How cloudflare-workers-expert Compares

Feature / Agentcloudflare-workers-expertStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexitymediumN/A

Frequently Asked Questions

What does this skill do?

Expert in Cloudflare Workers and the Edge Computing ecosystem. Covers Wrangler, KV, D1, Durable Objects, and R2 storage.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as medium. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

You are a senior Cloudflare Workers Engineer specializing in edge computing architectures, performance optimization at the edge, and the full Cloudflare developer ecosystem (Wrangler, KV, D1, Queues, etc.).

## Use this skill when

- Designing and deploying serverless functions to Cloudflare's Edge
- Implementing edge-side data storage using KV, D1, or Durable Objects
- Optimizing application latency by moving logic to the edge
- Building full-stack apps with Cloudflare Pages and Workers
- Handling request/response modification, security headers, and edge-side caching

## Do not use this skill when

- The task is for traditional Node.js/Express apps run on servers
- Targeting AWS Lambda or Google Cloud Functions (use their respective skills)
- General frontend development that doesn't utilize edge features

## Instructions

1. **Wrangler Ecosystem**: Use `wrangler.toml` for configuration and `npx wrangler dev` for local testing.
2. **Fetch API**: Remember that Workers use the Web standard Fetch API, not Node.js globals.
3. **Bindings**: Define all bindings (KV, D1, secrets) in `wrangler.toml` and access them through the `env` parameter in the `fetch` handler.
4. **Cold Starts**: Workers have 0ms cold starts, but keep the bundle size small to stay within the 1MB limit for the free tier.
5. **Durable Objects**: Use Durable Objects for stateful coordination and high-concurrency needs.
6. **Error Handling**: Use `waitUntil()` for non-blocking asynchronous tasks (logging, analytics) that should run after the response is sent.

## Examples

### Example 1: Basic Worker with KV Binding

```typescript
export interface Env {
  MY_KV_NAMESPACE: KVNamespace;
}

export default {
  async fetch(
    request: Request,
    env: Env,
    ctx: ExecutionContext,
  ): Promise<Response> {
    const value = await env.MY_KV_NAMESPACE.get("my-key");
    if (!value) {
      return new Response("Not Found", { status: 404 });
    }
    return new Response(`Stored Value: ${value}`);
  },
};
```

### Example 2: Edge Response Modification

```javascript
export default {
  async fetch(request, env, ctx) {
    const response = await fetch(request);
    const newResponse = new Response(response.body, response);

    // Add security headers at the edge
    newResponse.headers.set("X-Content-Type-Options", "nosniff");
    newResponse.headers.set(
      "Content-Security-Policy",
      "upgrade-insecure-requests",
    );

    return newResponse;
  },
};
```

## Best Practices

- ✅ **Do:** Use `env.VAR_NAME` for secrets and environment variables.
- ✅ **Do:** Use `Response.redirect()` for clean edge-side redirects.
- ✅ **Do:** Use `wrangler tail` for live production debugging.
- ❌ **Don't:** Import large libraries; Workers have limited memory and CPU time.
- ❌ **Don't:** Use Node.js specific libraries (like `fs`, `path`) unless using Node.js compatibility mode.

## Troubleshooting

**Problem:** Request exceeded CPU time limit.
**Solution:** Optimize loops, reduce the number of await calls, and move synchronous heavy lifting out of the request/response path. Use `ctx.waitUntil()` for tasks that don't block the response.

Related Skills

nestjs-expert

31392
from sickn33/antigravity-awesome-skills

You are an expert in Nest.js with deep knowledge of enterprise-grade Node.js application architecture, dependency injection patterns, decorators, middleware, guards, interceptors, pipes, testing strategies, database integration, and authentication systems.

Frameworks & LibrariesClaude

n8n-validation-expert

31392
from sickn33/antigravity-awesome-skills

Expert guide for interpreting and fixing n8n validation errors.

Workflow AutomationClaude

n8n-mcp-tools-expert

31392
from sickn33/antigravity-awesome-skills

Expert guide for using n8n-mcp MCP tools effectively. Use when searching for nodes, validating configurations, accessing templates, managing workflows, or using any n8n-mcp tool. Provides tool selection guidance, parameter formats, and common patterns.

Workflow AutomationClaude

mermaid-expert

31392
from sickn33/antigravity-awesome-skills

Create Mermaid diagrams for flowcharts, sequences, ERDs, and architectures. Masters syntax for all diagram types and styling.

Developer ToolsClaude

local-llm-expert

31392
from sickn33/antigravity-awesome-skills

Master local LLM inference, model selection, VRAM optimization, and local deployment using Ollama, llama.cpp, vLLM, and LM Studio. Expert in quantization formats (GGUF, EXL2) and local AI privacy.

Local LLM Development & OptimizationClaude

laravel-expert

31392
from sickn33/antigravity-awesome-skills

Senior Laravel Engineer role for production-grade, maintainable, and idiomatic Laravel solutions. Focuses on clean architecture, security, performance, and modern standards (Laravel 10/11+).

Coding & DevelopmentClaude

kotlin-coroutines-expert

31392
from sickn33/antigravity-awesome-skills

Expert patterns for Kotlin Coroutines and Flow, covering structured concurrency, error handling, and testing.

Knowledge & InformationClaude

flutter-expert

31392
from sickn33/antigravity-awesome-skills

Master Flutter development with Dart 3, advanced widgets, and multi-platform deployment.

Text AnalysisClaude

dwarf-expert

31392
from sickn33/antigravity-awesome-skills

Provides expertise for analyzing DWARF debug files and understanding the DWARF debug format/standard (v3-v5). Triggers when understanding DWARF information, interacting with DWARF files, answering DWARF-related questions, or working with code that parses DWARF data.

Developer ToolsClaude

drizzle-orm-expert

31392
from sickn33/antigravity-awesome-skills

Expert in Drizzle ORM for TypeScript — schema design, relational queries, migrations, and serverless database integration. Use when building type-safe database layers with Drizzle.

Developer ToolsClaude

docker-expert

31392
from sickn33/antigravity-awesome-skills

You are an advanced Docker containerization expert with comprehensive, practical knowledge of container optimization, security hardening, multi-stage builds, orchestration patterns, and production deployment strategies based on current industry best practices.

DevOps & InfrastructureClaude

bevy-ecs-expert

31392
from sickn33/antigravity-awesome-skills

Master Bevy's Entity Component System (ECS) in Rust, covering Systems, Queries, Resources, and parallel scheduling.

Game DevelopmentClaude