Skip to content

Cloudflare Hono Template

The Cloudflare Hono template is an edge-first API framework optimized for globally distributed, high-performance applications. It leverages Cloudflare Workers for serverless execution at the edge.

Overview

  • Framework: Hono - Ultrafast web framework
  • Runtime: Cloudflare Workers (V8 Isolates)
  • Language: TypeScript with strict mode
  • Database: D1 (SQLite), KV (Key-Value), R2 (Object Storage)
  • Caching: Cache API, KV namespaces
  • Real-time: Durable Objects, WebSockets
  • Deployment: Cloudflare Workers

Architecture

Project Structure

my-api/
├── src/
│   ├── routes/              # API route handlers
│   ├── middleware/          # Custom middleware
│   ├── services/           # Business logic
│   ├── lib/               # Utilities
│   └── index.ts           # Worker entry point
├── migrations/             # D1 database migrations
├── wrangler.toml          # Cloudflare configuration
├── CLAUDE.md              # Project memory
└── .orchestre/            # Orchestre configuration

Key Features

  1. Edge Performance: Sub-50ms response times globally
  2. Auto-scaling: Handles 0 to millions of requests
  3. Built-in Storage: D1, KV, R2, Durable Objects
  4. Security: Built-in DDoS protection, rate limiting
  5. WebSocket Support: Real-time communication
  6. Cost Effective: Pay only for actual usage

Edge-Native Intelligence

When working with Cloudflare projects, Orchestre's prompts understand the unique constraints and opportunities of edge computing:

Edge Computing Patterns

  • Global Distribution: Automatic awareness of multi-region deployment patterns
  • Latency Optimization: Understanding of edge proximity benefits
  • Resource Constraints: Knowledge of Worker CPU and memory limits
  • Stateless Design: Patterns for distributed state management

Cloudflare Platform Features

  • Storage Systems: Intelligent use of D1, KV, R2, and Durable Objects
  • Caching Strategies: Optimal Cache API and CDN utilization
  • Security Features: Built-in DDoS protection and firewall rules
  • Worker Limits: Automatic consideration of subrequest and duration limits

Adaptive Behaviors

When building features, Orchestre:

  1. Analyzes Constraints: Understands Worker limitations and optimizes accordingly
  2. Suggests Storage: Recommends appropriate storage for your use case
  3. Optimizes Performance: Implements edge-specific optimizations
  4. Handles State: Manages distributed state with Durable Objects when needed

For example, implementing a real-time feature will:

  • Recognize WebSocket needs and Durable Object coordination
  • Understand connection limits and scaling patterns
  • Implement proper error handling for edge environments
  • Optimize for global distribution
  • Handle connection state persistence

Common Workflows

1. Building Edge APIs

When creating APIs with Cloudflare, Orchestre helps you:

  • Design for Scale: Plan architecture that handles global traffic
  • Optimize Routes: Implement efficient request handling
  • Manage State: Choose appropriate storage for different data types
  • Secure Endpoints: Apply edge-native security patterns

The system understands Cloudflare's platform capabilities and guides you toward optimal implementations.

2. Real-time Applications

For real-time features, prompts automatically consider:

  • WebSocket Management: Handling connections at scale
  • Durable Objects: Coordinating state across regions
  • Message Routing: Efficient pub/sub patterns
  • Failover Strategies: Handling edge node failures

Orchestre adapts its suggestions based on your specific real-time requirements and scale needs.

3. Global Distribution

When building globally distributed systems, the intelligence:

  • Optimizes Latency: Suggests region-aware patterns
  • Handles Replication: Implements eventual consistency
  • Manages Conflicts: Provides resolution strategies
  • Monitors Performance: Tracks edge-specific metrics

The prompts understand the complexities of edge distribution and guide you through implementation.

Intelligent Pattern Application

Orchestre recognizes and implements edge-optimized patterns:

Security at the Edge

Automatic understanding of:

  • JWT validation without external calls
  • API key management in KV stores
  • Rate limiting with Durable Objects
  • DDoS protection strategies
  • Geographic access controls

Performance Patterns

Intelligent application of:

  • Cache API for static content
  • KV for session management
  • Smart cache invalidation
  • Request coalescing
  • Early returns for errors

Distributed State

Built-in knowledge of:

  • Durable Object coordination
  • Eventually consistent patterns
  • Conflict-free replicated data types
  • WebSocket state management
  • Cross-region synchronization

Resource Optimization

Automatic consideration of:

  • CPU time limits (10-50ms)
  • Memory constraints
  • Subrequest limits
  • Bundle size optimization
  • Cold start mitigation

