Production Deployment
Production Deployment
Section titled “Production Deployment”Complete guide to deploying ImageBot to production on Cloudflare’s edge infrastructure.
Prerequisites
Section titled “Prerequisites”- Cloudflare account (free tier works)
- Domain name (optional but recommended)
- Wrangler CLI installed (
npm install -g wrangler) - Git repository access
Deployment Architecture
Section titled “Deployment Architecture”┌─────────────────────────────────────────────┐│ Cloudflare Pages (Frontend) ││ https://your-site.pages.dev │└─────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────┐│ Cloudflare Worker (API Backend) ││ https://imagebot-worker.workers.dev │└─────────────────────────────────────────────┘ ↓ ┌───────────┬──────────┬─────────┐ │ D1 (DB) │ R2 │ AI │ │ SQLite │ Storage │ Models │ └───────────┴──────────┴─────────┘Step 1: Cloudflare Resources Setup
Section titled “Step 1: Cloudflare Resources Setup”1.1 Create D1 Database
Section titled “1.1 Create D1 Database”# Create production databasewrangler d1 create imagebot-db-prod
# Copy the database_id from output# Example output:# database_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"Update wrangler.toml:
[[d1_databases]]binding = "DB"database_name = "imagebot-db-prod"database_id = "your-database-id-here" # ← Paste your ID1.2 Create R2 Bucket
Section titled “1.2 Create R2 Bucket”# Create production storage bucketwrangler r2 bucket create imagebot-images-prod
# Verify creationwrangler r2 bucket listUpdate wrangler.toml:
[[r2_buckets]]binding = "IMAGES"bucket_name = "imagebot-images-prod"1.3 Configure Custom Domain for R2 (Optional)
Section titled “1.3 Configure Custom Domain for R2 (Optional)”# Add custom domain to R2 bucketwrangler r2 bucket domain add imagebot-images-prod --domain images.yourdomain.com
# Verify domainwrangler r2 bucket domain list imagebot-images-prodBenefits:
- SEO-friendly image URLs
- Brand consistency
- Better caching control
Step 2: Environment Secrets
Section titled “Step 2: Environment Secrets”Set production secrets using Wrangler:
# JWT Secret (generate strong random string)wrangler secret put JWT_SECRET# Paste: (output of: node -e "console.log(require('crypto').randomBytes(64).toString('hex'))")
# Stripe Keys (if using payment features)wrangler secret put STRIPE_SECRET_KEYwrangler secret put STRIPE_WEBHOOK_SECRET
# Email Service (MailerSend for notifications)wrangler secret put MAILERSEND_API_TOKEN
# GitHub OAuth (if using GitHub login)wrangler secret put GITHUB_CLIENT_IDwrangler secret put GITHUB_CLIENT_SECRETGenerate JWT Secret:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"Step 3: Database Migration
Section titled “Step 3: Database Migration”Apply all database schemas to production:
# Core schemawrangler d1 execute imagebot-db-prod --remote --file database/schema-init.sql
# Feature schemas (in order)wrangler d1 execute imagebot-db-prod --remote --file database/license-certificates-schema.sqlwrangler d1 execute imagebot-db-prod --remote --file database/multi-model-comparison-schema.sqlwrangler d1 execute imagebot-db-prod --remote --file database/api-keys-schema.sqlwrangler d1 execute imagebot-db-prod --remote --file database/teams-minimal.sqlwrangler d1 execute imagebot-db-prod --remote --file database/batch-schema.sqlwrangler d1 execute imagebot-db-prod --remote --file database/branding-schema.sqlwrangler d1 execute imagebot-db-prod --remote --file database/prompt-packs-schema.sqlVerify Database:
# Check table count (should be 41+)wrangler d1 execute imagebot-db-prod --remote --command "SELECT COUNT(*) as table_count FROM sqlite_master WHERE type='table'"
# List all tableswrangler d1 execute imagebot-db-prod --remote --command "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"Step 4: Deploy Worker API
Section titled “Step 4: Deploy Worker API”Critical: Deploy Worker BEFORE frontend to ensure API is available.
# Build and deploy Workernpm run worker:deploy
# Or with explicit environmentwrangler deploy
# Verify deploymentcurl https://imagebot-worker.your-subdomain.workers.dev/api/healthExpected Response:
{ "status": "ok", "timestamp": "2024-01-15T10:30:00Z", "database": "connected", "r2": "connected"}Configure Worker Custom Domain (Optional)
Section titled “Configure Worker Custom Domain (Optional)”# Add custom domain to Workerwrangler publish --routes "api.yourdomain.com/*"Update DNS:
- Type:
CNAME - Name:
api - Value:
imagebot-worker.your-subdomain.workers.dev - Proxy: Enabled (orange cloud)
Step 5: Deploy Frontend to Pages
Section titled “Step 5: Deploy Frontend to Pages”5.1 Build Production Frontend
Section titled “5.1 Build Production Frontend”Update .env.production:
PUBLIC_API_URL=https://imagebot-worker.your-subdomain.workers.dev# Or if using custom domain:# PUBLIC_API_URL=https://api.yourdomain.comBuild:
npm run build5.2 Deploy to Cloudflare Pages
Section titled “5.2 Deploy to Cloudflare Pages”# Deploy via Wranglerwrangler pages deploy dist --project-name=imagebot
# Or via Git integration (recommended)git push origin mainGit Integration Setup:
- Go to Cloudflare Dashboard → Pages
- Click “Create a project”
- Connect to GitHub repository
- Configure build settings:
- Build command:
npm run build - Build output directory:
dist - Environment variables: Add
PUBLIC_API_URL
- Build command:
5.3 Configure Custom Domain for Pages
Section titled “5.3 Configure Custom Domain for Pages”- Pages → Settings → Custom domains
- Click “Set up a custom domain”
- Enter your domain (e.g.,
app.yourdomain.com) - Update DNS:
- Type:
CNAME - Name:
app - Value:
imagebot.pages.dev - Proxy: Enabled
- Type:
Step 6: Production Configuration
Section titled “Step 6: Production Configuration”6.1 Update CORS Settings
Section titled “6.1 Update CORS Settings”In worker/index.ts, configure allowed origins:
const corsHeaders = { 'Access-Control-Allow-Origin': 'https://app.yourdomain.com', // Your Pages domain 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization',};6.2 Configure Rate Limiting
Section titled “6.2 Configure Rate Limiting”Update wrangler.toml:
[vars]RATE_LIMIT_PER_MINUTE = "100"RATE_LIMIT_BURST = "200"6.3 Enable Analytics
Section titled “6.3 Enable Analytics”Cloudflare automatically tracks:
- Request volume
- Response times
- Error rates
- Geographic distribution
View at: Dashboard → Workers → Analytics
Step 7: SSL/TLS Configuration
Section titled “Step 7: SSL/TLS Configuration”Cloudflare provides automatic SSL certificates:
- Dashboard → SSL/TLS → Overview
- Set encryption mode: Full (strict)
- Enable:
- Always Use HTTPS
- Automatic HTTPS Rewrites
- Minimum TLS Version: 1.2
Step 8: Performance Optimization
Section titled “Step 8: Performance Optimization”8.1 Enable Caching
Section titled “8.1 Enable Caching”Configure cache rules for R2 images:
# In wrangler.toml[env.production.routes]pattern = "*/generated/*"cache_ttl = 31536000 # 1 year8.2 Enable Argo Smart Routing (Optional)
Section titled “8.2 Enable Argo Smart Routing (Optional)”Reduces latency by up to 30%:
- Dashboard → Traffic → Argo
- Enable Argo Smart Routing
- Cost: $0.10 per GB
8.3 Configure Page Rules
Section titled “8.3 Configure Page Rules”Create page rules for static assets:
- Pattern:
app.yourdomain.com/*.js - Settings:
- Cache Level: Cache Everything
- Edge Cache TTL: 1 month
- Browser Cache TTL: 1 week
Step 9: Monitoring & Logging
Section titled “Step 9: Monitoring & Logging”9.1 Real-Time Logs
Section titled “9.1 Real-Time Logs”# Tail Worker logswrangler tail imagebot-worker
# Filter errors onlywrangler tail imagebot-worker --status error9.2 Set Up Alerts
Section titled “9.2 Set Up Alerts”Dashboard → Account → Notifications:
- Worker error rate threshold
- Worker CPU time exceeded
- R2 storage quota
- D1 request quota
9.3 Analytics Integration
Section titled “9.3 Analytics Integration”Add analytics to frontend:
export function trackEvent(event: string, properties?: Record<string, any>) { if (typeof window !== 'undefined' && window.gtag) { window.gtag('event', event, properties); }}Step 10: Backup & Disaster Recovery
Section titled “Step 10: Backup & Disaster Recovery”10.1 Database Backups
Section titled “10.1 Database Backups”# Export databasewrangler d1 export imagebot-db-prod --output backup-$(date +%Y%m%d).sql
# Automated backup script#!/bin/bashDATE=$(date +%Y%m%d)wrangler d1 export imagebot-db-prod --output "backups/backup-$DATE.sql"echo "Backup completed: backup-$DATE.sql"Set up daily backups via cron job.
10.2 R2 Backup
Section titled “10.2 R2 Backup”# List all objectswrangler r2 object list imagebot-images-prod
# Download specific objectwrangler r2 object get imagebot-images-prod/generated/img_abc123.png --file=backup.pngConsider using R2 to S3 replication for redundancy.
Production Checklist
Section titled “Production Checklist”Before going live:
- All environment secrets configured
- Database migrations applied
- Worker deployed and health check passes
- Frontend deployed to Pages
- Custom domains configured (if using)
- SSL/TLS set to Full (strict)
- CORS configured correctly
- Rate limiting enabled
- Analytics enabled
- Monitoring alerts configured
- Backup strategy implemented
- Load testing completed
- Security audit completed
- Documentation updated
Rollback Procedure
Section titled “Rollback Procedure”If deployment fails:
# Rollback Worker to previous versionwrangler rollback
# Rollback Pages deployment# Go to Pages → Deployments → Previous deployment → "Rollback to this deployment"Cost Estimation
Section titled “Cost Estimation”Cloudflare Free Tier:
- Workers: 100,000 requests/day
- Pages: Unlimited bandwidth
- D1: 5GB storage, 5M reads/day
- R2: 10GB storage, 1M reads/month
- AI: 10,000 neurons/day
Expected Monthly Costs (beyond free tier):
- Workers: $5/10M requests
- R2: $0.015/GB storage
- D1: $0.50/GB storage
- AI: $0.01/1,000 neurons
Estimated cost for 10K users: $20-50/month
Scaling Considerations
Section titled “Scaling Considerations”Horizontal Scaling
Section titled “Horizontal Scaling”- Cloudflare automatically scales Workers globally
- No configuration needed for geographic distribution
Database Optimization
Section titled “Database Optimization”- Add indexes for frequently queried columns
- Use prepared statements for performance
- Monitor D1 query times via analytics
R2 Optimization
Section titled “R2 Optimization”- Enable R2 lifecycle policies
- Implement image compression
- Use CDN caching aggressively
Support & Troubleshooting
Section titled “Support & Troubleshooting”Common production issues:
Worker errors:
wrangler tail imagebot-worker --status errorDatabase connection issues:
- Verify database_id in wrangler.toml
- Check D1 quota limits
- Review D1 analytics for slow queries
CORS errors:
- Verify allowed origins match Pages domain
- Check preflight OPTIONS handling
Rate limiting:
- Review Worker analytics for throttled requests
- Adjust rate limits in wrangler.toml