Deploying to Cloudflare Workers
Deploy your own ERA Agent instance on Cloudflare Workers to get a dedicated, customizable code execution platform running on the global edge network.
Why Deploy Your Own?
Section titled “Why Deploy Your Own?”While you can use the public ERA Agent at https://anewera.dev, deploying your own instance gives you:
- 🔐 Private Access - Control who can use your instance
- ⚙️ Custom Configuration - Adjust limits, timeouts, and settings
- 📊 Usage Monitoring - Track your own metrics and logs
- 🎯 Custom Domain - Use your own domain name
- 💰 Cost Control - Optimize for your usage patterns
- 🔒 Data Privacy - Keep data in your Cloudflare account
Prerequisites
Section titled “Prerequisites”- Cloudflare Account - Sign up free
- Node.js 18+ - For running Wrangler CLI
- npm or yarn - Package manager
- Git - For cloning the repository
Quick Deployment
Section titled “Quick Deployment”1. Clone the Repository
Section titled “1. Clone the Repository”git clone https://github.com/yourusername/era-agentcd era-agent/cloudflare2. Install Dependencies
Section titled “2. Install Dependencies”npm install3. Configure Wrangler
Section titled “3. Configure Wrangler”Login to Cloudflare:
npx wrangler loginThis will open a browser for you to authenticate.
4. Deploy
Section titled “4. Deploy”npx wrangler deployThat’s it! Your ERA Agent is now deployed at:
https://your-worker-name.workers.devConfiguration
Section titled “Configuration”Worker Settings
Section titled “Worker Settings”Edit wrangler.toml to customize your deployment:
name = "my-era-agent"main = "src/index.ts"compatibility_date = "2024-10-01"node_compat = true
# Environment variables[vars]AGENT_LOG_LEVEL = "info"
# Durable Objects[[durable_objects.bindings]]name = "ERA_AGENT"class_name = "EraAgent"
[[durable_objects.bindings]]name = "SESSIONS"class_name = "SessionDO"
# R2 Storage (for persistent files)[[r2_buckets]]binding = "SESSIONS_BUCKET"bucket_name = "era-sessions"
# Container runtime bindings[container_runtime]# Configure container executioninstance_type = "standard"Custom Domain
Section titled “Custom Domain”Use your own domain instead of *.workers.dev:
# Add route in wrangler.toml[routes]pattern = "era.yourdomain.com"zone_name = "yourdomain.com"
# Deploynpx wrangler deployResource Limits
Section titled “Resource Limits”Adjust execution limits in src/index.ts:
// Default limitsconst DEFAULT_TIMEOUT = 30; // secondsconst MAX_TIMEOUT = 300; // 5 minutesconst DEFAULT_MEMORY = 256; // MiBconst MAX_MEMORY = 2048; // 2 GBEnvironment Variables
Section titled “Environment Variables”Set secrets for production:
# Set API key (optional)npx wrangler secret put API_KEY
# Set custom limitsnpx wrangler secret put MAX_EXECUTION_TIME
# Deploy with new secretsnpx wrangler deployAuthentication
Section titled “Authentication”Add authentication to your deployment to restrict access.
Option 1: API Key Authentication
Section titled “Option 1: API Key Authentication”Add API key check in src/index.ts:
// Before handling requestsconst apiKey = request.headers.get('Authorization');const expectedKey = env.API_KEY; // Set via wrangler secret
if (apiKey !== `Bearer ${expectedKey}`) { return new Response('Unauthorized', { status: 401 });}Set the API key:
npx wrangler secret put API_KEY# Enter your secret key when prompted
npx wrangler deployUse it:
curl -X POST https://your-worker.workers.dev/api/execute \ -H "Authorization: Bearer your-secret-key" \ -H "Content-Type: application/json" \ -d '{"language":"python","code":"print(\"Hello!\")"}'Option 2: Cloudflare Access
Section titled “Option 2: Cloudflare Access”Protect your Worker with Cloudflare Access:
- Go to Cloudflare Dashboard → Zero Trust → Access
- Create new application
- Add your Worker URL:
https://your-worker.workers.dev - Configure authentication rules (email, SSO, etc.)
- Users must authenticate before accessing
Option 3: IP Allowlist
Section titled “Option 3: IP Allowlist”Restrict access by IP address:
const ALLOWED_IPS = ['203.0.113.0', '198.51.100.0'];
if (!ALLOWED_IPS.includes(request.headers.get('CF-Connecting-IP'))) { return new Response('Forbidden', { status: 403 });}Storage Setup
Section titled “Storage Setup”R2 Bucket Creation
Section titled “R2 Bucket Creation”ERA Agent uses R2 for persistent file storage:
# Create R2 bucketnpx wrangler r2 bucket create era-sessions
# Verifynpx wrangler r2 bucket listUpdate wrangler.toml:
[[r2_buckets]]binding = "SESSIONS_BUCKET"bucket_name = "era-sessions"Durable Objects Setup
Section titled “Durable Objects Setup”Durable Objects are automatically created. To manually manage:
# List Durable Objectsnpx wrangler durable-objects list
# Get specific instancenpx wrangler durable-objects get <id>Monitoring & Logs
Section titled “Monitoring & Logs”Real-Time Logs
Section titled “Real-Time Logs”View live logs from your Worker:
# Tail logsnpx wrangler tail
# Filter logsnpx wrangler tail --format json
# Filter by statusnpx wrangler tail --status errorAnalytics Dashboard
Section titled “Analytics Dashboard”View analytics in Cloudflare Dashboard:
- Go to Workers & Pages → Your Worker
- Click “Metrics” tab
- View:
- Requests per second
- Success rate
- CPU time
- Duration metrics
Custom Logging
Section titled “Custom Logging”Add structured logging:
console.log(JSON.stringify({ level: 'info', message: 'Code execution started', session_id: session.id, language: language, timestamp: new Date().toISOString()}));Performance Optimization
Section titled “Performance Optimization”Caching
Section titled “Caching”Enable caching for static resources:
// Cache responses for repeated requestsconst cache = caches.default;const cacheKey = new Request(url, request);let response = await cache.match(cacheKey);
if (!response) { response = await handleRequest(request); ctx.waitUntil(cache.put(cacheKey, response.clone()));}Cold Start Optimization
Section titled “Cold Start Optimization”Minimize cold start time:
// Preload commonly used modulesimport { loadPythonRuntime } from './runtimes';
// Keep connections warmsetInterval(() => { // Ping Durable Object}, 50000); // 50 secondsResource Limits
Section titled “Resource Limits”Optimize for your workload:
[container_runtime]# Standard tier: 1 CPU, 256 MBinstance_type = "standard"
# Or upgrade for more resources# instance_type = "standard-2" # 2 CPU, 512 MBCost Management
Section titled “Cost Management”Cloudflare Workers Pricing
Section titled “Cloudflare Workers Pricing”Free Tier:
- 100,000 requests/day
- 10 ms CPU time per invocation
Paid Plan ($5/month):
- 10 million requests included
- Additional: $0.50/million requests
- CPU time: $0.02/million CPU ms
R2 Storage Pricing
Section titled “R2 Storage Pricing”Free Tier:
- 10 GB storage
- 1 million Class A operations/month
- 10 million Class B operations/month
Beyond Free:
- Storage: $0.015/GB/month
- Class A ops: $4.50/million
- Class B ops: $0.36/million
Optimizing Costs
Section titled “Optimizing Costs”// 1. Set reasonable timeoutsconst MAX_TIMEOUT = 30; // Don't allow excessive CPU time
// 2. Clean up sessions automaticallyconst SESSION_TTL = 30 * 60 * 1000; // 30 minutes
// 3. Limit file storageconst MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MBProduction Checklist
Section titled “Production Checklist”Before going to production, ensure:
Security
Section titled “Security”- Add authentication (API keys, Cloudflare Access, or IP allowlist)
- Set rate limiting
- Configure CORS appropriately
- Rotate secrets regularly
- Enable HTTPS only
Configuration
Section titled “Configuration”- Set appropriate resource limits
- Configure timeout values
- Set up error monitoring
- Configure logging level
- Set up alerts
Storage
Section titled “Storage”- Create R2 bucket for persistent files
- Configure Durable Objects
- Set up backup strategy
- Plan for data retention
Monitoring
Section titled “Monitoring”- Enable Cloudflare Analytics
- Set up log aggregation
- Configure alerts for errors
- Monitor costs
- Track usage patterns
Deployment Strategies
Section titled “Deployment Strategies”Development → Staging → Production
Section titled “Development → Staging → Production”Use Wrangler environments:
[env.staging]name = "era-agent-staging"vars = { AGENT_LOG_LEVEL = "debug" }
[env.production]name = "era-agent-production"vars = { AGENT_LOG_LEVEL = "warn" }Deploy:
# Stagingnpx wrangler deploy --env staging
# Productionnpx wrangler deploy --env productionCI/CD with GitHub Actions
Section titled “CI/CD with GitHub Actions”name: Deploy to Cloudflare
on: push: branches: [main]
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18'
- name: Install dependencies run: npm install working-directory: ./cloudflare
- name: Deploy to Cloudflare run: npx wrangler deploy working-directory: ./cloudflare env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}Blue-Green Deployments
Section titled “Blue-Green Deployments”# Deploy new version to stagingnpx wrangler deploy --env staging
# Test thoroughlycurl https://era-agent-staging.workers.dev/health
# Promote to productionnpx wrangler deploy --env productionTroubleshooting
Section titled “Troubleshooting””Exceeded CPU time”
Section titled “”Exceeded CPU time””Problem: Code execution taking too long
Solutions:
- Reduce
MAX_TIMEOUTsetting - Upgrade to higher tier Worker
- Optimize code execution
- Add execution time monitoring
”Durable Object not found”
Section titled “”Durable Object not found””Problem: Durable Object not initialized
Solutions:
# Redeploy to initializenpx wrangler deploy
# Check Durable Object bindingsnpx wrangler durable-objects list“R2 bucket not accessible”
Section titled ““R2 bucket not accessible””Problem: R2 bucket not created or bound
Solutions:
# Create bucketnpx wrangler r2 bucket create era-sessions
# Verify binding in wrangler.toml[[r2_buckets]]binding = "SESSIONS_BUCKET"bucket_name = "era-sessions"
# Redeploynpx wrangler deployDeployment Errors
Section titled “Deployment Errors”Check Wrangler version:
npx wrangler --versionnpm install -g wrangler@latestCheck authentication:
npx wrangler whoaminpx wrangler loginClear cache:
rm -rf node_modulesnpm installnpx wrangler deployNext Steps
Section titled “Next Steps”- API Reference - Complete API documentation
- MCP Remote Server - Use as remote MCP
- Session Management - Advanced session features
- Cloudflare Docs - Workers documentation