edge-patterns-advanced

Advanced Edge Computing patterns — streaming responses (TransformStream, Server-Sent Events), edge caching (Cache API, stale-while-revalidate), Miniflare testing, and common edge runtime mistakes (Node.js APIs, large npm packages, synchronous computation).

8 stars

Best use case

edge-patterns-advanced is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Advanced Edge Computing patterns — streaming responses (TransformStream, Server-Sent Events), edge caching (Cache API, stale-while-revalidate), Miniflare testing, and common edge runtime mistakes (Node.js APIs, large npm packages, synchronous computation).

Teams using edge-patterns-advanced should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/edge-patterns-advanced/SKILL.md --create-dirs "https://raw.githubusercontent.com/marvinrichter/clarc/main/skills/edge-patterns-advanced/SKILL.md"

Manual Installation

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

How edge-patterns-advanced Compares

Feature / Agentedge-patterns-advancedStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Advanced Edge Computing patterns — streaming responses (TransformStream, Server-Sent Events), edge caching (Cache API, stale-while-revalidate), Miniflare testing, and common edge runtime mistakes (Node.js APIs, large npm packages, synchronous computation).

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.

SKILL.md Source

# Edge Patterns — Advanced

This skill extends `edge-patterns` with streaming, caching, testing, and anti-patterns. Load `edge-patterns` first.

## When to Activate

- Streaming large responses through a Cloudflare Worker
- Implementing edge caching with stale-while-revalidate
- Testing Workers locally with Miniflare
- Debugging "not supported in edge runtime" errors for Node.js API usage

---

## Streaming Responses

```typescript
// Cloudflare Workers — streaming from a slow upstream
export default {
  async fetch(request: Request): Promise<Response> {
    const upstream = await fetch('https://slow-api.example.com/data');

    // Transform stream (uppercase each chunk)
    const { readable, writable } = new TransformStream({
      transform(chunk, controller) {
        const text = new TextDecoder().decode(chunk);
        controller.enqueue(new TextEncoder().encode(text.toUpperCase()));
      },
    });

    upstream.body!.pipeTo(writable);

    return new Response(readable, {
      headers: {
        'Content-Type': 'text/plain',
        'Transfer-Encoding': 'chunked',
      },
    });
  },
};

// Server-Sent Events
function* generateEvents() {
  for (let i = 0; i < 10; i++) {
    yield `data: ${JSON.stringify({ count: i })}\n\n`;
  }
}

export default {
  fetch(): Response {
    const encoder = new TextEncoder();
    const stream = new ReadableStream({
      async start(controller) {
        for (const event of generateEvents()) {
          controller.enqueue(encoder.encode(event));
          await new Promise(r => setTimeout(r, 1000));
        }
        controller.close();
      },
    });

    return new Response(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
      },
    });
  },
};
```

---

## Edge Caching

```typescript
// Cloudflare Cache API
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const cache = caches.default;

    // Cache key — can be different from request URL
    const cacheKey = new Request(request.url, { method: 'GET' });

    // Check cache
    const cached = await cache.match(cacheKey);
    if (cached) {
      return new Response(cached.body, {
        ...cached,
        headers: { ...cached.headers, 'X-Cache': 'HIT' },
      });
    }

    // Fetch and cache
    const response = await fetch(request);
    const toCache = new Response(response.body, response);
    toCache.headers.set('Cache-Control', 'public, max-age=3600');
    toCache.headers.set('X-Cache', 'MISS');

    // Store in background (don't block response)
    ctx.waitUntil(cache.put(cacheKey, toCache.clone()));

    return toCache;
  },
};
```

```typescript
// Stale-While-Revalidate pattern
async function swr(
  cacheKey: Request,
  fetchFn: () => Promise<Response>,
  maxAge: number,
  staleAge: number,
  ctx: ExecutionContext
): Promise<Response> {
  const cache = caches.default;
  const cached = await cache.match(cacheKey);

  if (cached) {
    const age = parseInt(cached.headers.get('X-Cache-Age') ?? '0');
    if (age < maxAge) return cached;  // Fresh

    // Stale — return cached but revalidate in background
    if (age < staleAge) {
      ctx.waitUntil(
        fetchFn().then(fresh => {
          fresh.headers.set('X-Cache-Age', '0');
          return cache.put(cacheKey, fresh);
        })
      );
      return cached;
    }
  }

  // Miss or expired
  const fresh = await fetchFn();
  const toCache = new Response(fresh.body, fresh);
  toCache.headers.set('X-Cache-Age', '0');
  ctx.waitUntil(cache.put(cacheKey, toCache.clone()));
  return toCache;
}
```

---

## Testing — Miniflare

