{"slug":"operations/TENANT_ROUTING_IMPLEMENTATION","title":"Subdomain-Based Tenant Routing Implementation","section":"operations","sectionLabel":"Operations","status":"unclassified","type":"document","path":"operations/TENANT_ROUTING_IMPLEMENTATION.mdx","bytes":10112,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n## Overview\n\nThis implementation adds multi-tenant support to IntegrateWise via subdomain-based routing. Each tenant lives on its own subdomain (e.g., `saas-corp.integratewise.com`) and serves a branded landing page. The middleware handles subdomain resolution and tenant context injection, making all downstream code automatically tenant-scoped.\n\n## Architecture\n\n### 1. Schema Extensions (`lib/data/types.ts`)\n\nExtended the `Tenant` interface with branding and landing configuration:\n\n```typescript\ninterface Tenant {\n  id: string;\n  name: string;\n  slug: string; // DNS-safe subdomain identifier\n  industry: Industry;\n  environment: Environment;\n  branding?: {\n    logoUrl?: string; // Emoji or URL\n    primaryColor?: string; // Hex color\n    backgroundColor?: string; // Hex color\n    tagline?: string;\n  };\n  landing?: {\n    headline?: string;\n    subhead?: string;\n    featuredPluginIds?: string[];\n    featuredAgentIds?: string[];\n  };\n  customDomain?: string; // Optional CNAME support\n  status: \"active\" | \"suspended\" | \"provisioning\";\n}\n```\n\nExtended `TenantRepo` interface with new methods:\n\n- `getBySlug(slug)` — lookup tenant by subdomain slug\n- `update(tenantId, updates)` — update tenant branding/landing config\n- `validateSlug(slug)` — validate DNS-safe slug and check uniqueness\n\n### 2. Data Provider Updates (`lib/data/in-memory-provider.ts`)\n\n- Added reserved slug validation (www, app, api, admin, docs, etc.)\n- DNS-safe slug regex validation: `^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`\n- Seed tenants with branding configuration:\n  - **saas-corp**: Blue (#3B82F6), SaaS-focused\n  - **healthtech**: Green (#10B981), Healthcare-focused\n  - **fintech-solutions**: Purple (#8B5CF6), Financial-focused\n- Implemented `InMemoryTenantRepo` methods for CRUD and slug validation\n- Added seed initialization in DataProvider constructor\n\n### 3. Middleware Enhancement (`middleware.ts`)\n\nEnhanced middleware to handle both role subdomains (existing) and tenant subdomains (new):\n\n**Routing logic:**\n\n1. Extract subdomain from Host header\n2. Check if role subdomain (founder, sales, etc.) → rewrite to `/workbench/[role]`\n3. Check if reserved subdomain → allow `app`, deny others\n4. Look up tenant by slug from seed data\n5. If found → inject `X-Tenant-Slug` and `X-Tenant-Id` headers\n6. If not found → rewrite to 404 \"workspace not found\"\n7. Local dev support: `*.localhost:3000` resolves to tenant subdomains\n\n**Reserved subdomains:** www, app, api, admin, docs, localhost, staging, dev, mail, smtp, ftp\n\n### 4. Tenant Context & Providers\n\n**TenantProvider** (`lib/context/tenant-context.tsx`):\n\n- React context for tenant state management\n- Reads `X-Tenant-Slug` from request headers\n- Loads tenant data from DataProvider\n- Provides `useTenant()` and `useTenantContext()` hooks\n- Handles loading and error states\n\n**Tenant Route Group** (`app/(tenant)/layout.tsx`):\n\n- Wraps all tenant-scoped routes with TenantProvider\n- Automatically injects tenant context to all children\n- All server components inside automatically receive tenant scope\n\n### 5. Per-Tenant Landing Page\n\n**TenantLandingPage** (`components/tenant/landing-page.tsx`):\n\nModern, polished landing page with:\n\n- **Responsive navigation** with tenant logo, name, and auth status\n- **Hero section** with customizable headline/subhead and CTA\n- **Features grid** showing 4 key capabilities\n- **Industry-specific section** with stats (templates, integrations, team members)\n- **Call-to-action section** with context-aware messaging\n- **Footer** with links and copyright\n\nDesign patterns from v0 templates:\n\n- CSS variables for tenant branding (primary color, background)\n- Smooth transitions and hover effects\n- Semantic HTML and accessibility\n- Mobile-first responsive design\n- Auth-aware routing (sign-out → sign-in; onboarded → /work; not-onboarded → /onboarding)\n\n### 6. Tenant Picker Page\n\n**TenantPicker** (`components/tenant/tenant-picker.tsx`):\n\nWorkspace selection hub served at `app.integratewise.com`:\n\n- Lists all active tenants with branding\n- Displays tenant logo, name, industry, tagline, status\n- Hover effects showing navigation intent\n- Status indicator (active/suspended/provisioning)\n- Empty state with helpful messaging\n- Call-to-action for workspace creation\n\n### 7. Routes Created\n\n```\n(tenant)/                          # Tenant-scoped route group\n  layout.tsx                       # TenantProvider wrapper\n  page.tsx                         # Per-tenant branded landing\n\napp/                               # Reserved subdomain (app.integratewise.com)\n  page.tsx                         # Tenant picker\n```\n\n### 8. Routing Model\n\n```\nintegratewise.com            → public ecosystem (future: marketplace, docs, etc.)\nwww.integratewise.com        → same as apex\n{tenant}.integratewise.com   → tenant landing page + app entry\napp.integratewise.com        → tenant picker (lists workspaces user can access)\n*.localhost:3000             → local dev equivalent (tenant.localhost)\n```\n\n## Data Flow\n\n1. **Request arrives** → middleware extracts subdomain\n2. **Tenant lookup** → middleware finds tenant by slug from DataProvider\n3. **Header injection** → middleware injects `X-Tenant-Slug` and `X-Tenant-Id`\n4. **Route match** → Next.js routes to `(tenant)` group\n5. **TenantProvider mounts** → reads headers and loads tenant from DataProvider\n6. **Context available** → all child components access tenant via `useTenant()`\n7. **Branding applied** → CSS variables apply tenant colors/logo\n8. **Auth-aware navigation** → page routes based on user session state\n\n## Key Features\n\n### Branding System\n\n- CSS variables for dynamic theming: `--primary-color`, `--background-color`\n- Tenant-specific logo, tagline, and visual identity\n- Consistent branding across landing page via design tokens\n\n### Industry Awareness\n\n- Landing copy customized by industry (SaaS/Healthcare/Fintech)\n- Pre-populated section headlines and feature descriptions\n- Differentiated messaging for each workspace type\n\n### Auth-Aware Routing\n\n- Unsigned users: redirect to sign-in\n- Signed-in, not-onboarded: redirect to onboarding\n- Signed-in, onboarded: redirect to workspace dashboard\n- Each page state has clear CTA\n\n### Fallback Defaults\n\n- Tenants without custom branding get clean defaults\n- Default colors: blue (#3B82F6)\n- Default background: light blue (#F0F9FF)\n- Sensible fallback copy and layouts\n\n## Seed Data\n\nThree demo tenants ship with the implementation:\n\n| Slug              | Name              | Industry   | Primary Color | Logo |\n| ----------------- | ----------------- | ---------- | ------------- | ---- |\n| saas-corp         | SaaS Corp         | saas       | #3B82F6       | 🚀   |\n| healthtech        | HealthTech Inc    | healthcare | #10B981       | ⚕️   |\n| fintech-solutions | Fintech Solutions | fintech    | #8B5CF6       | 💰   |\n\nEach includes:\n\n- Custom branding (color, background, tagline)\n- Industry-aware landing copy\n- Active status\n\n## Testing\n\n### Local Development\n\nAccess tenants via subdomains on localhost:\n\n- `http://saas-corp.localhost:3000`\n- `http://healthtech.localhost:3000`\n- `http://fintech-solutions.localhost:3000`\n- `http://app.localhost:3000` → tenant picker\n\n### Verification Checklist\n\n1. ✅ Subdomain resolves to tenant landing page\n2. ✅ Branding (colors, logo, copy) applied correctly\n3. ✅ Auth-aware navigation works (signed out → sign-in CTA)\n4. ✅ Tenant picker shows all active tenants\n5. ✅ Unknown subdomain returns 404\n6. ✅ Reserved subdomains (www, api, etc.) blocked\n7. ✅ Role subdomains still work (founder.localhost → /workbench/founder)\n\n## Integration Points\n\nAll existing features automatically benefit from tenant scoping:\n\n- **DataProvider**: All data queries automatically scoped to tenant (via `X-Tenant-Id` header)\n- **Work Router**: Resolves capabilities within tenant scope\n- **Onboarding**: Pre-fills tenant context\n- **Authentication**: Sessions remain tenant-aware\n\n## Production Considerations\n\n### Custom Domains\n\nThe `customDomain` field supports CNAME mappings (e.g., `acme.com` → `acme.integratewise.com`). Implementation requires:\n\n- DNS validation flow\n- Middleware enhancement to handle custom domain → slug lookup\n- SSL certificate provisioning (via Vercel)\n\n### Database Integration\n\nCurrent implementation uses in-memory storage for development. For production:\n\n1. Move tenant data to persistent database (Neon PostgreSQL)\n2. Add caching layer for slug → tenant lookups (Redis or in-process LRU)\n3. Implement slug availability checking in admin API\n4. Add tenant creation/deletion endpoints\n\n### Admin Interface\n\nFuture enhancement for tenant provisioning:\n\n- Create workspace (validate slug, generate branding options)\n- Edit branding and landing config\n- Manage team members and permissions\n- Monitor tenant health and usage\n\n## Files Changed\n\n### New Files\n\n- `lib/context/tenant-context.tsx` — Tenant context provider\n- `lib/tenant-lookup.ts` — Tenant lookup utility (optional)\n- `components/tenant/landing-page.tsx` — Branded landing page\n- `components/tenant/tenant-picker.tsx` — Workspace picker\n- `app/(tenant)/layout.tsx` — Tenant route group layout\n- `app/(tenant)/page.tsx` — Tenant landing route\n- `app/app/page.tsx` — Tenant picker route\n\n### Modified Files\n\n- `lib/data/types.ts` — Extended Tenant interface and TenantRepo\n- `lib/data/in-memory-provider.ts` — Added seed tenants, validation, new methods\n- `middleware.ts` — Enhanced for tenant subdomain routing\n\n## Performance\n\n- **Lazy tenant lookup**: Tenants loaded on first request via context provider\n- **In-memory caching**: Seed data cached in DataProvider\n- **Header-based routing**: No additional database queries in middleware\n- **CSS variable theming**: No re-renders for branding application\n\n## Security\n\n- DNS-safe slug validation prevents injection attacks\n- Reserved subdomain list prevents conflicts\n- Header injection via middleware ensures tenant context integrity\n- Future: RLS policies on database ensure tenant data isolation\n"}