Add PM2 ecosystem config and deployment troubleshooting guide
All checks were successful
Build Frontend / Build Frontend (push) Successful in 23s

- Added ecosystem.config.js for PM2 with watch enabled
- Created .env.production.template with correct production URLs
- Added DEPLOYMENT_FIXES.md with complete troubleshooting guide
- Documented fixes for PM2 watch, login redirect, and WebSocket issues
This commit is contained in:
2026-01-11 01:46:50 +00:00
parent 5411d29ca7
commit 5502d403a4
2 changed files with 516 additions and 0 deletions

83
.env.production.template Normal file
View File

@@ -0,0 +1,83 @@
# Production Environment Variables Template
# Copy this to .env and fill in your actual values
# =============================================================================
# SERVER CONFIGURATION
# =============================================================================
NODE_ENV=production
PORT=3000
HOST=0.0.0.0
# =============================================================================
# DATABASE
# =============================================================================
# Production MongoDB connection (MongoDB Atlas or remote server)
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/turbotrades?retryWrites=true&w=majority
# =============================================================================
# STEAM AUTHENTICATION
# =============================================================================
# Get your Steam API key from: https://steamcommunity.com/dev/apikey
STEAM_API_KEY=YOUR_STEAM_API_KEY_HERE
# Steam OAuth URLs - MUST match your production domain
STEAM_REALM=https://api.turbotrades.dev
STEAM_RETURN_URL=https://api.turbotrades.dev/auth/steam/return
# =============================================================================
# CORS & COOKIES
# =============================================================================
# Frontend domain - where requests come from
CORS_ORIGIN=https://turbotrades.dev
# Cookie configuration for production
COOKIE_DOMAIN=.turbotrades.dev
COOKIE_SECURE=true
COOKIE_SAME_SITE=none
# =============================================================================
# JWT SECRETS
# =============================================================================
# Generate secure random strings for production!
# You can use: openssl rand -base64 32
JWT_ACCESS_SECRET=your-super-secret-jwt-access-key-change-this-in-production
JWT_REFRESH_SECRET=your-super-secret-jwt-refresh-key-change-this-in-production
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_EXPIRY=7d
# Session secret
SESSION_SECRET=your-super-secret-session-key-change-this-in-production
# =============================================================================
# RATE LIMITING
# =============================================================================
RATE_LIMIT_MAX=100
RATE_LIMIT_TIMEWINDOW=60000
# =============================================================================
# WEBSOCKET
# =============================================================================
WS_PING_INTERVAL=30000
WS_MAX_PAYLOAD=1048576
# =============================================================================
# EMAIL (Optional - for future features)
# =============================================================================
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
EMAIL_FROM=noreply@turbotrades.com
# =============================================================================
# IMPORTANT NOTES
# =============================================================================
#
# 1. STEAM_REALM and STEAM_RETURN_URL must use your API domain (api.turbotrades.dev)
# 2. CORS_ORIGIN should be your frontend domain (turbotrades.dev)
# 3. COOKIE_DOMAIN should start with a dot for subdomain support (.turbotrades.dev)
# 4. COOKIE_SECURE must be true in production (requires HTTPS)
# 5. COOKIE_SAME_SITE should be 'none' for cross-domain cookies with HTTPS
# 6. Generate new JWT secrets for production (never use the defaults!)
#
# =============================================================================

433
DEPLOYMENT_FIXES.md Normal file
View File