```typescript
// test/worker.test.ts
import { Miniflare } from 'miniflare';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';

describe('Worker', () => {
  let mf: Miniflare;

  beforeAll(async () => {
    mf = new Miniflare({
      scriptPath: './src/index.ts',
      kvNamespaces: ['MY_KV'],
      d1Databases: ['MY_DB'],
      bindings: { MY_SECRET: 'test-secret' },
    });
  });

  afterAll(() => mf.dispose());

  it('returns health check', async () => {
    const res = await mf.dispatchFetch('http://localhost/api/health');
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body).toEqual({ status: 'ok' });
  });

  it('reads from KV', async () => {
    const kv = await mf.getKVNamespace('MY_KV');
    await kv.put('user:1', JSON.stringify({ name: 'Alice' }));

    const res = await mf.dispatchFetch('http://localhost/api/user/1');
    expect(res.status).toBe(200);
  });
});
```

```bash
# Install
npm install -D miniflare vitest

# Run tests
vitest run
```

---

## Common Mistakes

```typescript
// WRONG: Node.js API in Edge Runtime
import { readFileSync } from 'fs';  // Not available

// CORRECT: Use fetch to load static assets
const data = await fetch(new URL('./data.json', import.meta.url)).then(r => r.json());

// WRONG: Large npm package (pulls in Node.js dependencies)
import moment from 'moment';  // Too large, Node.js APIs

// CORRECT: Web-compatible alternative
import { format } from 'date-fns/format';  // Pure JS, tree-shakeable

// WRONG: Synchronous heavy computation blocking isolate
export default {
  fetch(): Response {
    const result = heavySync(largeData);  // Hits CPU limit
    return Response.json(result);
  }
}

// CORRECT: Stream or offload to Durable Object / Queue
```

## Reference

- `edge-patterns` — runtime constraints, Cloudflare Workers (KV/D1/R2/Durable Objects), Vercel Edge Middleware, Deno Deploy
- `serverless-patterns` — cold starts, Step Functions, Lambda Powertools, idempotency
- `wasm-patterns` — run Rust WASM in Cloudflare Workers

Related Skills

zero-trust-patterns

8
from marvinrichter/clarc

Zero-Trust security patterns — mTLS between microservices (Istio/SPIFFE), SPIRE workload identity, OPA/Envoy authorization, NetworkPolicy default-deny-all, short-lived credentials, service mesh security, and Kubernetes RBAC hardening.

webrtc-patterns

8
from marvinrichter/clarc

WebRTC patterns — peer connection setup, ICE/STUN/TURN configuration, signaling server design, SFU vs mesh topology, screen sharing, media track management, and reconnect/ICE restart handling.

webhook-patterns

8
from marvinrichter/clarc

Webhook patterns for receiving, verifying (HMAC), and idempotently processing third-party events. Covers Stripe, GitHub, and generic webhook patterns, delivery guarantees, retry handling, and testing.

wasm-patterns

8
from marvinrichter/clarc

WebAssembly patterns: wasm-pack, wasm-bindgen (JS↔Wasm interop), WASI, Component Model, wasm-opt, Rust-to-WASM compilation, JS integration (web workers, streaming instantiation), and production deployment (CDN, Content-Type headers).

ux-micro-patterns

8
from marvinrichter/clarc

UX micro-patterns for every product state: Empty States, Loading States (skeleton screens, spinners, optimistic UI), Error States, Success States, Confirmation Dialogs, Onboarding Flows, and Progressive Disclosure. These patterns apply to every feature — done wrong, they're the biggest source of user confusion.

typescript-patterns

8
from marvinrichter/clarc

TypeScript patterns — type system best practices, strict mode, utility types, generics, discriminated unions, error handling with Result types, and module organization. Core patterns for production TypeScript.

typescript-patterns-advanced

8
from marvinrichter/clarc

Advanced TypeScript — mapped types, template literal types, conditional types, infer, type guards, decorators, async patterns, testing with Vitest/Jest, and performance. Extends typescript-patterns.

typescript-monorepo-patterns

8
from marvinrichter/clarc

TypeScript monorepo patterns with Turborepo + pnpm workspaces. Covers package structure, shared configs, task pipeline caching, build orchestration, and publishing strategy.

terraform-patterns

8
from marvinrichter/clarc

Infrastructure as Code with Terraform — project structure, remote state, modules, workspace strategy, AWS/GCP patterns, CI/CD integration, and security hardening. The standard for managing production infrastructure.

tdd-workflow-advanced

8
from marvinrichter/clarc

TDD anti-patterns — writing code before tests, testing implementation details instead of behavior, using waitForTimeout as a sync strategy, chaining tests that share state, mocking the system under test instead of its dependencies.

swiftui-patterns

8
from marvinrichter/clarc

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

swift-patterns

8
from marvinrichter/clarc

Core Swift patterns — value vs reference types, protocols, generics, optionals, Result, error handling, Codable, and module organization. Foundation for all Swift development.