Installation & Deployment
Installation & Deployment
This guide covers the complete installation and deployment process for ZServed platform, from local development to production deployment with enterprise-grade security and multi-tenant isolation.
Prerequisites
System Requirements
Minimum Requirements:
- Node.js 18.x or higher
- npm 9.x or pnpm 8.x
- Git 2.x
- Cloudflare account with Workers enabled
Recommended Production:
- Node.js 20.x LTS
- pnpm 8.x (for faster installs)
- Docker (for local development)
- SSL certificates for custom domains
Cloudflare Services
Ensure access to the following Cloudflare services:
- Workers - Application runtime
- Pages - Frontend hosting
- D1 - Database storage
- R2 - File storage
- KV - Key-value storage
- Vectorize - AI embeddings
- Workers AI - AI model inference
Installation Process
1. Repository Setup
# Clone the repositorygit clone https://github.com/autimind/zserved.gitcd zserved
# Install dependenciespnpm install
# Install Wrangler CLI globallynpm install -g wrangler
# Login to Cloudflarewrangler login
2. Environment Configuration
# Copy environment templatecp .env.example .env
# Generate JWT secretopenssl rand -base64 32
Configure your .env
file with required variables:
# Core ConfigurationJWT_SECRET="your-generated-jwt-secret"GITHUB_CLIENT_ID="your-github-oauth-app-id"GITHUB_CLIENT_SECRET="your-github-oauth-secret"OPENAI_API_KEY="sk-your-openai-api-key"
# Email ServicesRESEND_API_KEY="re-your-resend-api-key"
# Payment ProcessingSQUARE_APPLICATION_ID="your-square-app-id"SQUARE_ACCESS_TOKEN="your-square-access-token"SQUARE_LOCATION_ID="your-square-location-id"SQUARE_ENVIRONMENT="production"
3. Cloudflare Resource Creation
Create all required Cloudflare resources:
# Create KV namespaceswrangler kv namespace create "TENANTS"wrangler kv namespace create "FILE_METADATA"wrangler kv namespace create "SUPER_ADMIN_KV"
# Create D1 databasewrangler d1 create zserved-db
# Create R2 bucketswrangler r2 bucket create serveros-files
# Create Vectorize indiceswrangler vectorize create document-embeddings \ --dimensions=1536 \ --metric=cosine
wrangler vectorize create client-metadata \ --dimensions=1536 \ --metric=cosine
4. Database Schema Setup
Apply database schemas in the correct order:
# Core schemawrangler d1 execute zserved-db --file=migrations/schema.sql --remote
# Authentication & admin featureswrangler d1 execute zserved-db --file=migrations/admin-auth-schema.sql --remote
# Pricing & usage enforcementwrangler d1 execute zserved-db --file=migrations/new-pricing-schema.sql --remote
# Super admin controlswrangler d1 execute zserved-db --file=migrations/super-admin-schema.sql --remote
# AgentKit integrationwrangler d1 execute zserved-db --file=migrations/agentkit-schema.sql --remote
# DAO backing featureswrangler d1 execute zserved-db --file=migrations/dao-backing-schema.sql --remote
5. Secrets Configuration
Set up production secrets securely:
# Core secretswrangler secret put JWT_SECRETwrangler secret put GITHUB_CLIENT_IDwrangler secret put GITHUB_CLIENT_SECRETwrangler secret put OPENAI_API_KEY
# Email & notificationswrangler secret put RESEND_API_KEY
# Payment processingwrangler secret put SQUARE_ACCESS_TOKENwrangler secret put SQUARE_WEBHOOK_SIGNATURE_KEY
# Super admin encryptionwrangler secret put SUPER_ADMIN_ENCRYPTION_KEYwrangler secret put LEGAL_COMPLIANCE_KEY
Deployment Process
Main Platform Deployment
1. Backend (Workers) Deployment
# Deploy main workerwrangler deploy
# Verify deploymentcurl https://your-worker-url.workers.dev/api/health
2. Frontend (Pages) Deployment
# Build frontendnpm run build
# Deploy to Pageswrangler pages deploy dist
# Set custom domain (optional)wrangler pages project create zserved --production-branch main
Multi-Tenant Deployment
For each tenant (law firm), create isolated resources:
1. Tenant Worker Deployment
# Create tenant-specific workerchmod +x scripts/deploy-tenant-worker.sh./scripts/deploy-tenant-worker.sh {tenant-name}
This script automatically creates:
- Isolated Cloudflare Worker
- Dedicated D1 database
- Separate KV namespaces
- Isolated R2 bucket
- Dedicated Vectorize index
2. Tenant Database Setup
# Apply schema to tenant databasewrangler d1 execute "zserved-db-{tenant}" --file=migrations/schema.sql --remote
# Seed demo data (if needed)wrangler d1 execute "zserved-db-{tenant}" --file=scripts/seed-demo-data.sql --remote
3. Tenant Secrets Configuration
# Set tenant-specific secretswrangler secret put JWT_SECRET --config wrangler.{tenant}.jsoncwrangler secret put GITHUB_CLIENT_ID --config wrangler.{tenant}.jsoncwrangler secret put OPENAI_API_KEY --config wrangler.{tenant}.jsonc
4. Tenant Frontend Deployment
# Deploy tenant-specific Pageswrangler pages project create {tenant} --production-branch mainwrangler pages deploy dist --project-name {tenant}
Production Configuration
SSL & Domain Setup
1. Custom Domains
# Add custom domain to Pageswrangler pages project {project-name} custom-domains add {domain.com}
# Add custom domain to Workerwrangler route add "{domain.com}/*" {worker-name}
2. SSL Certificates
Cloudflare automatically provisions SSL certificates for:
- Main platform domain
- Tenant custom domains
- Subdomain routing
Security Hardening
1. Security Headers
Configured automatically in the platform:
const securityHeaders = { 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'};
2. Rate Limiting
Built-in rate limiting protects against abuse:
const rateLimits = { api: '100 requests/minute', auth: '5 attempts/15 minutes', uploads: '20 files/hour'};
3. Content Security Policy
const csp = "default-src 'self'; script-src 'self' 'unsafe-inline' https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;";
Monitoring Setup
1. Health Checks
Built-in health monitoring:
# Platform healthcurl https://your-domain.com/api/health
# Tenant healthcurl https://tenant.your-domain.com/api/health
2. Analytics Configuration
# Set analytics environment variableswrangler secret put PUBLIC_GOOGLE_ANALYTICS_ID
3. Error Tracking
Automatic error logging to Cloudflare Analytics:
const errorTracking = { logLevel: 'error', includeStackTrace: true, alertThresholds: { errorRate: 5, // 5% error rate responseTime: 5000 // 5 second response time }};
Backup & Recovery
Database Backups
# Export main databasewrangler d1 export zserved-db --output backup-main.sql
# Export tenant databasewrangler d1 export "zserved-db-{tenant}" --output backup-{tenant}.sql
File Storage Backups
# Sync R2 bucket to local storagerclone sync r2:serveros-files ./backups/files/
# Sync tenant bucketrclone sync r2:serveros-files-{tenant} ./backups/files-{tenant}/
Configuration Backups
# Export wrangler configurationcp wrangler.jsonc backups/config/cp wrangler.{tenant}.jsonc backups/config/
# Export environment variables (without secrets)env | grep PUBLIC_ > backups/config/env-public.txt
Performance Optimization
Caching Strategy
const cachingConfig = { static: { maxAge: 86400, // 1 day staleWhileRevalidate: 3600 // 1 hour }, api: { maxAge: 300, // 5 minutes staleWhileRevalidate: 60 // 1 minute }};
Database Optimization
-- Apply performance indexesCREATE INDEX IF NOT EXISTS idx_jobs_tenant_status ON jobs(tenant_id, status);CREATE INDEX IF NOT EXISTS idx_files_tenant_created ON files(tenant_id, created_at);CREATE INDEX IF NOT EXISTS idx_events_job_created ON events(job_id, created_at);
CDN Configuration
Cloudflare CDN is automatically configured with:
- Global edge caching
- Smart compression
- Image optimization
- Browser caching directives
Scaling Considerations
Horizontal Scaling
The platform automatically scales through:
- Workers: Auto-scaling compute with zero cold starts
- D1: Automatic read replicas for high availability
- R2: Unlimited storage with global distribution
- Vectorize: Auto-scaling AI inference
Vertical Scaling
Resource limits can be increased:
# Increase CPU time (if needed)# Contact Cloudflare support for enterprise limits
# Increase memory limits# Configured automatically based on usage patterns
Multi-Region Deployment
For global deployment:
# Deploy to specific regionswrangler deploy --compatibility-date 2024-01-01 --region eu,us
# Configure region-specific databaseswrangler d1 create zserved-db-eu --region euwrangler d1 create zserved-db-us --region us
Verification & Testing
Deployment Verification
# Test API endpointscurl https://your-domain.com/api/healthcurl https://your-domain.com/api/tenants
# Test authenticationcurl -X POST https://your-domain.com/api/admin/auth \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"test123"}'
# Test file uploadcurl -X POST https://your-domain.com/api/files/upload \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -F "file=@test-document.pdf"
Performance Testing
# Load testing with artillerynpm install -g artilleryartillery quick --count 10 --num 100 https://your-domain.com/api/health
# Database performancewrangler d1 execute zserved-db --command "EXPLAIN QUERY PLAN SELECT * FROM jobs WHERE tenant_id = 'test';"
Security Testing
# SSL/TLS verificationcurl -I https://your-domain.comnmap --script ssl-enum-ciphers -p 443 your-domain.com
# Header security checkcurl -I https://your-domain.com | grep -E "(X-Frame-Options|X-Content-Type-Options|Strict-Transport-Security)"
Troubleshooting
Common Issues
-
Worker deployment fails:
Terminal window # Check resource bindingswrangler whoamiwrangler d1 listwrangler kv namespace list -
Database connection errors:
Terminal window # Verify D1 bindingwrangler d1 execute zserved-db --command "SELECT 1;" -
File upload failures:
Terminal window # Check R2 bucket accesswrangler r2 bucket list -
Authentication issues:
Terminal window # Verify JWT secret is setwrangler secret list
Support Resources
- Documentation: docs.zserved.com
- GitHub Issues: github.com/autimind/zserved/issues
- Cloudflare Support: support.cloudflare.com
Maintenance Tasks
Regular maintenance schedule:
- Daily: Monitor error rates and response times
- Weekly: Review security logs and update dependencies
- Monthly: Database cleanup and backup verification
- Quarterly: Security audit and performance review
Next Steps
After successful deployment:
- Configure your first tenant - Follow the tenant setup guide
- Set up monitoring - Enable alerts and dashboards
- Configure integrations - Set up email, payments, and AI services
- Review security - Conduct security review and penetration testing
- Plan scaling - Prepare for growth with monitoring and alerts
For detailed configuration options, see the Configuration Guide.