@@ -0,0 +1,433 @@
# Deployment Fixes & Troubleshooting Guide
This guide covers the three main issues you're experiencing and how to fix them.
---
## 🔴 Issues
1. **PM2 doesn't restart/watch properly**
2. **Login redirects to localhost instead of turbotrades.dev**
3. **WebSocket connection fails**
---
## ✅ Solutions
### 1. Fix PM2 Watch & Auto-Restart
#### Problem
PM2 is not watching for file changes or not restarting properly.
#### Solution
**A. Use the ecosystem.config.js file (already created)**
```bash
# Stop current PM2 process
pm2 stop all
pm2 delete all
# Start with ecosystem config
pm2 start ecosystem.config.js --env production
# Save the process list
pm2 save
# Setup PM2 to start on system boot
pm2 startup
```
**B. Manual PM2 commands (if ecosystem doesn't work)**
```bash
# Start with watch enabled
pm2 start index.js --name turbotrades-backend --watch --ignore-watch="node_modules logs frontend .git" --env production
# Or restart existing process with watch
pm2 restart turbotrades-backend --watch
```
**C. Verify PM2 is watching**
```bash
pm2 list # Check status
pm2 info turbotrades-backend # See watch status
pm2 logs # View real-time logs
```
---
### 2. Fix Login Redirect (localhost issue)
#### Problem
After Steam login, users are redirected to `localhost:3000` instead of `turbotrades.dev`.
#### Root Cause
Your production `.env` file contains localhost URLs for Steam authentication.
#### Solution
**Edit your `.env` file on the server and update these values:**
```env
# ❌ WRONG (localhost)
STEAM_REALM=http://localhost:3000
STEAM_RETURN_URL=http://localhost:3000/auth/steam/return
CORS_ORIGIN=http://localhost:5173
# ✅ CORRECT (production domain)
STEAM_REALM=https://api.turbotrades.dev
STEAM_RETURN_URL=https://api.turbotrades.dev/auth/steam/return
CORS_ORIGIN=https://turbotrades.dev
```
**Full production `.env` should have:**
```env
# Server
NODE_ENV=production
PORT=3000
HOST=0.0.0.0
# Database
MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/turbotrades
# Steam - MUST USE PRODUCTION DOMAIN
STEAM_API_KEY=your_actual_steam_api_key
STEAM_REALM=https://api.turbotrades.dev
STEAM_RETURN_URL=https://api.turbotrades.dev/auth/steam/return
# CORS & Cookies
CORS_ORIGIN=https://turbotrades.dev
COOKIE_DOMAIN=.turbotrades.dev
COOKIE_SECURE=true
COOKIE_SAME_SITE=none
# JWT Secrets (generate new ones!)
JWT_ACCESS_SECRET=your-production-secret-here
JWT_REFRESH_SECRET=your-production-secret-here
SESSION_SECRET=your-production-session-secret
```
**After editing `.env`:**
```bash
# Restart PM2 to pick up new env vars
pm2 restart turbotrades-backend --update-env
# Or if that doesn't work, reload
pm2 reload turbotrades-backend
```
---
### 3. Fix WebSocket Connection
#### Problem
WebSocket fails to connect: `Firefox can't establish a connection to wss://ws.turbotrades.dev/`
#### Root Cause
Frontend is trying to connect to wrong WebSocket URL.
#### Solution A: Rebuild Frontend (REQUIRED)
The frontend needs to be rebuilt with the correct environment variables:
```bash
cd frontend
# Build with production settings
npm run build
# Upload the new dist/ folder to your server
# The dist folder should be served by your web server (Nginx/Apache)
```
The `.env.production` file (already created) contains:
```env
VITE_WS_URL=wss://api.turbotrades.dev/ws
```
#### Solution B: Configure Reverse Proxy
**If using Nginx**, add WebSocket support:
```nginx
server {
listen 443 ssl http2;
server_name api.turbotrades.dev;
# ... SSL config ...
# Regular API endpoints
location /api/ {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# WebSocket endpoint
location /ws {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 86400;
}
# Steam OAuth callback (no /api prefix)
location /auth/ {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
**After editing Nginx config:**
```bash
# Test config
sudo nginx -t
# Reload Nginx
sudo systemctl reload nginx
```
---
## 🚀 Complete Deployment Checklist
### Backend Deployment
- [ ] **1. Update `.env` file on server**
```bash
nano .env # or vim .env
# Update STEAM_REALM, STEAM_RETURN_URL, CORS_ORIGIN
```
- [ ] **2. Pull latest code**
```bash
git pull origin main
```
- [ ] **3. Install dependencies** (if needed)
```bash
npm install
```
- [ ] **4. Restart PM2 with ecosystem**
```bash
pm2 stop all
pm2 delete all
pm2 start ecosystem.config.js --env production
pm2 save
```
- [ ] **5. Verify backend is running**
```bash
pm2 logs
curl http://localhost:3000/health
```
### Frontend Deployment
- [ ] **1. Build frontend locally**
```bash
cd frontend
npm run build
```
- [ ] **2. Upload `dist/` folder to server**
```bash
# Using SCP
scp -r dist/* user@server:/path/to/webroot/
# Or using rsync
rsync -avz dist/ user@server:/path/to/webroot/
```
- [ ] **3. Verify frontend files are in place**
```bash
ls -la /path/to/webroot/
# Should see index.html, assets/, etc.
```
### Reverse Proxy (Nginx/Apache)
- [ ] **1. Configure WebSocket support**
- Edit Nginx/Apache config
- Add `/ws` location with WebSocket headers
- [ ] **2. Configure API proxy**
- `/api/*` → `http://localhost:3000/api/*`
- `/auth/*` → `http://localhost:3000/auth/*`
- [ ] **3. Test and reload**
```bash
sudo nginx -t
sudo systemctl reload nginx
```
---
## 🧪 Testing
### Test Backend
```bash
# Health check
curl https://api.turbotrades.dev/health
# Test Steam login (in browser)
https://turbotrades.dev
# Click "Login to Steam" button
# Should redirect to Steam, then back to turbotrades.dev (NOT localhost)
```
### Test WebSocket
**In browser console (on turbotrades.dev):**
```javascript
// Test WebSocket connection
const ws = new WebSocket('wss://api.turbotrades.dev/ws');
ws.onopen = () => console.log('✅ WebSocket connected!');
ws.onerror = (err) => console.error('❌ WebSocket error:', err);
ws.onmessage = (msg) => console.log('📨 Message:', msg.data);
```
### Test PM2 Watch
```bash
# Make a small change to a file
echo "// test change" >> index.js
# Check PM2 logs - should see restart
pm2 logs
# Remove test change
git checkout index.js
```
---
## 🔍 Debugging
### Check Environment Variables
```bash
# View what PM2 is using
pm2 env turbotrades-backend
# Or check process
pm2 info turbotrades-backend
```
### Check Logs
```bash
# PM2 logs
pm2 logs turbotrades-backend --lines 100
# Application logs
tail -f logs/pm2-error.log
tail -f logs/pm2-out.log
# Nginx logs
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/access.log
```
### Common Issues
**Issue: "CORS error"**
- Check `CORS_ORIGIN` in `.env` matches frontend domain
- Restart backend after changing `.env`
**Issue: "WebSocket connection failed"**
- Rebuild frontend: `cd frontend && npm run build`
- Check Nginx WebSocket config
- Verify `/ws` endpoint: `curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" http://localhost:3000/ws`
**Issue: "Redirects to localhost"**
- Update `STEAM_REALM` and `STEAM_RETURN_URL` in `.env`
- Must use `https://api.turbotrades.dev`
- Restart PM2 with `--update-env`
**Issue: "PM2 not watching"**
- Use ecosystem.config.js: `pm2 start ecosystem.config.js`
- Or add `--watch` flag: `pm2 restart turbotrades-backend --watch`
---
## 📋 Quick Reference
### PM2 Commands
```bash
pm2 start ecosystem.config.js --env production # Start with config
pm2 restart turbotrades-backend --update-env # Restart with new env
pm2 reload turbotrades-backend # Zero-downtime reload
pm2 stop turbotrades-backend # Stop
pm2 delete turbotrades-backend # Remove from PM2
pm2 logs # View logs
pm2 monit # Monitor resources
pm2 save # Save process list
pm2 startup # Setup auto-start
```
### Build & Deploy
```bash
# Backend
git pull && npm install && pm2 restart all
# Frontend
cd frontend && npm run build && cd ..
# Then upload dist/ to server
# Full deployment
git pull && npm install && cd frontend && npm run build && cd .. && pm2 restart all
```
---
## 🎯 Expected Result
After following all steps:
✅ PM2 watches files and auto-restarts on changes
✅ Login redirects to `turbotrades.dev` (not localhost)
✅ WebSocket connects to `wss://api.turbotrades.dev/ws`
✅ All features work in production
---
## 📞 Support
If issues persist:
1. Check all logs (`pm2 logs`, Nginx logs)
2. Verify `.env` file has correct production URLs
3. Ensure frontend is rebuilt after changing `.env.production`
4. Test each component individually (backend health, WebSocket, login)
---
**Last Updated:** 2024
**Version:** 1.0