# Complete Setup & Build Guide This document covers everything needed to develop, build, and deploy Craft2Prints. ## Table of Contents 1. [Local Development Setup](#local-development-setup) 2. [Configuration Reference](#configuration-reference) 3. [Database Management](#database-management) 4. [Feature Setup](#feature-setup) 5. [Building for Production](#building-for-production) 6. [Deployment](#deployment) 7. [Troubleshooting](#troubleshooting) --- ## Local Development Setup ### Prerequisites **Node.js 18 or later** is required: ```bash node -v # Check your version ``` If not installed, download from https://nodejs.org (LTS version recommended). ### Step 1: Clone and Install ```bash # Clone the repository git clone cd craft2prints # Install dependencies npm install # This automatically runs: npx prisma generate ``` ### Step 2: Environment Setup ```bash # Copy example environment file cp .env.example .env ``` Edit `.env` and configure at minimum: ```env DATABASE_URL="file:./dev.db" NEXT_PUBLIC_SITE_URL="http://localhost:3000" ADMIN_USER="admin" ADMIN_PASSWORD="changeme" ADMIN_SESSION_SECRET="" SESSION_SECRET="" ``` For random secrets, use: ```bash node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" ``` ### Step 3: Database Setup ```bash # Create SQLite database and run migrations npm run db:push # Load starter products npm run db:seed ``` ### Step 4: Start Development Server ```bash npm run dev ``` Open http://localhost:3000 in your browser. **Auto-reload on file changes:** The dev server watches your code and reloads automatically. If you change `prisma/schema.prisma`, run `npm run db:push` manually. --- ## Configuration Reference ### Essential Variables | Variable | Description | Example | |----------|-------------|---------| | `DATABASE_URL` | SQLite database path | `file:./dev.db` | | `ADMIN_USER` | Admin login username | `admin` | | `ADMIN_PASSWORD` | Admin login password | `changeme` | | `ADMIN_SESSION_SECRET` | Session signing key (random) | 32-byte hex string | | `SESSION_SECRET` | Customer session key (random) | 32-byte hex string | ### Stripe Configuration Get from https://dashboard.stripe.com (make sure you're in **test mode** first): ```env STRIPE_SECRET_KEY="sk_test_..." # From Developers > API keys STRIPE_WEBHOOK_SECRET="whsec_..." # From Stripe CLI (see below) ``` **Local Webhook Setup:** ```bash # Install Stripe CLI: https://docs.stripe.com/stripe-cli stripe login stripe listen --forward-to localhost:3000/api/webhook # Copy the whsec_... secret into .env ``` ### Email (SMTP) For order confirmations and password resets: ```env SMTP_HOST="smtp.gmail.com" SMTP_PORT="587" SMTP_USER="your-email@gmail.com" SMTP_PASSWORD="your-app-password" # Not your normal password! MAIL_FROM="Craft2Prints " ADMIN_NOTIFY_EMAIL="admin@example.com" # For photo request alerts ``` **For Gmail:** Generate an app password at https://myaccount.google.com/apppasswords (requires 2FA enabled). ### CAPTCHA (Cloudflare Turnstile) Protects public forms (registration, contact, custom requests): ```env NEXT_PUBLIC_TURNSTILE_SITE_KEY="..." # Get from dash.cloudflare.com TURNSTILE_SECRET_KEY="..." ``` If not configured, forms work without CAPTCHA. Optional, not required. ### Optional Variables ```env NEXT_PUBLIC_FACEBOOK_APP_ID="..." # For Messenger sharing NEXT_PUBLIC_SITE_URL="http://localhost:3000" # For design approval links ``` --- ## Database Management ### Common Tasks **Create database and migrations:** ```bash npm run db:push ``` **Reset database (⚠️ deletes all data):** ```bash rm dev.db npm run db:push npm run db:seed ``` **Add new database tables/columns:** 1. Edit `prisma/schema.prisma` 2. Run `npm run db:push` to sync **Seed starter products:** ```bash npm run db:seed ``` Updating the seed is safe — it only touches the 6 starter products by their slug, leaving your custom products untouched. **Backup database:** ```bash cp dev.db dev.db.backup-$(date +%Y%m%d-%H%M%S) ``` --- ## Feature Setup ### Stripe Payments 1. Create account at https://dashboard.stripe.com 2. Switch to **Test Mode** (top-right toggle) 3. Get **Secret Key** from Developers > API keys 4. Set `STRIPE_SECRET_KEY` in `.env` 5. Start Stripe webhook listener (see Configuration Reference above) 6. Test with card: `4242 4242 4242 4242`, any future expiry, any 3-digit CVC ### Email Notifications **Option 1: Gmail** 1. Enable 2-Factor Authentication 2. Generate app password at https://myaccount.google.com/apppasswords 3. Set SMTP variables in `.env` 4. Test by submitting a form that triggers email **Option 2: Other Providers** - Outlook, SendGrid, AWS SES, etc. — check their SMTP settings - Most follow the same pattern: username (email), password (app-specific) ### CAPTCHA Protection 1. Sign up at https://dash.cloudflare.com 2. Go to Turnstile > Add Site 3. Copy **Site Key** and **Secret Key** 4. Set in `.env`: ```env NEXT_PUBLIC_TURNSTILE_SITE_KEY="..." TURNSTILE_SECRET_KEY="..." ``` 5. Refresh the page — CAPTCHA should appear on forms --- ## Building for Production ### Build Process ```bash # Build the Next.js app npm run build # Start the production server npm start ``` The server listens on port 3000 by default. ### Build Output ``` .next/ # Compiled Next.js app (production build) .next/standalone/ # Self-contained server ``` ### Environment for Production Before deploying, update `.env` for production: ```env # Database (use production connection string) DATABASE_URL="postgresql://user:pass@prod-db:5432/craft2prints" # SECURITY: Change these! ADMIN_USER="" ADMIN_PASSWORD="" ADMIN_SESSION_SECRET="" SESSION_SECRET="" # Stripe (switch to LIVE keys, not test) STRIPE_SECRET_KEY="sk_live_..." STRIPE_WEBHOOK_SECRET="whsec_live_..." # Site URL NEXT_PUBLIC_SITE_URL="https://yourdomain.com" # Email (production SMTP) SMTP_HOST="..." SMTP_USER="..." SMTP_PASSWORD="..." MAIL_FROM="Craft2Prints " ``` --- ## Deployment ### Option 1: Self-Hosted (Recommended for Control) **Hardware Requirements:** - Server with Node.js 18+ support - 2GB+ RAM (more for concurrent traffic) - SQLite storage, or PostgreSQL for larger deployments **Setup:** 1. **Upload code to server** ```bash scp -r . user@server:/app/craft2prints ``` 2. **Install dependencies** ```bash ssh user@server cd /app/craft2prints npm install --production npm run build ``` 3. **Set up environment** ```bash cp .env.example .env # Edit .env with production values nano .env ``` 4. **Create database** ```bash npm run db:push npm run db:seed ``` 5. **Install process manager** (keep app running) ```bash npm install -g pm2 pm2 start "npm start" --name craft2prints pm2 startup pm2 save ``` 6. **Set up reverse proxy** (nginx) ```nginx server { listen 80; server_name yourdomain.com; location / { 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; } } ``` 7. **Enable HTTPS** (Let's Encrypt) ```bash sudo apt-get install certbot python3-certbot-nginx sudo certbot --nginx -d yourdomain.com ``` ### Option 2: Platform Services **Vercel** (easiest, free tier available) - Push to GitHub - Connect GitHub repo to Vercel - Environment variables in Vercel dashboard - Automatic deploys on push **Heroku** (deprecated but still works) - Use Procfile + buildpack - Set environment variables in Heroku dashboard **Railway, Render, etc.** - Similar to Vercel — push → deploy ### Option 3: Docker (Containerized) Create `Dockerfile`: ```dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --production COPY . . RUN npm run build EXPOSE 3000 CMD ["npm", "start"] ``` ```bash docker build -t craft2prints . docker run -p 3000:3000 --env-file .env craft2prints ``` ### Post-Deployment Checklist - [ ] Admin password changed from default - [ ] Session secrets regenerated - [ ] Stripe keys switched to **live** (not test) - [ ] Stripe webhook configured in dashboard - [ ] HTTPS enabled with valid certificate - [ ] Email SMTP tested (send test order confirmation) - [ ] CAPTCHA working on public forms - [ ] Database backups scheduled - [ ] Log monitoring set up - [ ] Rate limiting verified - [ ] Staging environment created for testing --- ## Troubleshooting ### Development **"Cannot find module '@prisma/client'"** ```bash npx prisma generate npm install ``` **Port 3000 already in use** ```bash npm run dev -- -p 3001 # Use port 3001 instead # Or find and kill process using port 3000 ``` **Blank product catalog** ```bash npm run db:seed # Load starter products ``` **Database corrupted** ```bash rm dev.db npm run db:push npm run db:seed ``` ### Production **App not starting** ```bash npm start # Check console for errors npm run build # Rebuild if necessary ``` **Email not sending** ```bash # Test SMTP configuration node -e "const smtp = require('nodemailer'); console.log(JSON.stringify(process.env, null, 2))" ``` **High memory usage** - Check for memory leaks: `node --inspect start` - Increase server RAM or split into multiple processes - Consider database optimization for large datasets **Database connection issues** ```bash # Test connection psql $DATABASE_URL # If PostgreSQL # Or sqlite3 dev.db ".tables" # If SQLite ``` --- ## Maintenance ### Regular Tasks **Daily:** - Monitor error logs - Check payment processing (Stripe dashboard) **Weekly:** - Backup database - Review admin activity logs - Check storage usage **Monthly:** - Update npm dependencies: `npm outdated` - Review security advisories: `npm audit` - Analyze financial reports **Quarterly:** - Security audit - Performance optimization - Dependency updates ### Updating ```bash # Pull latest code git pull # Update dependencies npm install # Sync database schema npm run db:push # Rebuild if needed npm run build ``` --- ## Security Hardening ### Before Going Live 1. **Change default credentials** - Admin username/password - Session secrets (32-byte random strings) 2. **Enable HTTPS** - Get certificate from Let's Encrypt (free) - Set `NEXT_PUBLIC_SITE_URL` to `https://yourdomain.com` 3. **Rate Limiting** - Enabled by default on login/checkout - Adjust in code if needed 4. **CAPTCHA** - Recommended on all public forms - Get free keys from Cloudflare Turnstile 5. **Email** - Use app-specific passwords (not your actual password) - Enable SMTP authentication 6. **Backups** - Daily automated backups - Test restore process quarterly --- ## Support & Issues - **Questions?** Check this guide again or search existing issues - **Bug report?** Create GitHub issue with reproduction steps - **Feature request?** Open an issue for discussion --- *Last updated: 2025-03-17*