# Optimized Vercel Deployment Guide

**Date**: November 5, 2025  
**Purpose**: Guide for CLI-based pre-built deployments to minimize upload size and deployment time

## Overview

This guide describes the new optimized deployment process for the Polartek main app using Vercel's CLI with pre-built artifacts.

### What Changed

**Old Approach (Git-Based)**:
- Push code to GitHub
- Vercel builds on their servers
- Upload size: ~25-30 MB (source + node_modules)
- Build time: 2-5 minutes

**New Approach (CLI-Based Pre-Built)**:
- Build locally with Bun
- Upload only production artifacts
- Upload size: ~18 MB (dist directory only)
- Build time: <1 second on Vercel

### Benefits

1. **Faster deployments**: 30-60 seconds vs 3-8 minutes
2. **Smaller uploads**: 80% reduction in upload size
3. **Local control**: Build on your machine, control over build environment
4. **Cost savings**: Reduced Vercel build minutes and bandwidth
5. **Reliable**: Guaranteed same build locally and deployed

### Tradeoffs

1. **Manual deployment**: No automatic deployments on git push
2. **Local build required**: Must build before deploying
3. **Local environment setup**: Need Bun and dependencies locally
4. **CI/CD updates needed**: GitHub Actions needs modification

## Quick Start

### For Manual Deployments

```bash
# 1. Set environment variables
export VITE_API_URL=https://api.polartek.vercel.app

# 2. Deploy (builds locally and uploads)
bun deploy:main:optimized

# 3. Choose preview or production
# The script will ask before going to production
```

### For CI/CD Deployments

Update GitHub Actions to build locally, then deploy.

