# 🚀 Deployment Guide - CardingCentral

## Production Checklist

Before deploying to production, ensure:

- [ ] Change JWT_SECRET in environment
- [ ] Update SITE_URL to your domain
- [ ] Configure Telegram bot token and chat ID
- [ ] Set up proper database backup strategy
- [ ] Enable HTTPS only
- [ ] Setup domain SSL certificate
- [ ] Configure analytics (optional)
- [ ] Test all features on staging

## Deploying Frontend (React)

### Option 1: Netlify (Recommended - Free)

1. **Build the project:**
   ```bash
   cd client
   npm run build
   ```

2. **Connect to Netlify:**
   - Go to https://netlify.com
   - Click "New site from Git"
   - Connect GitHub repo
   - Build command: `cd client && npm run build`
   - Publish directory: `client/dist`
   - Deploy

3. **Configure environment:**
   - In Netlify dashboard → Settings → Environment
   - Add `VITE_API_URL=https://your-api.com/api`

4. **Setup domain:**
   - In Netlify → Custom domain
   - Add your domain (cardingcentral.com)

### Option 2: Vercel (Free)

1. **Build and deploy:**
   ```bash
   npm install -g vercel
   vercel
   ```

2. **Follow prompts:**
   - Select framework: Other
   - Output directory: `client/dist`

3. **Set environment variables:**
   - Project Settings → Environment Variables
   - Add API URL

### Option 3: Firebase Hosting (Free)

```bash
npm install -g firebase-tools
firebase login
firebase init hosting
# Select client/dist as public directory
firebase deploy
```

### Option 4: Manual Server (nginx/Apache)

1. **Build:**
   ```bash
   cd client
   npm run build
   # dist/ folder now contains static files
   ```

2. **Upload dist folder to server**

3. **nginx config:**
   ```nginx
   server {
     listen 80;
     server_name cardingcentral.com;
     
     root /var/www/cardingcentral;
     index index.html;
     
     location / {
       try_files $uri /index.html;
     }
     
     location /api {
       proxy_pass http://localhost:5000;
       proxy_http_version 1.1;
       proxy_set_header Connection "";
     }
   }
   ```

4. **Redirect to HTTPS** (use Certbot for free SSL)

## Deploying Backend (Node.js)

### Option 1: Railway.app (Easy, Free tier)

1. **Create Railway account** at https://railway.app

2. **Connect GitHub:**
   - New Project → GitHub Repo
   - Select cardingcentral repo

3. **Configure:**
   - Root directory: `server`
   - Build command: `npm install`
   - Start command: `npm start`

4. **Set environment variables:**
   - `NODE_ENV=production`
   - `JWT_SECRET=your-super-secret-key`
   - `SITE_URL=https://cardingcentral.com`

5. **Generate domain:** Railway provides auto URL

6. **Update frontend API URL** to your Railway URL

### Option 2: Heroku

```bash
# Install Heroku CLI
curl https://cli.heroku.com/install.sh | sh

# Login
heroku login

# Create app
heroku create cardingcentral-api

# Set environment variables
heroku config:set NODE_ENV=production
heroku config:set JWT_SECRET=your-secret
heroku config:set SITE_URL=https://cardingcentral.com

# Deploy
git push heroku main
```

### Option 3: Render.com

1. Go to https://render.com
2. New → Web Service
3. Connect GitHub repo
4. Settings:
   - Root directory: `server`
   - Build: `npm install`
   - Start: `npm start`
5. Environment variables: (same as Railway)
6. Deploy

### Option 4: AWS EC2/DigitalOcean/Linode

**Setup Node.js on Ubuntu:**

```bash
# SSH into server
ssh root@your-server-ip

# Update system
apt update && apt upgrade -y

# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
apt install -y nodejs

# Install git
apt install -y git

# Clone repo
git clone https://github.com/yourname/cardingcentral.git
cd cardingcentral/server

# Install dependencies
npm install

# Install PM2 (process manager)
npm install -g pm2

# Start with PM2
pm2 start index.js --name "cardingcentral"
pm2 startup
pm2 save

# Install nginx
apt install -y nginx

# Copy config (see nginx config above)
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/cardingcentral
sudo nano /etc/nginx/sites-available/cardingcentral
# Paste config, update server_name

# Enable site
sudo ln -s /etc/nginx/sites-available/cardingcentral /etc/nginx/sites-enabled/

# Setup SSL with Certbot
apt install -y certbot python3-certbot-nginx
certbot certonly --standalone -d cardingcentral.com

# Restart nginx
sudo systemctl restart nginx
```

