Skip to content

Cloudflare Frontend Migration ​

Overview ​

This document describes the frontend API migration to support Cloudflare Workers, enabling gradual rollout and A/B testing between traditional Node.js backend and Cloudflare Workers.

Architecture ​

Dual-Mode API Client ​

The frontend now supports two deployment modes:

  1. Traditional Mode: Connects to Node.js/Hono backend at localhost:4000
  2. Cloudflare Mode: Connects to Cloudflare Workers at configured Worker URLs

Configuration System ​

All configuration is managed through environment variables and feature flags in /packages/frontend/src/config/api.config.ts.

Environment Variables ​

New Variables (Added) ​

bash
# Enable Cloudflare Workers (master toggle)
VITE_CLOUDFLARE_WORKERS_ENABLED=false

# Cloudflare Workers API base URL
VITE_CLOUDFLARE_API_URL=https://api.monotask.workers.dev

# Cloudflare WebSocket URL (Durable Objects)
VITE_CLOUDFLARE_WS_URL=wss://ws.monotask.workers.dev

# Cloudflare deployment environment
VITE_CLOUDFLARE_ENV=dev

# Gradual rollout percentage (0-100)
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=0

# Feature-specific flags (comma-separated)
# Options: auth,tasks,projects,github,dashboard,workers,queue,metrics,all
VITE_CLOUDFLARE_FEATURE_FLAGS=

Existing Variables (Unchanged) ​

bash
VITE_API_URL=http://localhost:4000
VITE_WS_URL=ws://localhost:4000
VITE_ENV=development

Feature Flags ​

Granular Migration ​

The system supports granular feature migration through the VITE_CLOUDFLARE_FEATURE_FLAGS variable:

bash
# Migrate only authentication to Workers
VITE_CLOUDFLARE_FEATURE_FLAGS=auth

# Migrate multiple features
VITE_CLOUDFLARE_FEATURE_FLAGS=auth,tasks,projects

# Migrate everything
VITE_CLOUDFLARE_FEATURE_FLAGS=all

Available Features ​

  • auth - Authentication endpoints
  • tasks - Task management endpoints
  • projects - Project management endpoints
  • github - GitHub integration endpoints
  • dashboard - Dashboard metrics endpoints
  • workers - Worker management endpoints
  • queue - Automation queue endpoints
  • metrics - Performance metrics endpoints
  • all - All endpoints (override)

Rollout Strategy ​

Percentage-Based Rollout ​

The VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE variable controls what percentage of users see Cloudflare Workers:

bash
# 0% - No users (testing only)
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=0

# 10% - Limited beta
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=10

# 50% - A/B testing
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=50

# 100% - Full migration
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=100

The system uses sessionStorage to maintain consistency - once a user is assigned to Cloudflare or traditional, they remain in that group for the session.

API Client Updates ​

Request Interceptors ​

The API client now includes Cloudflare-specific request interceptors:

  • Performance Tracking: Request timestamps for performance monitoring
  • Trace Headers: Debug headers for Cloudflare request tracing
  • Request IDs: Unique IDs for distributed tracing

Response Interceptors ​

Enhanced error handling for Cloudflare-specific errors:

  • Worker Timeouts (522, 524): Logged with Cloudflare Ray ID
  • Worker Errors (530): Specific Worker error logging
  • CORS Detection: Warns about potential CORS issues
  • Performance Metrics: Logs slow requests (>2s)

Example Error Response ​

javascript
{
  status: 522,
  deployment: 'cloudflare',
  cfRay: 'abc123-SFO',
  cfCacheStatus: 'MISS',
  message: 'Connection timed out'
}

WebSocket Updates ​

Durable Objects Support ​

The WebSocket hook now supports Cloudflare Durable Objects:

typescript
// Automatic URL detection
const ws = useWebSocket(['task.updated', 'worker.spawned'])

// Uses VITE_CLOUDFLARE_WS_URL when Cloudflare is enabled
// Falls back to VITE_WS_URL for traditional mode

Connection Logging ​

Enhanced logging shows deployment mode:

javascript
WebSocket connected {
  url: 'wss://ws.monotask.workers.dev',
  deployment: 'Cloudflare Durable Objects'
}

Migration Phases ​

Phase 1: Infrastructure (Complete) ​

  • ✅ Environment configuration
  • ✅ API client updates
  • ✅ Request/response interceptors
  • ✅ WebSocket URL routing
  • ✅ Feature flag system

