Skip to content

deploy-worker

Deploy your application to Cloudflare Workers.

Overview

The deploy-worker command handles the complete deployment process for your Cloudflare Workers application, including environment configuration, secret management, and production deployment.

Usage

bash
/template deploy-worker [environment] [options]

Parameters

  • [environment] - Target environment: production, staging, preview (default: production)

Options

  • --dry-run - Preview deployment without applying changes
  • --secrets - Update secrets during deployment
  • --migrations - Run database migrations
  • --compatibility-date - Set Workers compatibility date

Examples

Production Deployment

bash
/template deploy-worker production

Staging with Migrations

bash
/template deploy-worker staging --migrations

Preview Deployment

bash
/template deploy-worker preview --dry-run

Update Secrets

bash
/template deploy-worker production --secrets

What It Creates

Deployment Configuration

  • Environment-specific wrangler configs
  • GitHub Actions workflow
  • Deployment scripts
  • Secret management utilities

Generated Structure

├── .github/
│   └── workflows/
│       └── deploy.yml      # CI/CD workflow
├── deploy/
│   ├── environments/
│   │   ├── production.toml # Production config
│   │   ├── staging.toml    # Staging config
│   │   └── preview.toml    # Preview config
│   ├── scripts/
│   │   ├── deploy.sh       # Deployment script
│   │   ├── secrets.sh      # Secret management
│   │   └── validate.sh     # Pre-deploy validation
│   └── checks.ts           # Deployment checks

Environment Configuration

toml
# deploy/environments/production.toml
name = "my-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[env.production]
vars = { 
  ENVIRONMENT = "production",
  API_URL = "https://api.myapp.com"
}

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

[[r2_buckets]]
binding = "FILES"
bucket_name = "my-app-files"

[[d1_databases]]
binding = "DB"
database_id = "xxxxx"

GitHub Actions Workflow

yaml
# .github/workflows/deploy.yml
name: Deploy to Cloudflare Workers

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run tests
        run: npm test
        
      - name: Deploy to Cloudflare
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}

Deployment Process

1. Pre-deployment Checks

typescript
// deploy/checks.ts
export async function runPreDeployChecks() {
  // Check environment variables
  validateEnvVars(['DATABASE_URL', 'JWT_SECRET']);
  
  // Test database connection
  await testDatabaseConnection();
  
  // Verify API keys
  await verifyApiKeys();
  
  // Check resource limits
  await checkResourceLimits();
}

2. Secret Management

bash
# deploy/scripts/secrets.sh
#!/bin/bash

# Set production secrets
wrangler secret put JWT_SECRET --env production
wrangler secret put DATABASE_URL --env production
wrangler secret put STRIPE_SECRET_KEY --env production

3. Database Migrations

typescript
// Run migrations before deployment
export async function runMigrations(env: string) {
  const db = getDatabase(env);
  const migrations = await getMigrations();
  
  for (const migration of migrations) {
    await db.exec(migration.sql);
    await markMigrationComplete(migration.id);
  }
}

4. Deployment Script

bash
# deploy/scripts/deploy.sh
#!/bin/bash

ENV=${1:-production}

echo "Deploying to $ENV..."

# Run pre-deploy checks
npm run deploy:check

# Run migrations if needed
if [ "$2" == "--migrations" ]; then
  npm run db:migrate:$ENV
fi

# Deploy to Cloudflare
wrangler deploy --env $ENV

# Run post-deploy tests
npm run test:e2e:$ENV

Environment Management

Development

bash
# Local development
wrangler dev

# With local resources
wrangler dev --local --persist

Staging

bash
# Deploy to staging
wrangler deploy --env staging

# Test staging environment
curl https://staging.myapp.workers.dev/health

Production

bash
# Deploy to production with confirmation
wrangler deploy --env production

# Rollback if needed
wrangler rollback --env production

Monitoring Deployment

Health Checks

typescript
app.get('/health', (c) => {
  return c.json({
    status: 'healthy',
    environment: c.env.ENVIRONMENT,
    version: c.env.VERSION,
    timestamp: Date.now(),
  });
});

Deployment Notifications

typescript
// Notify on successful deployment
async function notifyDeployment(env: string) {
  await sendSlackMessage({
    text: `Deployed to ${env} successfully`,
    channel: '#deployments',
  });
}

Best Practices

  1. Always Test First: Deploy to preview/staging before production
  2. Use Secrets: Never commit sensitive data
  3. Version Control: Tag releases in git
  4. Monitor Metrics: Watch performance after deployment
  5. Rollback Plan: Know how to quickly rollback

Rollback Procedures

Quick Rollback

bash
# List deployments
wrangler deployments list --env production

# Rollback to previous
wrangler rollback --env production

Manual Rollback

bash
# Deploy specific version
git checkout v1.2.3
wrangler deploy --env production

Performance Optimization

Bundle Size

bash
# Check bundle size before deploy
wrangler deploy --dry-run --outdir dist

# Analyze bundle
npm run analyze:bundle

Cold Start Optimization

  • Minimize dependencies
  • Use dynamic imports
  • Optimize initialization code

Security Checklist

  • [ ] All secrets in Cloudflare dashboard
  • [ ] Environment variables validated
  • [ ] CORS configured correctly
  • [ ] Rate limiting enabled
  • [ ] Security headers set

Troubleshooting

Common Issues

  1. Secret Missing: Check wrangler secret list
  2. KV Binding Error: Verify namespace ID
  3. Build Failure: Check Node.js version
  4. Size Limit: Reduce bundle size

Debug Deployment

bash
# Verbose deployment
wrangler deploy --env production --log-level debug

# Test specific routes
wrangler tail --env production

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