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 productionStaging with Migrations
bash
/template deploy-worker staging --migrationsPreview Deployment
bash
/template deploy-worker preview --dry-runUpdate Secrets
bash
/template deploy-worker production --secretsWhat 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 checksEnvironment 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 production3. 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:$ENVEnvironment Management
Development
bash
# Local development
wrangler dev
# With local resources
wrangler dev --local --persistStaging
bash
# Deploy to staging
wrangler deploy --env staging
# Test staging environment
curl https://staging.myapp.workers.dev/healthProduction
bash
# Deploy to production with confirmation
wrangler deploy --env production
# Rollback if needed
wrangler rollback --env productionMonitoring 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
- Always Test First: Deploy to preview/staging before production
- Use Secrets: Never commit sensitive data
- Version Control: Tag releases in git
- Monitor Metrics: Watch performance after deployment
- 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 productionManual Rollback
bash
# Deploy specific version
git checkout v1.2.3
wrangler deploy --env productionPerformance Optimization
Bundle Size
bash
# Check bundle size before deploy
wrangler deploy --dry-run --outdir dist
# Analyze bundle
npm run analyze:bundleCold 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
- Secret Missing: Check wrangler secret list
- KV Binding Error: Verify namespace ID
- Build Failure: Check Node.js version
- Size Limit: Reduce bundle size
Debug Deployment
bash
# Verbose deployment
wrangler deploy --env production --log-level debug
# Test specific routes
wrangler tail --env productionRelated Commands
deploy- Full deployment pipelinesetup-analytics- Monitor deploymentsadd-worker-cron- Schedule post-deploy tasks