When implementing features, Orchestre applies these patterns contextually, understanding when each approach is most appropriate for your specific use case.

Configuration

Wrangler Configuration

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

[env.production]
vars = { ENVIRONMENT = "production" }

[[kv_namespaces]]
binding = "CACHE"
id = "abc123"

[[d1_databases]]
binding = "DB"
database_name = "my-api-db"
database_id = "def456"

[[durable_objects.bindings]]
name = "RATE_LIMITER"
class_name = "RateLimiter"

Environment Variables

typescript
// Access in code
interface Env {
  DB: D1Database
  CACHE: KVNamespace
  JWT_SECRET: string
  RATE_LIMITER: DurableObjectNamespace
}

Development Experience

Edge-First Development

Orchestre enhances your Cloudflare development by:

  1. Understanding Constraints: Knows Worker limits and guides you within them
  2. Optimizing Performance: Suggests edge-specific optimizations automatically
  3. Managing Complexity: Handles Wrangler configuration and deployment intricacies
  4. Testing Strategies: Implements appropriate testing for edge environments

Adaptive Guidance

The system adjusts based on:

  • API Complexity: Simple endpoints vs. complex orchestration
  • Scale Requirements: Hobby project vs. enterprise traffic
  • Storage Needs: Choosing between D1, KV, R2, and Durable Objects
  • Geographic Distribution: Single region vs. global deployment

Platform Integration

As you develop, Orchestre:

  • Configures Wrangler: Sets up bindings and environments properly
  • Manages Secrets: Handles environment variables securely
  • Optimizes Builds: Minimizes bundle size for faster cold starts
  • Monitors Limits: Warns about approaching platform constraints

Best Practices Recognition

Orchestre automatically implements Cloudflare best practices:

Edge Optimization

Intelligent application of:

  • Bundle size management
  • Tree shaking strategies
  • Dynamic imports for optional features
  • Minimal dependencies
  • Native API preferences

Performance First

Automatic implementation of:

  • Streaming responses for large data
  • Early returns for validation
  • Parallel subrequests when possible
  • Efficient error handling
  • Cold start optimization

Security Patterns

Built-in awareness of:

  • Edge-side validation
  • Cloudflare security features
  • CORS configuration
  • Rate limiting strategies
  • Input sanitization

Platform Features

Optimal use of:

  • Cache API for performance
  • KV for distributed state
  • D1 for relational data
  • R2 for object storage
  • Durable Objects for coordination

These practices are applied intelligently - Orchestre understands your specific use case and implements the most appropriate patterns without explicit instruction.

Edge Computing Patterns

Global Data Replication

typescript
// Replicate data across regions
export const replicateData = async (c: Context) => {
  const data = await c.req.json()
  
  // Write to primary region
  await c.env.DB.prepare('INSERT INTO ...').bind(data).run()
  
  // Replicate to other regions asynchronously
  c.executionCtx.waitUntil(
    Promise.all([
      replicateToRegion('eu', data),
      replicateToRegion('asia', data)
    ])
  )
}

Edge-side Rendering

typescript
// Generate HTML at the edge
export const renderPage = async (c: Context) => {
  const data = await fetchData(c)
  
  return c.html(`
    <html>
      <body>
        <h1>${data.title}</h1>
        <p>${data.content}</p>
      </body>
    </html>
  `)
}

Troubleshooting

Common Issues

  1. Worker size limits

    • Keep bundle under 10MB
    • Use code splitting
    • Minimize dependencies
  2. CPU time limits

    • Optimize algorithms
    • Use streaming responses
    • Offload to Durable Objects
  3. Subrequest limits

    • Batch API calls
    • Use KV for caching
    • Implement request coalescing

Getting Help

  • Check Edge Patterns
  • Run /suggest-improvements --edge
  • Use /review --performance

Getting Started

When you begin with Cloudflare, Orchestre helps you:

  1. Understand Edge Computing: Learn the unique aspects of Worker development
  2. Design for Scale: Plan architecture that leverages global distribution
  3. Implement Efficiently: Build with edge-optimized patterns
  4. Monitor Performance: Track metrics specific to edge environments
  5. Deploy Globally: Manage multi-region deployments confidently

The intelligence adapts to your edge computing experience - providing foundational knowledge for beginners while offering advanced optimization strategies for experienced developers.

Ready to build at the edge? Orchestre will guide you through the unique challenges and opportunities of Cloudflare Workers, ensuring you build performant, globally distributed applications.

Built with ❤️ for the AI Coding community, by Praney Behl