See [CI/CD Integration](#cicd-integration) section.

## Detailed Deployment Process

### Step 1: Prepare Environment Variables

**Identify build-time variables** (baked into JavaScript):
```bash
export VITE_API_URL=https://api.polartek.vercel.app
export VITE_APP_VERSION=1.0.0
```

**Set optional flags**:
```bash
# Run preview deployment first (default: true)
# Use --skip-preview to go straight to production

# Test build locally before deploying
# Use --test to start preview server
```

### Step 2: Build Locally

```bash
cd /Users/razvan/git/polartek/apps/main
bun run build
```

**Expected output**:
- `dist/` directory created (~18 MB)
- 120+ files including HTML, JS, CSS, assets
- Build completes in <30 seconds

**Verify build**:
```bash
du -sh dist/
find dist/ -type f | wc -l
```

### Step 3: Test Build Locally (Optional)

```bash
# Preview the build locally
bun run preview

# Open http://localhost:4173 and test functionality
# Check console for errors
# Then Ctrl+C to exit
```

### Step 4: Deploy to Vercel

```bash
# From monorepo root
bun deploy:main:optimized

# Or from app directory
cd apps/main && bun run build && cd ../.. && vercel deploy
```

**What happens**:
1. Script validates prerequisites (Bun, Vercel CLI)
2. Authenticates with Vercel (if needed)
3. Cleans previous builds
4. Builds app locally with Vite
5. Creates preview deployment
6. Asks for confirmation before production
7. Deploys to production

### Step 5: Verify Deployment

**Check preview URL** (before production):
- Visit preview link in terminal output
- Test all main features
- Check browser console for errors
- Verify API connectivity

**Check production** (after deploying):
- Visit https://polartek.vercel.app
- Run smoke tests
- Verify CDN caching headers
- Check analytics integration

## Script Options

### `bun deploy:main:optimized`

**Default behavior**:
1. Builds locally
2. Creates preview deployment
3. Asks for confirmation
4. Deploys to production

**Options**:
```bash
# Skip preview, go straight to production
bun deploy:main:optimized --skip-preview

# Test build locally first
bun deploy:main:optimized --test

# Skip preview and test
bun deploy:main:optimized --skip-preview --test
```

## Deployment Checklist

Before each deployment, verify:

- [ ] All code changes committed
- [ ] Tests passing locally
- [ ] Build completes without errors
- [ ] No console errors in local preview
- [ ] Environment variables set correctly
- [ ] API endpoints are accessible
- [ ] Database migrations up to date

## Breaking Changes

### Git Pushes No Longer Trigger Deployments

**Old behavior**: Push to GitHub → Automatic Vercel deployment

**New behavior**: Must explicitly run deployment script

**Impact**: Requires manual deployment step but more control

### Build-Time Variables Must Be Set Locally

**Old behavior**: Vercel built on their servers with env vars from dashboard

**New behavior**: Must set `VITE_*` variables before running `bun run build`

**Example**:
```bash
# WRONG: This won't work anymore
git push
# (no deployment happens)

# CORRECT: Build and deploy manually
export VITE_API_URL=https://api.polartek.vercel.app
bun deploy:main:optimized
```

### CI/CD Pipelines Need Updates

**Old behavior**: GitHub push → Vercel builds and deploys

**New behavior**: GitHub push → CI builds locally → CI deploys via Vercel CLI

See [CI/CD Integration](#cicd-integration) section.

## Environment Variables

See detailed guide: `docs/deployment/environment-variables-guide.md`

### Quick Reference

**Build-Time Variables** (set before `bun run build`):
- `VITE_API_URL` - API endpoint (public)
- `VITE_APP_VERSION` - App version (public)
- `VITE_ENVIRONMENT` - Environment name (public)

**Runtime Variables** (set in Vercel dashboard):
- Use `/api/config` endpoint for secrets
- Use `/config.json` for public runtime config
- Never use `VITE_` prefix for secrets

## Troubleshooting

### Issue: Vercel CLI not installed

**Error**: `vercel: command not found`

**Solution**:
```bash
npm install -g vercel
```

### Issue: Not authenticated with Vercel

**Error**: `Error: You are not authenticated`

**Solution**:
```bash
vercel login
```

### Issue: Build fails locally

**Error**: `Build failed: dist directory not found`

**Solution**:
```bash
# Check for errors in build output
cd apps/main
bun run build

# Common issues:
# - Missing dependencies: bun install
# - TypeScript errors: bun run type-check
# - Environment variables not set: export VITE_API_URL=...
```

### Issue: Deployment timeout

**Error**: `Deployment timed out`

**Solution**:
1. Check internet connection
2. Try again: `bun deploy:main:optimized --skip-preview`
3. Check Vercel status: https://www.vercelstatus.com

### Issue: App doesn't load on preview URL

**Error**: Blank page or error in console

**Solution**:
1. Check network tab - verify dist files loaded
2. Check console - look for JavaScript errors
3. Verify API endpoint is correct
4. Test locally: `bun run preview`

### Issue: Environment variables not working

**Error**: API calls fail with wrong endpoint

**Solution**:
1. Verify variables baked into build:
   ```bash
   grep -r "api.polartek.app" dist/
   ```
2. Check for typos in variable names
3. Rebuild with correct variables:
   ```bash
   export VITE_API_URL=https://api.polartek.vercel.app
   bun run build
   bun deploy:main:optimized
   ```

## Rollback Procedure

### Quick Rollback via Vercel Dashboard

1. Go to https://vercel.com/dashboard
2. Select Polartek main project
3. Click "Deployments" tab
4. Find the previous successful deployment
5. Click menu (•••) → "Promote to Production"

### Command-Line Rollback

```bash
# Get deployment URL
vercel deployments

# Rollback to specific deployment
vercel rollback <deployment-url>
```

### Re-Enable Git-Based Deployments (Emergency)

If you need to revert to git-based deployments:

1. Go to Project Settings in Vercel
2. Set `buildCommand`: `cd apps/main && bun run build`
3. Set `installCommand`: `bun install`
4. Disconnect current CLI link
5. Connect GitHub repo again

## CI/CD Integration

### GitHub Actions Setup

Create `.github/workflows/deploy-main.yml`:

```yaml
name: Deploy Main App

on:
  push:
    branches: [main]
    paths:
      - 'apps/main/**'
      - '.github/workflows/deploy-main.yml'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Bun
        uses: oven-sh/setup-bun@v1
      
      - name: Install dependencies
        run: bun install
      
      - name: Build main app
        env:
          VITE_API_URL: https://api.polartek.vercel.app
          VITE_APP_VERSION: ${{ github.ref_name }}
        run: |
          cd apps/main
          bun run build
      
      - name: Deploy to Vercel
        env:
          VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
          VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
          VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
        run: |
          cd apps/main
          vercel deploy --prod --token=$VERCEL_TOKEN
```

### Required Secrets in GitHub

1. `VERCEL_TOKEN`: Personal access token from Vercel
2. `VERCEL_ORG_ID`: Organization ID from Vercel
3. `VERCEL_PROJECT_ID`: Project ID from Vercel dashboard

### Getting Vercel Secrets

1. **VERCEL_TOKEN**:
   ```bash
   vercel login
   # Token stored in ~/.vercel/auth.json
   ```

2. **VERCEL_ORG_ID** and **VERCEL_PROJECT_ID**:
   ```bash
   vercel project list
   # Or check .vercel/project.json in main app
   ```

## Performance Metrics

### Upload Size Reduction

**Before**: ~25-30 MB (source + node_modules)
**After**: ~18 MB (dist only)
**Reduction**: 30-40% smaller uploads

### Deployment Time Reduction

**Before**: 3-8 minutes (remote build + upload)
**After**: 30-60 seconds (upload only)
**Reduction**: 80-90% faster deployments

### Build Time

**Before**: 2-5 minutes on Vercel servers
**After**: <30 seconds locally (not counted in deployment time)
**Control**: Full control over build environment

## Monitoring & Alerts

### Set Up Vercel Notifications

1. Go to Project Settings
2. Notifications → Slack / Email
3. Enable deployment alerts
4. Choose: Failed deployments, Production deployments, etc.

### Monitor Upload Size

```bash
# Check size before deploying
cd apps/main && du -sh dist/

# Track over time
cd apps/main
echo "$(date): $(du -sh dist/ | cut -f1)" >> ~/deployment-sizes.log
```

### Health Checks

After each deployment:
- [ ] App loads (check https://polartek.vercel.app)
- [ ] No console errors
- [ ] API calls work
- [ ] Authentication flows work
- [ ] Key features functional
- [ ] Analytics working

## Maintenance

### Updating .vercelignore

Periodically review `.vercelignore` to ensure nothing unnecessary is uploaded:

```bash
# Check what's being uploaded
vercel deploy --dry-run

# If size seems large, update .vercelignore
# See docs/deployment/baseline-audit.md for what should be excluded
```

### Monitoring Upload Trends

```bash
# Monitor size changes
cd apps/main
du -sh dist/ # Check current size
```

**Expected size**: 16-20 MB
**Alert if**: >25 MB (something added to dist)

### Rotating Secrets

Vercel secrets should be rotated regularly:

1. Generate new secret
2. Update in Vercel dashboard
3. Test in preview deployment
4. Deploy to production

## Additional Resources

- [Vercel CLI Documentation](https://vercel.com/docs/cli)
- [Environment Variables Guide](environment-variables-guide.md)
- [Baseline Audit Report](baseline-audit.md)
- [Vercel CLI Research](vercel-cli-research.md)
- [Vercel Docs - Static Deployment](https://vercel.com/docs/concepts/deployments/static-deployments)

## Support & Questions

For issues or questions:

1. Check [Troubleshooting](#troubleshooting) section
2. Review [Vercel CLI Research](vercel-cli-research.md) for technical details
3. Check Vercel logs: `vercel logs <url>`
4. Run `vercel --version` to ensure CLI is updated

## Summary

| Aspect | Git Deploy | CLI Deploy |
|--------|-----------|-----------|
| Upload size | 25-30 MB | ~18 MB |
| Deployment time | 3-8 min | 30-60 sec |
| Build location | Vercel servers | Local |
| Automation | Automatic | Manual/CI-CD |
| Control | Limited | Full |
| Cost | Higher | Lower |