## Database Backup Strategy

### SQLite Backup (for development/small sites)

```bash
# Manual backup
cp server/db/cardingcentral.db server/db/backups/cardingcentral-$(date +%Y%m%d).db

# Automated daily backup (cron)
0 2 * * * cp /path/to/cardingcentral.db /path/to/backups/cardingcentral-$(date +\%Y\%m\%d).db
```

### Migration to PostgreSQL (for production scale)

1. **Install PostgreSQL:**
   ```bash
   apt install postgresql postgresql-contrib
   ```

2. **Update database.js to use pg instead of sqlite3**

3. **Migrate schema and data**

## Performance Optimization

### Frontend
- ✅ Already using Vite (fast builds)
- ✅ TailwindCSS PurgeCSS (minimal CSS)
- ✅ Image optimization (WebP + JPG)
- ✅ Code splitting (route-based)

**Additional:**
- Enable gzip compression in nginx
- Use CDN for image delivery (Cloudinary, ImgIX)
- Minify JavaScript/CSS (automatic via Vite)

### Backend
- ✅ Database indexes on key columns
- ✅ JWT caching (7-day tokens)
- ✅ Image optimization (Sharp)

**Additional:**
- Use Redis for caching (optional)
- Enable HTTP compression (helmet)
- Setup rate limiting (express-rate-limit)
- Monitor with PM2 Plus or New Relic

## Security in Production

### Required
- ✅ HTTPS/SSL certificate
- ✅ Strong JWT_SECRET (32+ chars, random)
- ✅ CORS whitelist only your domain
- ✅ Rate limiting on auth endpoints

### Recommended
- Add rate limiting:
  ```javascript
  import rateLimit from 'express-rate-limit';
  app.use('/api/auth/login', rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5
  }));
  ```

- Add CSRF protection
- Setup monitoring/alerts
- Regular security audits
- Keep dependencies updated: `npm audit fix`

## Monitoring & Logging

### Option 1: PM2 Plus (Free tier available)
```bash
pm2 plus
# Auto-monitors and sends alerts
```

### Option 2: Sentry (Error tracking)
```bash
npm install @sentry/node
# Add Sentry init to index.js
```

### Option 3: Basic Logging
```bash
npm install pino # Structured logging
```

## Domain Setup

1. **Purchase domain:** GoDaddy, Namecheap, Google Domains

2. **Point to your deployment:**
   - Netlify: Add nameservers
   - Railway/Heroku: Add CNAME record
   - Self-hosted: Add A record to server IP

3. **Setup SSL:**
   - Netlify/Vercel: Automatic (free)
   - Railway/Heroku: Automatic (free)
   - Self-hosted: Certbot (free)

## Post-Deployment

1. **Test everything:**
   - Create a post
   - Publish and verify
   - Check SEO in browser DevTools
   - Test Telegram notification
   - Verify sitemap.xml works
   - Check robots.txt

2. **Monitor:**
   - Check error logs
   - Monitor uptime
   - Track page performance
   - Monitor database size

3. **Backup:**
   - Setup automated database backups
   - Backup configuration files
   - Version control everything

4. **Update regularly:**
   - `npm audit fix` monthly
   - Security patches immediately
   - New features as needed

## Environment Variables

**Server (.env file):**
```
NODE_ENV=production
PORT=5000
JWT_SECRET=generate-random-secret-here
SITE_URL=https://cardingcentral.com
DB_PATH=/var/lib/cardingcentral/cardingcentral.db
```

**Client (.env file):**
```
VITE_API_URL=https://api.cardingcentral.com
VITE_SITE_NAME=CardingCentral
```

## Scaling Tips

As traffic grows:

1. **Database:**
   - Migrate from SQLite to PostgreSQL
   - Add database indexes
   - Setup replication for HA

2. **Backend:**
   - Use load balancer (nginx, HAProxy)
   - Run multiple Node instances (cluster mode)
   - Add Redis caching

3. **Frontend:**
   - Use CDN for static assets (Cloudflare, AWS CloudFront)
   - Enable aggressive caching headers
   - Optimize bundle size

4. **Images:**
   - Use image CDN (Cloudinary, ImgIX)
   - Auto-resize based on device
   - Serve WebP to modern browsers

## Support

For deployment help:
- Railway docs: https://docs.railway.app
- Heroku docs: https://devcenter.heroku.com
- Render docs: https://render.com/docs
- DigitalOcean tutorials: https://www.digitalocean.com/community/tutorials

---

**Your site will be live in minutes!** 🎉
