---
name: Deployment
description: Use this skill for deploying applications from development to production. Covers environments, CI/CD, deployment checklists, and rollback procedures.
version: 1.0.0
---

# Deployment Skill

> Getting your code from your laptop to users safely.

---

## Why This Matters

Bad deployments cause:
- ❌ Downtime (users can't use your app)
- ❌ Data loss
- ❌ Security vulnerabilities
- ❌ Reputation damage
- ❌ Stress and panic

**A good deployment process = confidence and safety.**

---

## Understanding Environments

```
┌─────────────────────────────────────────────────────────────┐
│                     ENVIRONMENTS                            │
├─────────────┬─────────────┬─────────────┬──────────────────┤
│   LOCAL     │   DEVELOP   │   STAGING   │   PRODUCTION     │
│             │             │             │                   │
│ Your laptop │ Shared dev  │ Pre-prod    │ Real users       │
│ experiment  │ integration │ testing     │ live data        │
│             │             │             │                   │
│ Break stuff │ May break   │ Should work │ MUST work        │
└─────────────┴─────────────┴─────────────┴──────────────────┘
         │            │            │              │
         └────────────┴────────────┴──────────────┘
                    Code flows left to right →
```

### Environment Purposes

| Environment | Purpose | Who Uses It | Data |
|-------------|---------|-------------|------|
| **Local** | Development | You | Fake/test data |
| **Develop** | Integration | Team | Test data |
| **Staging** | Pre-production testing | QA, stakeholders | Copy of prod data |
| **Production** | Live application | Real users | Real data |

---

## Environment Variables

Each environment has different configuration:

```bash
# .env.local (your machine - NEVER commit this)
DATABASE_URL=postgresql://localhost:5432/myapp_dev
NEXT_PUBLIC_API_URL=http://localhost:3000
STRIPE_SECRET_KEY=sk_test_xxxxx

# .env.staging (staging server)
DATABASE_URL=postgresql://staging-db.example.com/myapp_staging
NEXT_PUBLIC_API_URL=https://staging.myapp.com
STRIPE_SECRET_KEY=sk_test_xxxxx

# .env.production (production server)
DATABASE_URL=postgresql://prod-db.example.com/myapp
NEXT_PUBLIC_API_URL=https://myapp.com
STRIPE_SECRET_KEY=sk_live_xxxxx  # ← REAL keys!
```

### Golden Rules for Env Vars

1. **NEVER commit secrets** to git
2. **Add `.env*` to `.gitignore`**
3. **Use platform secrets** (Vercel, Railway, etc.)
4. **Different keys per environment**

```gitignore
# .gitignore
.env
.env.local
.env.*.local
```

---

## Deployment Platforms (Recommended)

### For Web Apps

| Platform | Best For | Ease | Cost |
|----------|----------|------|------|
| **Vercel** | Next.js, React | ⭐⭐⭐⭐⭐ | Free tier |
| **Railway** | Full-stack, databases | ⭐⭐⭐⭐ | Free tier |
| **Render** | General apps | ⭐⭐⭐⭐ | Free tier |
| **Fly.io** | Docker, global edge | ⭐⭐⭐ | Free tier |

### For Mobile Apps

| Platform | Best For |
|----------|----------|
| **Expo EAS** | React Native (Expo) |
| **App Store Connect** | iOS distribution |
| **Google Play Console** | Android distribution |

### For macOS Apps

| Method | Best For |
|--------|----------|
| **Mac App Store** | Wide distribution |
| **Direct (Notarized)** | Outside App Store |
| **TestFlight** | Beta testing |

---

## CI/CD Pipeline

### What is CI/CD?

```
CI (Continuous Integration)
= Automatically test code when pushed

CD (Continuous Deployment)
= Automatically deploy when tests pass
```

### Simple GitHub Actions Pipeline

```yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]  # Deploy when main is updated

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run tests
        run: npm test
      
      - name: Type check
        run: npm run typecheck
  
  deploy:
    needs: test  # Only deploy if tests pass
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      # For Vercel
      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: '--prod'
```

### Pipeline Stages

```
Push to main
     ↓
┌─────────────┐
│   INSTALL   │ npm ci
└──────┬──────┘
       ↓
┌─────────────┐
│    TEST     │ npm test
└──────┬──────┘
       ↓
┌─────────────┐
│    BUILD    │ npm run build
└──────┬──────┘
       ↓
┌─────────────┐
│   DEPLOY    │ Push to platform
└─────────────┘
```

---

## Deployment Checklist

### Before Every Deploy

#### Code Quality
- [ ] All tests pass locally
- [ ] TypeScript compiles without errors
- [ ] No console.log/debug statements
- [ ] No hardcoded secrets in code
- [ ] PR has been reviewed (if team)

#### Environment
- [ ] Environment variables set on platform
- [ ] Correct API keys for target environment
- [ ] Database migrations applied (if any)

#### Dependencies
- [ ] package-lock.json committed
- [ ] No vulnerable dependencies (`npm audit`)

### During Deploy

- [ ] Watch deployment logs
- [ ] Check for build errors
- [ ] Note deployment time (for rollback reference)

### After Deploy

- [ ] Verify app loads correctly
- [ ] Test critical user flows:
  - [ ] Login/signup works
  - [ ] Core feature works
  - [ ] Payments work (if applicable)
- [ ] Check error monitoring (Sentry, etc.)
- [ ] Monitor for spike in errors

---

## Database Migrations

### What Are Migrations?

Changes to your database structure that need to be applied safely.

```typescript
// migrations/001_add_users_table.sql
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email TEXT UNIQUE NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

// migrations/002_add_profile_to_users.sql
ALTER TABLE users ADD COLUMN profile_image TEXT;
```

### Migration Rules

1. **Never modify old migrations** - Create new ones
2. **Test migrations on staging first**
3. **Have a rollback plan**
4. **Backup before applying to production**

### With Supabase

```bash
# Generate migration
supabase migration new add_user_profile

# Apply locally
supabase db push

# Apply to production (via Supabase dashboard or CLI)
supabase db push --linked
```

---

## Rollback Procedures

### When to Rollback

- Critical feature is broken
- Security vulnerability discovered
- Data corruption occurring
- Major performance degradation

### How to Rollback

#### Vercel
```bash
# List deployments
vercel ls

# Rollback to previous
vercel rollback [deployment-url]

# Or via dashboard: Deployments → ... → Promote to Production
```

#### Git-based Rollback
```bash
# Revert last commit
git revert HEAD
git push origin main

# This triggers a new deploy with the reverted code
```

#### Emergency: Revert to Known Good
```bash
# Find last working commit
git log --oneline

# Deploy specific commit (platform-specific)
# Vercel: redeploy old deployment from dashboard
# Railway: git push with specific commit
```

---

## Deployment Strategies

### 1. All-at-Once (Simple)
```
Old version ──→ New version
           (instant switch)
```
- ✅ Simple
- ❌ Downtime risk

### 2. Rolling Deployment
```
Server 1: Old → New
Server 2: Old → New
Server 3: Old → New
        (gradual)
```
- ✅ Zero downtime
- ❌ More complex

### 3. Blue-Green
```
Blue (live) ←── Traffic
Green (new) ←── Testing

Then switch:
Blue (old) 
Green (live) ←── Traffic
```
- ✅ Easy rollback
- ❌ Need double resources

### For Solo/Small Teams
Start with **All-at-Once** via Vercel/Railway. Move to Blue-Green when you need more safety.

---

## Platform-Specific Guides

### Vercel (Next.js)

```bash
# Install CLI
npm i -g vercel

# First deploy
vercel

# Production deploy
vercel --prod

# Set environment variable
vercel env add STRIPE_SECRET_KEY production
```

**Automatic deploys:**
- Push to `main` → Production
- Push to other branches → Preview

### Railway

```bash
# Install CLI
npm i -g @railway/cli

# Login
railway login

# Deploy
railway up

# View logs
railway logs
```

### Expo (React Native)

```bash
# Install EAS CLI
npm i -g eas-cli

# Configure
eas build:configure

# Build for iOS
eas build --platform ios

# Build for Android
eas build --platform android

# Submit to stores
eas submit
```

---

## Monitoring After Deploy

### Essential Monitoring

| Tool | Purpose | Free Tier |
|------|---------|-----------|
| **Sentry** | Error tracking | ✅ |
| **Vercel Analytics** | Web vitals | ✅ |
| **PostHog** | Product analytics | ✅ |
| **UptimeRobot** | Uptime monitoring | ✅ |

### What to Watch

```
First 15 minutes after deploy:
├── Error rate (should stay same or decrease)
├── Response times (should stay same)
├── CPU/Memory usage (should stay same)
└── User complaints (check support channels)
```

---

## Quick Reference: Deploy Commands

```bash
# Vercel
vercel --prod                    # Deploy to production
vercel ls                        # List deployments
vercel rollback                  # Rollback

# Railway
railway up                       # Deploy
railway logs                     # View logs

# GitHub Actions
# Just push to main - it deploys automatically

# Manual database backup (Supabase)
supabase db dump -f backup.sql
```

---

## Pre-Production Checklist (Final)

Before going live with a new product:

### Security
- [ ] HTTPS enabled
- [ ] Secrets in environment variables (not code)
- [ ] Authentication tested
- [ ] Sensitive endpoints protected
- [ ] CORS configured correctly

### Performance
- [ ] Build is optimized
- [ ] Images optimized
- [ ] No unnecessary console logs

### Reliability
- [ ] Error tracking set up (Sentry)
- [ ] Health check endpoint exists
- [ ] Database backups configured
- [ ] Domain and SSL configured

### Legal
- [ ] Privacy policy page
- [ ] Terms of service page
- [ ] Cookie consent (if required)

---

## Vendor Deploy Skills

### Vercel Deployment (Recommended for Next.js)
For Vercel projects, install the official Vercel agent skills:
- Auto-detects framework (40+ supported)
- Creates claimable deploy URLs
- Source: github.com/vercel-labs/agent-skills

### Cloudflare Deployment
For Cloudflare projects, install official Cloudflare skills:
- Workers, Pages, D1, R2, Durable Objects
- Source: github.com/cloudflare/skills

### Deploy Checklist Enhancement
Before deploying, also verify:
- [ ] Security scan passed (Trail of Bits: check insecure defaults)
- [ ] No secrets in environment (verify .env.local is gitignored)
- [ ] CSP headers configured
- [ ] HTTPS enforced
- [ ] Rate limiting enabled on API routes

---

*This skill ensures safe, reliable, and repeatable deployments.*
