Skip to content

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

Terminal window
# Clone the repository
git clone https://github.com/autimind/zserved.git
cd zserved
# Install dependencies
pnpm install
# Install Wrangler CLI globally
npm install -g wrangler
# Login to Cloudflare
wrangler login

2. Environment Configuration

Terminal window
# Copy environment template
cp .env.example .env
# Generate JWT secret
openssl rand -base64 32

Configure your .env file with required variables:

Terminal window
# Core Configuration
JWT_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 Services
RESEND_API_KEY="re-your-resend-api-key"
# Payment Processing
SQUARE_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:

Terminal window
# Create KV namespaces
wrangler kv namespace create "TENANTS"
wrangler kv namespace create "FILE_METADATA"
wrangler kv namespace create "SUPER_ADMIN_KV"
# Create D1 database
wrangler d1 create zserved-db
# Create R2 buckets
wrangler r2 bucket create serveros-files
# Create Vectorize indices
wrangler 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:

Terminal window
# Core schema
wrangler d1 execute zserved-db --file=migrations/schema.sql --remote
# Authentication & admin features
wrangler d1 execute zserved-db --file=migrations/admin-auth-schema.sql --remote
# Pricing & usage enforcement
wrangler d1 execute zserved-db --file=migrations/new-pricing-schema.sql --remote
# Super admin controls
wrangler d1 execute zserved-db --file=migrations/super-admin-schema.sql --remote
# AgentKit integration
wrangler d1 execute zserved-db --file=migrations/agentkit-schema.sql --remote
# DAO backing features
wrangler d1 execute zserved-db --file=migrations/dao-backing-schema.sql --remote

5. Secrets Configuration

Set up production secrets securely:

Terminal window
# Core secrets
wrangler secret put JWT_SECRET
wrangler secret put GITHUB_CLIENT_ID
wrangler secret put GITHUB_CLIENT_SECRET
wrangler secret put OPENAI_API_KEY
# Email & notifications
wrangler secret put RESEND_API_KEY
# Payment processing
wrangler secret put SQUARE_ACCESS_TOKEN
wrangler secret put SQUARE_WEBHOOK_SIGNATURE_KEY
# Super admin encryption
wrangler secret put SUPER_ADMIN_ENCRYPTION_KEY
wrangler secret put LEGAL_COMPLIANCE_KEY

Deployment Process

Main Platform Deployment

1. Backend (Workers) Deployment

Terminal window
# Deploy main worker
wrangler deploy
# Verify deployment
curl https://your-worker-url.workers.dev/api/health

2. Frontend (Pages) Deployment

Terminal window
# Build frontend
npm run build
# Deploy to Pages
wrangler 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

Terminal window
# Create tenant-specific worker
chmod +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

Terminal window
# Apply schema to tenant database
wrangler 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

Terminal window
# Set tenant-specific secrets
wrangler secret put JWT_SECRET --config wrangler.{tenant}.jsonc
wrangler secret put GITHUB_CLIENT_ID --config wrangler.{tenant}.jsonc
wrangler secret put OPENAI_API_KEY --config wrangler.{tenant}.jsonc

4. Tenant Frontend Deployment

Terminal window
# Deploy tenant-specific Pages
wrangler pages project create {tenant} --production-branch main
wrangler pages deploy dist --project-name {tenant}

Production Configuration

SSL & Domain Setup

1. Custom Domains

Terminal window
# Add custom domain to Pages
wrangler pages project {project-name} custom-domains add {domain.com}
# Add custom domain to Worker
wrangler 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:

Terminal window
# Platform health
curl https://your-domain.com/api/health
# Tenant health
curl https://tenant.your-domain.com/api/health

2. Analytics Configuration

Terminal window
# Set analytics environment variables
wrangler 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

Terminal window
# Export main database
wrangler d1 export zserved-db --output backup-main.sql
# Export tenant database
wrangler d1 export "zserved-db-{tenant}" --output backup-{tenant}.sql

File Storage Backups

Terminal window
# Sync R2 bucket to local storage
rclone sync r2:serveros-files ./backups/files/
# Sync tenant bucket
rclone sync r2:serveros-files-{tenant} ./backups/files-{tenant}/

Configuration Backups

Terminal window
# Export wrangler configuration
cp 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 indexes
CREATE 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:

Terminal window
# 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:

Terminal window
# Deploy to specific regions
wrangler deploy --compatibility-date 2024-01-01 --region eu,us
# Configure region-specific databases
wrangler d1 create zserved-db-eu --region eu
wrangler d1 create zserved-db-us --region us

Verification & Testing

Deployment Verification

Terminal window
# Test API endpoints
curl https://your-domain.com/api/health
curl https://your-domain.com/api/tenants
# Test authentication
curl -X POST https://your-domain.com/api/admin/auth \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"test123"}'
# Test file upload
curl -X POST https://your-domain.com/api/files/upload \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "file=@test-document.pdf"

Performance Testing

Terminal window
# Load testing with artillery
npm install -g artillery
artillery quick --count 10 --num 100 https://your-domain.com/api/health
# Database performance
wrangler d1 execute zserved-db --command "EXPLAIN QUERY PLAN SELECT * FROM jobs WHERE tenant_id = 'test';"

Security Testing

Terminal window
# SSL/TLS verification
curl -I https://your-domain.com
nmap --script ssl-enum-ciphers -p 443 your-domain.com
# Header security check
curl -I https://your-domain.com | grep -E "(X-Frame-Options|X-Content-Type-Options|Strict-Transport-Security)"

Troubleshooting

Common Issues

  1. Worker deployment fails:

    Terminal window
    # Check resource bindings
    wrangler whoami
    wrangler d1 list
    wrangler kv namespace list
  2. Database connection errors:

    Terminal window
    # Verify D1 binding
    wrangler d1 execute zserved-db --command "SELECT 1;"
  3. File upload failures:

    Terminal window
    # Check R2 bucket access
    wrangler r2 bucket list
  4. Authentication issues:

    Terminal window
    # Verify JWT secret is set
    wrangler secret list

Support Resources

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:

  1. Configure your first tenant - Follow the tenant setup guide
  2. Set up monitoring - Enable alerts and dashboards
  3. Configure integrations - Set up email, payments, and AI services
  4. Review security - Conduct security review and penetration testing
  5. Plan scaling - Prepare for growth with monitoring and alerts

For detailed configuration options, see the Configuration Guide.