Skip to main content

Frontend Architecture

ReptiDex’s frontend architecture is designed for scalability, maintainability, and optimal user experience across multiple applications while maximizing code reuse through strategic shared packages.

Frontend Strategy

Architecture Principles

  1. Application-Per-User-Journey: Separate applications for distinct user workflows and optimization needs
  2. Minimal Package Complexity: Keep shared packages to essential UI and core business logic only
  3. Service-Aligned: Frontend applications align with backend service boundaries where logical
  4. Performance-First: Optimize bundle sizes and loading patterns per application type
  5. Design System Consistency: Unified UI/UX across all applications through shared components

User-Centric Design

Breeder Journey: Comprehensive workspace for managing breeding operations and sales Buyer Journey: Streamlined discovery and purchasing experience Admin Journey: Powerful administrative tools for platform management Public Journey: SEO-optimized marketing and discovery experience

Frontend Applications

Core Applications (4)

web-public

Marketing, Discovery & PurchasingUsers: Anonymous visitors, potential buyers Technology: Vite + React 19 + Tailwind CSS Deployment: CDN-optimized for global performanceKey Features:
  • Landing pages and marketing content
  • Public animal browsing and search
  • Pedigree viewing and breeder discovery
  • Animal purchasing and inquiry flows
  • SEO-optimized pages for search visibility

web-breeder

Breeder Workspace & Sales ManagementUsers: Authenticated breeders, organization members Technology: Vite + React 19 + Tailwind CSS Deployment: Authentication-required workspaceKey Features:
  • Animal records and lineage management
  • Breeding pairs and clutch tracking
  • Inventory management and sales listings
  • Analytics and breeding insights
  • Organization and team collaboration

web-admin

Administrative InterfaceUsers: ReptiDex administrators, support staff Technology: Vite + React 19 + Tailwind CSS Deployment: Internal admin-only accessKey Features:
  • User and organization management
  • Content moderation and abuse handling
  • System monitoring and analytics
  • Feature flag and configuration management
  • Support tools and customer assistance

web-embed

Embeddable WidgetsUsers: Website visitors on breeder sites Technology: Vite + React (minimal bundle) Deployment: CDN for external integrationKey Features:
  • Pedigree tree widgets
  • Breeder profile cards
  • Animal listing grids
  • Contact forms and inquiry widgets
  • Minimal footprint for external sites

Shared Package Strategy

Simplified Package Architecture

ReptiDex uses a minimal shared package approach to balance code reuse with maintenance simplicity.
Single comprehensive UI and design system packageComponents:
  • Radix UI primitives with Tailwind CSS styling
  • Complete component library (Button, Form, Modal, Table, etc.)
  • Design tokens and brand guidelines
  • Icon library and asset management
  • Typography and spacing systems
Benefits:
  • Single source of truth for all UI components
  • Consistent design across all applications
  • Easy theme updates and brand changes
  • Simplified dependency management
// Usage across applications
import { Button, AnimalCard, PedigreeTree, cn } from '@reptidex/ui'

export default function App() {
  return (
    <div className="min-h-screen bg-background">
      <AnimalCard animal={animal} />
      <PedigreeTree pedigree={pedigree} />
    </div>
  )
}
Comprehensive business logic and integration packageAPI Clients:
  • Generated TypeScript clients for all 6 backend services
  • Request/response types and validation
  • Error handling and retry logic
Business Logic:
  • TypeScript interfaces for all business entities
  • Reptile-specific utilities (genetics, morphs, taxonomy)
  • Authentication and permission management
  • State management patterns (Zustand + React Query)
Utilities:
  • Date formatting and validation helpers
  • Constants, enums, and configuration
  • Common React hooks and patterns
// API Client usage
import { reptidexApi } from '@reptidex/core'

const animals = await reptidexApi.business.getAnimals({
  organizationId: 'org_123',
  species: 'ball_python'
})

// Business logic usage  
import { calculateGeneticProbability, morphUtils } from '@reptidex/core'

const offspring = calculateGeneticProbability(sire, dam)
const morphDisplay = morphUtils.formatMorphString(animal.morphs)
Minimal package for external widget integrationPurpose: Ultra-lightweight components for external websites Bundle Size: < 50KB gzipped Dependencies: Minimal (no heavy UI libraries, optimized React)Components:
  • Standalone pedigree viewer
  • Simple animal profile cards
  • Contact forms and inquiry widgets
  • Minimal styling and theming
// Lightweight embed usage
import { EmbedPedigree, EmbedAnimalCard } from '@reptidex/embed'

// Can be used on any external website
<EmbedPedigree animalId="animal_123" />
<EmbedAnimalCard animalId="animal_456" />

Frontend-to-Backend Integration

Service Communication Patterns

Application-Specific Service Usage

ApplicationPrimary ServicesSecondary Services
web-publicrepti-engagement, repti-businessrepti-media, repti-core
web-breederrepti-business, repti-corerepti-commerce, repti-media
web-adminrepti-operations, repti-coreAll services (admin access)
web-embedrepti-business, repti-mediarepti-core (minimal auth)

Technology Stack

Core Technologies

Frontend Framework

Vite for fast builds and HMR
React 19 with concurrent features
TypeScript for type safety
Radix UI + Tailwind CSS for components

