> ## Documentation Index
> Fetch the complete documentation index at: https://docs.charle.agency/llms.txt
> Use this file to discover all available pages before exploring further.

# Deployment

> Deploying CharleOS to production

CharleOS is deployed to **Vercel** with automatic deployments from GitHub. This page provides an overview of the deployment process.

## Deployment Architecture

```
GitHub (main branch)
  ↓
  Trigger: Push to main
  ↓
Vercel Build
  ├── Install dependencies
  ├── Run database migrations
  ├── Build Next.js app
  └── Deploy to production
  ↓
charle.agency (live)
```

### Environments

| Environment    | URL                                                               | Branch           | Purpose          |
| -------------- | ----------------------------------------------------------------- | ---------------- | ---------------- |
| **Production** | [https://charle.agency](https://charle.agency)                    | `main`           | Live application |
| **Preview**    | [https://charle-os-\*.vercel.app](https://charle-os-*.vercel.app) | Feature branches | PR previews      |
| **Local**      | [http://localhost:3000](http://localhost:3000)                    | Any              | Development      |

## Deployment Process

### Automatic Deployments

Every push to `main` triggers a deployment:

<Steps>
  <Step title="Push to GitHub">
    ```bash theme={null}
    git push origin main
    ```
  </Step>

  <Step title="Vercel Detects Change">
    Webhook triggers Vercel build automatically
  </Step>

  <Step title="Build Process">
    * Install npm dependencies
    * Run database migrations (`postinstall` script)
    * Build Next.js application
    * Generate static assets
  </Step>

  <Step title="Deploy">
    * Upload to Vercel's CDN
    * Update DNS to point to new deployment
    * Old deployment kept for 30 days (rollback)
  </Step>

  <Step title="Post-Deploy">
    * Environment goes live
    * Vercel sends notification
    * Logs available in dashboard
  </Step>
</Steps>

### Preview Deployments

Pull requests get automatic preview deployments:

* **URL**: `https://charle-os-git-{branch}-charle.vercel.app`
* **Purpose**: Test changes before merging
* **Database**: Uses DEV branch (safe to experiment)
* **Auto-cleanup**: Deleted after PR merges

## Build Configuration

### package.json Scripts

```json theme={null}
{
  "scripts": {
    "build": "next build",
    "postinstall": "drizzle-kit migrate"
  }
}
```

**Build process:**

1. `npm install` - Install dependencies
2. `postinstall` hook runs → `drizzle-kit migrate` - Apply database migrations
3. `npm run build` - Build Next.js app

### Environment Variables

Production environment variables are set in Vercel dashboard:

**Required for build:**

* `DATABASE_URL` - Production database connection
* `BETTER_AUTH_SECRET` - Auth encryption key
* `BETTER_AUTH_URL` - `https://charle.agency`
* `GOOGLE_CLIENT_ID` - Google OAuth credentials
* `GOOGLE_CLIENT_SECRET`

**Runtime variables:**

* All integration API keys (Pusher, Resend, Algolia, etc.)
* Feature flags
* Service URLs

<Info>
  Environment variables are encrypted at rest and only decrypted during build/runtime.
</Info>

## Database Migrations

Migrations run automatically during deployment:

```json theme={null}
// package.json
{
  "postinstall": "drizzle-kit migrate"
}
```

**How it works:**

1. Vercel installs dependencies
2. `postinstall` hook triggers
3. Drizzle applies pending migrations from `drizzle/` folder
4. If migrations fail, deployment fails (safe!)
5. App starts with updated schema

<Warning>
  Always test migrations locally before deploying. Failed migrations will prevent deployment.
</Warning>

## Rollback

If a deployment has issues:

### Option 1: Rollback in Vercel Dashboard

1. Go to [Vercel Dashboard](https://vercel.com/charle/charle-os)
2. Click "Deployments"
3. Find previous working deployment
4. Click "⋯" → "Promote to Production"

### Option 2: Revert Git Commit

```bash theme={null}
# Revert last commit
git revert HEAD
git push origin main

# Vercel automatically deploys the revert
```

### Option 3: Redeploy Previous Commit

```bash theme={null}
# Go to specific commit
git checkout abc123

# Force push (use with caution!)
git push origin main --force

# Or create revert commit
git revert abc123..HEAD
git push origin main
```

## Monitoring

### Vercel Analytics

Built-in analytics show:

* Page views
* Load times
* Core Web Vitals
* Top pages

**Access:** [Vercel Dashboard → Analytics](https://vercel.com/charle/charle-os/analytics)

### Sentry Error Tracking

Production errors are tracked in Sentry:

* Runtime errors
* API failures
* Performance issues
* User context

**Access:** [Sentry Dashboard](https://sentry.io/organizations/charle/projects/)

### Logs

View deployment logs in Vercel:

**Build logs:**

* Show build output
* Database migration results
* Warnings and errors

**Runtime logs:**

* API route logs
* Server component logs
* Edge function logs

**Access:** Vercel Dashboard → Deployments → Select deployment → Logs

## Performance Optimization

### Caching Strategy

Vercel automatically caches:

* Static assets (images, CSS, JS)
* Server Components (ISR)
* API routes with `Cache-Control` headers

### Edge Functions

API routes run on Vercel's Edge Network:

* **Global**: Deployed to 90+ edge locations
* **Fast**: Sub-100ms response times
* **Scalable**: Auto-scales to demand

### Image Optimization

Next.js Image component uses Vercel's optimization:

* Automatic format conversion (WebP/AVIF)
* Responsive sizing
* Lazy loading
* CDN caching

## Security

<AccordionGroup>
  <Accordion title="HTTPS Everywhere" icon="lock">
    * All traffic encrypted with TLS 1.3
    * Automatic SSL certificate management
    * HTTP → HTTPS redirect
  </Accordion>

  <Accordion title="Environment Variable Encryption" icon="key">
    * Encrypted at rest
    * Only decrypted during build/runtime
    * Never exposed in logs or UI
  </Accordion>

  <Accordion title="DDoS Protection" icon="shield">
    * Vercel's Edge Network provides DDoS mitigation
    * Automatic rate limiting
    * IP blocking for suspicious traffic
  </Accordion>

  <Accordion title="Security Headers" icon="shield-check">
    ```typescript theme={null}
    // next.config.ts
    module.exports = {
      async headers() {
        return [
          {
            source: '/:path*',
            headers: [
              { key: 'X-Frame-Options', value: 'DENY' },
              { key: 'X-Content-Type-Options', value: 'nosniff' },
              { key: 'Referrer-Policy', value: 'origin-when-cross-origin' },
            ],
          },
        ];
      },
    };
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

### Build Failures

**Error:** "Build failed"

**Common causes:**

1. TypeScript errors
2. Failed database migration
3. Missing environment variables
4. Dependency installation failure

**Fix:**

1. Check build logs in Vercel dashboard
2. Run `npm run build` locally to reproduce
3. Fix errors and push again

### Runtime Errors

**Error:** "Application error" / 500 Internal Server Error

**Fix:**

1. Check Sentry for error details
2. View runtime logs in Vercel
3. Verify environment variables are set
4. Check database connection

### Migration Failures

**Error:** "Migration failed"

**Fix:**

1. Test migration locally: `npm run db:migrate`
2. Check migration SQL for syntax errors
3. Verify database schema compatibility
4. If needed, create fix-forward migration

## Best Practices

<AccordionGroup>
  <Accordion title="Test Locally Before Deploying" icon="flask">
    Always build and test locally:

    ```bash theme={null}
    # Build locally
    npm run build

    # Run production build
    npm run start

    # Test migrations
    npm run db:migrate
    ```
  </Accordion>

  <Accordion title="Use Preview Deployments" icon="eye">
    Test changes in preview before merging:

    1. Create PR
    2. Wait for Vercel preview deployment
    3. Test preview URL
    4. Merge when confirmed working
  </Accordion>

  <Accordion title="Monitor After Deployment" icon="chart-line">
    Watch for issues after deploying:

    * Check Vercel Analytics for traffic
    * Monitor Sentry for errors
    * Verify key user flows work
    * Check database migrations succeeded
  </Accordion>

  <Accordion title="Keep Dependencies Updated" icon="arrows-rotate">
    Regular dependency updates:

    ```bash theme={null}
    # Check for updates
    npm outdated

    # Update dependencies
    npm update

    # Test thoroughly before deploying
    ```
  </Accordion>
</AccordionGroup>

## Deployment Checklist

Before deploying to production:

* [ ] All tests passing (unit + E2E)
* [ ] TypeScript compiles without errors
* [ ] Database migrations tested locally
* [ ] Environment variables configured
* [ ] Breaking changes documented
* [ ] Rollback plan prepared
* [ ] Monitoring/alerts configured

## Related Documentation

<CardGroup cols={2}>
  <Card title="Vercel Deployment" icon="triangle" href="/developer/deployment/vercel">
    Vercel-specific configuration
  </Card>

  <Card title="CI/CD Pipeline" icon="circle-check" href="/developer/deployment/ci-cd">
    Automated testing and deployment
  </Card>

  <Card title="Database Migrations" icon="database" href="/developer/database/migrations">
    Managing schema changes
  </Card>

  <Card title="Environment Variables" icon="gear" href="/developer/getting-started/environment">
    Configuration reference
  </Card>
</CardGroup>