Phase 2: Authentication (Issue #80) ​

  • Update GitHub OAuth flow for Workers
  • Token management in Worker KV
  • Session handling

Phase 3: Real-time Updates (Issue #78) ​

  • Durable Objects WebSocket client
  • Event subscription management
  • Reconnection logic

Phase 4: Feature Migration (Issues #79-86) ​

  • Sandbox management UI
  • Performance optimizations
  • Error boundaries
  • Offline support
  • Edge caching

Testing ​

Local Development ​

  1. Traditional Mode (Default)
bash
# .env
VITE_CLOUDFLARE_WORKERS_ENABLED=false
VITE_API_URL=http://localhost:4000
  1. Cloudflare Mode (Testing)
bash
# .env
VITE_CLOUDFLARE_WORKERS_ENABLED=true
VITE_CLOUDFLARE_API_URL=http://localhost:8787  # Local Wrangler
VITE_CLOUDFLARE_WS_URL=ws://localhost:8787

Feature Flag Testing ​

bash
# Test specific features with Cloudflare
VITE_CLOUDFLARE_WORKERS_ENABLED=true
VITE_CLOUDFLARE_FEATURE_FLAGS=auth,tasks

A/B Testing ​

bash
# 50/50 split between traditional and Cloudflare
VITE_CLOUDFLARE_WORKERS_ENABLED=true
VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE=50

Debugging ​

Development Console ​

The API configuration is logged on startup in development mode:

javascript
🔧 MonoTask API Configuration
  Environment: development
  Using Cloudflare: true
  Base URL: https://api.monotask.workers.dev
  WebSocket URL: wss://ws.monotask.workers.dev
  Rollout Percentage: 50%
  Feature Flags: auth, tasks
  Running on Cloudflare Pages: false

Request Tracing ​

In development with Cloudflare enabled, all requests include:

  • X-Trace-Request: true
  • X-Request-ID: [unique-id]
  • X-Request-Start: [timestamp]

Performance Monitoring ​

Slow requests (>2s) are automatically logged:

javascript
Slow API Request: {
  url: '/api/tasks',
  method: 'GET',
  duration: '3250ms',
  isCloudflare: true
}

Production Deployment ​

Cloudflare Pages ​

When deploying to Cloudflare Pages:

bash
# wrangler.toml
[env.production]
vars = {
  VITE_CLOUDFLARE_WORKERS_ENABLED = "true"
  VITE_CLOUDFLARE_API_URL = "https://api.monotask.workers.dev"
  VITE_CLOUDFLARE_WS_URL = "wss://ws.monotask.workers.dev"
  VITE_CLOUDFLARE_ENV = "production"
  VITE_CLOUDFLARE_ROLLOUT_PERCENTAGE = "100"
}

Traditional Deployment ​

Existing deployment unchanged:

bash
VITE_API_URL=https://api.monotask.com
VITE_WS_URL=wss://api.monotask.com

API Compatibility ​

Endpoint Mapping ​

All existing API endpoints work with both modes:

TraditionalCloudflare Worker
http://localhost:4000/api/taskshttps://api.monotask.workers.dev/api/tasks
ws://localhost:4000/wswss://ws.monotask.workers.dev

Request/Response Format ​

The request and response formats remain identical. Workers maintain compatibility with the existing Hono API.

Error Handling ​

Worker-Specific Errors ​

StatusMeaningHandling
522Connection timed outAutomatic retry with exponential backoff
524Timeout occurredLog error, show user message
530Worker errorLog full error context, fallback to traditional if configured

Fallback Strategy ​

Currently, no automatic fallback is implemented. Future enhancement:

typescript
// Proposed fallback logic
if (workerError && canFallback) {
  console.warn('Falling back to traditional API')
  useTraditionalApi()
}

Security Considerations ​

CORS ​

Workers must include appropriate CORS headers:

javascript
// Required in Worker response
headers: {
  'Access-Control-Allow-Origin': 'https://app.monotask.com',
  'Access-Control-Allow-Credentials': 'true'
}

Authentication ​

  • Session tokens work with both modes
  • Workers use KV storage for session management
  • Cookies remain the same format

Performance Benefits ​

Expected Improvements ​

  1. Lower Latency: ~50ms improvement from edge deployment
  2. Global Distribution: CDN-based API delivery
  3. Auto-scaling: No capacity planning needed
  4. Reduced Costs: Pay-per-request model

Monitoring ​

Track these metrics:

  • Request duration (P50, P95, P99)
  • Error rates by deployment mode
  • WebSocket connection stability
  • Cache hit rates (Workers KV)

Migration Checklist ​

Pre-Migration ​

  • [ ] Test all API endpoints with local Wrangler
  • [ ] Verify WebSocket connection to Durable Objects
  • [ ] Test authentication flow
  • [ ] Review error handling

During Migration ​

  • [ ] Start with 0% rollout (testing only)
  • [ ] Increase to 1% for canary testing
  • [ ] Monitor error rates and performance
  • [ ] Gradually increase to 10%, 25%, 50%
  • [ ] Full rollout at 100%

Post-Migration ​

  • [ ] Remove traditional backend (when appropriate)
  • [ ] Update documentation
  • [ ] Archive rollback procedures
  • [ ] Clean up feature flags

Troubleshooting ​

Common Issues ​

Issue: CORS errors with Workers

Solution: Verify Worker CORS configuration matches frontend domain

Issue: WebSocket fails to connect

Solution: Check Durable Objects binding and routing

Issue: Authentication breaks

Solution: Verify KV namespace bindings and session storage

Issue: Slow performance

Solution: Check Worker cold starts, add warming strategy

  • Track B (Workers): docs/TRACK_B_WORKERS.md
  • Track D (Testing): docs/TRACK_D_TESTING.md
  • Deployment: docs/CLOUDFLARE_DEPLOYMENT.md

Contacts ​

  • Frontend Lead: [Track C Agent]
  • Workers Lead: [Track B Agent]
  • Integration: [Foundation Track]

MonoKernel MonoTask Documentation