State Management

Zustand for global state
React Query for server state
React Hook Form for form management
Zod for validation schemas

Development Tools

Build & Development

Vite for fast development builds
ESLint + Prettier for code quality
Storybook for component development
Vitest + Testing Library for testing

Deployment

Static hosting for frontend apps
CloudFront CDN for global distribution
GitHub Actions for CI/CD
Docker for containerized environments

Application Architecture Patterns

Authentication & Authorization

// Shared authentication pattern via @reptidex/core
import { useAuth, withAuth } from '@reptidex/core'

export default function BreederDashboard() {
  const { user, organization, permissions } = useAuth()
  
  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold mb-4">Welcome, {user.name}</h1>
      {permissions.canManageAnimals && <AnimalManagement />}
    </div>
  )
}

// Route protection
export default withAuth(BreederDashboard, {
  requireAuth: true,
  requiredPermissions: ['animals:read']
})

State Management Pattern

// Zustand store with React Query integration
import { create } from 'zustand'
import { useQuery } from '@tanstack/react-query'
import { reptidexApi } from '@reptidex/core'

// Global UI state
export const useUIStore = create((set) => ({
  sidebarOpen: false,
  currentOrganization: null,
  toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen }))
}))

// Server state with React Query
export function useAnimals(organizationId: string) {
  return useQuery({
    queryKey: ['animals', organizationId],
    queryFn: () => reptidexApi.business.getAnimals({ organizationId }),
    staleTime: 5 * 60 * 1000 // 5 minutes
  })
}

Error Handling Strategy

// Global error boundary with user-friendly messaging
import { ErrorBoundary } from '@reptidex/ui'
import { BrowserRouter as Router } from 'react-router-dom'

export default function App() {
  return (
    <div className="min-h-screen bg-background">
      <ErrorBoundary
        fallback={<ErrorFallback />}
        onError={(error, errorInfo) => {
          // Log to monitoring service
          console.error('Application error:', error, errorInfo)
        }}
      >
        <Router>
          <Routes />
        </Router>
      </ErrorBoundary>
    </div>
  )
}

// API error handling in @reptidex/core
export const reptidexApi = {
  business: {
    getAnimals: async (params) => {
      try {
        const response = await fetch('/api/animals', { ... })
        if (!response.ok) throw new ApiError(response)
        return response.json()
      } catch (error) {
        throw new ApiError('Failed to fetch animals', error)
      }
    }
  }
}

Performance Optimization

Bundle Optimization

Code Splitting: Each application loads only required code
// Dynamic imports for large components
const PedigreeVisualization = lazy(() => import('./PedigreeVisualization'))
const AdvancedAnalytics = lazy(() => import('./AdvancedAnalytics'))
Tree Shaking: Dead code elimination across shared packages
// Import only needed functions
import { formatDate, validateEmail } from '@reptidex/core/utils'
// Instead of importing entire utils package
Asset Optimization: Images, fonts, and media optimized per application
  • web-public: Heavy focus on image optimization for marketing
  • web-breeder: Optimized for data-heavy interfaces
  • web-embed: Minimal assets for fast external loading

Caching Strategy

Static Assets: Long-term caching with version hashing API Responses: React Query caching with intelligent invalidation CDN Distribution: Global edge caching for public content

Development Workflow

Monorepo Structure

frontend/
├── apps/
│   ├── web-public/          # Marketing and discovery app
│   ├── web-breeder/         # Breeder workspace app  
│   ├── web-admin/           # Administrative interface
│   └── web-embed/           # Embeddable widgets
├── packages/
│   ├── ui/                  # @reptidex/ui components
│   ├── core/                # @reptidex/core business logic
│   └── embed/               # @reptidex/embed (optional)
├── tools/
│   ├── eslint-config/       # Shared linting rules
│   ├── typescript-config/   # Shared TS configuration
│   └── build-tools/         # Build and deployment scripts
└── docs/
    ├── storybook/           # Component documentation
    └── api-docs/            # API integration guides

Development Commands

# Start all applications in development
pnpm dev

# Start specific application
pnpm dev:public
pnpm dev:breeder
pnpm dev:admin

# Build shared packages
pnpm build:packages

# Run tests across all applications
pnpm test

# Build for production
pnpm build:all

Security Considerations

Authentication Security

JWT Token Management: Secure storage and automatic refresh Route Protection: Application-level and component-level guards Permission Checking: Granular permission validation via @reptidex/core

Content Security

Input Validation: All user inputs validated with Zod schemas XSS Prevention: Radix UI components with built-in protections CSRF Protection: Vite apps with SameSite cookies and CSRF tokens

External Widget Security

Embed Security: web-embed widgets use minimal permissions Domain Restrictions: Configurable allowed domains for widget embedding Content Isolation: Widgets cannot access parent page content

Future Expansion

Planned Enhancements

Mobile PWA: Dedicated mobile application for native-like experience Desktop App: Electron wrapper for offline breeding management Browser Extensions: Quick access tools for external marketplaces

Architecture Evolution

Micro-Frontends: Consider micro-frontend architecture if team scaling requires it Edge Computing: Move more logic to edge for global performance AI Integration: Frontend components for genetics prediction and breeding recommendations