Unclassified

Frontend-to-Backend Service Integration

Complete & Production-Ready
3 Profiles × 31 Services = Full Cloudflare Control from UI


Architecture Overview

apps/platform (Next.js Frontend)
    ↓
ProfileProvider (Context)
    ↓
useServices() Hook
    ↓
12 Service Clients (Tenants, Connectors, MCP, etc.)
    ↓
Gateway API → /api/v1/*
    ↓
31 Cloudflare Workers Services
    ↓
Neon (Control Plane) + D1 (Runtime)

What Was Built

1. Profile Context & Providers

File: lib/contexts/profile-context.tsx

Manages deployment profile switching:

  • Dev (95% SLA, TLS 1.2 + JWT)
  • Customer Zero (99.5% SLA, TLS 1.3 + mTLS)
  • External Users (99.9% SLA, TLS 1.3 + mTLS + pinning)

Each profile has:

  • Isolated data
  • Separate configuration
  • Own Cloudflare Worker deployments
  • Profile-specific MCP pools
const { activeProfile, setProfile } = useProfile();

// Switch profiles
await setProfile("customer-zero");

2. Tenant Schema Allocation

File: lib/services/tenant-schema.ts

Handles schema assignment during onboarding:

Core 10 Base Tenants (Dev & Customer Zero):

  • System, Admin, Support, Analytics, Compliance
  • Monitoring, Audit, Billing, Onboarding, Testing

Profile-Specific Tenants (External Users):

  • Custom per customer

Schema allocation:

await allocateTenantSchema({
  tenantId: "tenant-123",
  profile: "customer-zero",
  tenantName: "Acme Corp",
  tier: "enterprise",
  region: "us-east",
});
// Creates: schema_customer_zero_tenant_123_abc123

3. Tenant Onboarding Workflow

File: lib/services/tenant-onboarding.ts

5-step automated onboarding:

  1. Create Tenant — Register in tenants service
  2. Allocate Schema — Reserve database schema
  3. Create Admin User — Initialize tenant admin
  4. Setup Core Services — Deploy 10 base services
  5. Configure Profile Settings — Apply profile-specific config

Progress tracking with error recovery.

4. useServices() Hook

File: lib/hooks/useServices.ts

Single entry point for all backend operations:

const services = useServices();

// Tenants
await services.tenants.list();
await services.tenants.create("Acme Corp", "enterprise");
await services.tenants.update(id, { tier: "growth" });

// Connectors
await services.connectors.list();
await services.connectors.sync(connectorId);

// Admin
await services.admin.users.create(tenantId, "admin@example.com", "admin");
await services.admin.audit.list(tenantId);

// Governance
await services.governance.policies.list();
await services.governance.approvals.list();

// Observability
await services.observability.health();
await services.observability.metrics("request_count");

All calls automatically scoped to active profile.

5. Platform Pages Wired to Services

Tenants Page (app/(shell)/tenants/page.tsx)

  • Lists all tenants in profile
  • Profile-specific data isolation
  • Tier, status, creation date visible

Connectors Page (app/(shell)/connectors/page.tsx)

  • Shows integration connectors
  • Last sync timestamp
  • Connection status

Environment Page (app/(shell)/environment/page.tsx)

  • Cloudflare Workers Status — All 31 services
  • TLS Configuration — Shows active profile settings
  • Infrastructure Info — Data centers, backup regions
  • Metrics — Uptime, latency, worker count, Durable Objects

Onboarding Page (app/(shell)/onboarding/page.tsx)

  • Form to create new tenants
  • Region selection (us-east, eu-west, ap-south)
  • Tier selection (starter, growth, enterprise)
  • Real-time progress tracking

6. Profile Switcher Component

File: components/profile-switcher.tsx

UI to switch deployment profiles with:

  • Current profile indicator
  • SLA information
  • TLS/mTLS status
  • Live configuration display

Data Isolation Per Profile

Dev Profile

  • 10 core tenants (shared base)
  • 95% SLA guarantee
  • TLS 1.2 + JWT auth
  • Single region (us-east)
  • Internal only

Customer Zero Profile

  • 10 core tenants (same as dev)
  • 99.5% SLA guarantee
  • TLS 1.3 + mTLS certificates
  • Primary region + backup
  • First paying customer

External Users Profile

  • Variable custom tenants
  • 99.9% SLA guarantee
  • TLS 1.3 + mTLS + certificate pinning
  • 5 regions (multi-region failover)
  • Public production

How Frontend Controls Cloudflare

1. Profile Selection

// UI switches profile
await setProfile("external-users");
// All subsequent service calls route to external-users workers

2. Service Operations

// Create connector → integration-management-mcp worker
await services.connectors.create("Salesforce", config);

// Execute capability → iw-agent-runtime worker
await services.capabilities.execute(capabilityId, params);

// Update governance → twin-orchestrator worker
await services.governance.policies.create("rate-limit", rules);

3. Environment Control

// Check all 31 workers' health
const health = await services.observability.health();
// Returns: status of gateway, tenants, admin, connectors, mcp-pool,
//          spine, knowledge, continuity, agents, etc.

4. Tenant Onboarding

// Complete workflow with schema allocation
const result = await onboardTenant({
  tenantName: "Acme Corp",
  adminEmail: "admin@acme.com",
  profile: "customer-zero",
  region: "eu-west",
  tier: "enterprise",
});
// Allocates schema: schema_customer_zero_acmecorp_abc123
// Creates all 10 base tenants automatically

File Structure

apps/platform/
├── lib/
│   ├── services/
│   │   ├── index.ts                    # Service client exports
│   │   ├── types.ts                    # BaseServiceClient
│   │   ├── gateway.ts                  # Gateway routing
│   │   ├── tenants.ts                  # Tenant lifecycle
│   │   ├── admin.ts                    # Users & roles
│   │   ├── connectors.ts               # Integrations
│   │   ├── mcp.ts                      # MCP registry
│   │   ├── capabilities.ts             # Agent workflows
│   │   ├── knowledge.ts                # Docs & search
│   │   ├── memory.ts                   # Session continuity
│   │   ├── governance.ts               # Policies & approvals
│   │   ├── observability.ts            # Health & metrics
│   │   ├── spine.ts                    # Entity management
│   │   ├── agents.ts                   # Agent deployment
│   │   ├── tenant-schema.ts            # Schema allocation
│   │   └── tenant-onboarding.ts        # Onboarding workflow
│   ├── contexts/
│   │   └── profile-context.tsx         # Profile provider
│   └── hooks/
│       └── useServices.ts              # Main service hook
├── components/
│   └── profile-switcher.tsx            # Profile UI
└── app/(shell)/
    ├── tenants/page.tsx                # Tenant management
    ├── connectors/page.tsx             # Connector control
    ├── environment/page.tsx            # CF environment dashboard
    └── onboarding/page.tsx             # Tenant onboarding

Usage Example: End-to-End Flow

'use client'


  const { activeProfile, setProfile } = useProfile()
  const services = useServices()

  // 1. Switch to customer-zero profile
  const handleSwitchProfile = async () => {
    await setProfile('customer-zero')
  }

  // 2. List all tenants in active profile
  const handleListTenants = async () => {
    const tenants = await services.tenants.list()
    console.log('Tenants:', tenants)
  }

  // 3. Onboard new tenant
  const handleOnboard = async () => {
    const result = await onboardTenant({
      tenantName: 'New Customer',
      adminEmail: 'admin@newcustomer.com',
      profile: activeProfile,
      region: 'us-east',
      tier: 'growth',
    })
    console.log('Tenant created:', result.tenantId)
  }

  // 4. Check environment health
  const handleCheckHealth = async () => {
    const health = await services.observability.health()
    console.log('Environment health:', health)
  }

  return (
    <div className="space-y-4">
      <button onClick={handleSwitchProfile}>Switch Profile</button>
      <button onClick={handleListTenants}>List Tenants</button>
      <button onClick={handleOnboard}>Onboard Tenant</button>
      <button onClick={handleCheckHealth}>Check Health</button>
    </div>
  )
}

Key Features

✅ Profile-Scoped Operations — All service calls scoped to active profile
✅ Automatic Data Isolation — Dev, Customer Zero, External Users data never mixed
✅ Complete Cloudflare Control — 31 services managed from frontend
✅ Tenant Schema Allocation — Automatic during onboarding
✅ 10 Base Tenants — Pre-configured for Dev & Customer Zero
✅ Observability Dashboard — Real-time health & metrics
✅ Error Handling — ServiceErrorClass with retry support
✅ Type Safety — Full TypeScript with JSDoc


Ready For

✅ Phase 1: Platform Implementation (Week 1)
✅ Phase 2: Multi-tenant deployment
✅ Phase 3: External user rollout

All frontend-to-backend service wiring complete.