Project Architecture Overview 🏗️

Understanding CrittrHavens' technical foundation. A comprehensive guide to the application's architecture, patterns, and design decisions for developers.

Developer working on code with multiple monitors showing programming interfaces

Architecture at a Glance

CrittrHavens is a modern Progressive Web App built for reptile and amphibian care management.

Tech Stack Overview

Frontend Foundation:

  • React 18: Component-based UI library
  • TypeScript: Type-safe development
  • Vite: Lightning-fast build tooling
  • Tailwind CSS: Utility-first styling
  • shadcn/ui: Accessible component library

Backend Services:

  • Supabase: PostgreSQL + Auth + Storage
  • Edge Functions: Serverless compute
  • Stripe: Payment processing
  • Push Notifications: Web Push API

Mobile Platform:

  • Capacitor: Native app wrapper
  • PWA: Progressive Web App features
  • Service Workers: Offline support

Application Structure

How the codebase is organized for maintainability and scale.

Directory Layout

src/
├── components/       # Reusable UI components
│   ├── care/        # Care-related components
│   ├── inventory/   # Inventory management
│   ├── reports/     # Reporting components
│   ├── tasks/       # Task management
│   └── ui/          # Base UI components
├── pages/           # Route-level components
├── hooks/           # Custom React hooks
├── lib/             # Utility functions
├── services/        # Business logic layer
├── integrations/    # External service clients
├── types/           # TypeScript definitions
└── config/          # App configuration

Component Architecture

Component Hierarchy:

App
├── AuthWrapper (Authentication boundary)
├── Router (Navigation)
│   ├── Layout (Common UI)
│   └── Pages (Route components)
│       ├── Smart Components (Logic)
│       └── Presentation Components (UI)

Component Patterns:

  • Smart/Container components handle logic
  • Presentation components focus on UI
  • Compound components for complex UI
  • Render props for flexible composition

Frontend Architecture

React patterns and practices that power the UI.

Component Organization

Feature-Based Structure:

// Feature module example
components/care/
├── CareLogForm.tsx       // Main form component
├── CareLogList.tsx       // List display
├── CareLogCard.tsx       // Individual item
├── care-log.config.ts    // Configuration
└── index.ts              // Public exports

Component Categories:

  • Page Components: Full-screen views
  • Feature Components: Business logic
  • UI Components: Reusable primitives
  • Layout Components: Structure

State Management

React Query for Server State:

// Data fetching with React Query
const { data, isLoading } = useQuery({
  queryKey: ['crittrs', havenId],
  queryFn: () => fetchCrittrs(havenId),
  staleTime: 5 * 60 * 1000, // 5 minutes
});

Local State Patterns:

  • Component state with useState
  • Complex state with useReducer
  • Form state with React Hook Form
  • URL state with React Router

Routing Architecture

Route Structure:

// Route configuration
const routes = [
  { path: '/', element: <Home /> },
  { path: '/havens/:id', element: <HavenDetail /> },
  { path: '/care', element: <CareCenter /> },
  { path: '/settings', element: <Settings /> },
];

Protected Routes:

  • Authentication wrapper
  • Role-based access
  • Subscription checks
  • Loading states

Data Flow Patterns

How data moves through the application.

Unidirectional Data Flow

User Action → Hook → API Call → State Update → UI Render
     ↑                                              ↓
     └──────────── User Feedback ←─────────────────┘

Hook Architecture

Custom Hook Pattern:

// Business logic encapsulation
function useHavens() {
  const queryClient = useQueryClient();
  
  const havens = useQuery(['havens'], fetchHavens);
  
  const createHaven = useMutation(
    (data) => api.createHaven(data),
    {
      onSuccess: () => {
        queryClient.invalidateQueries(['havens']);
      }
    }
  );
  
  return { havens, createHaven };
}

Hook Categories:

  • Data Hooks: API interactions
  • Action Hooks: User operations
  • Utility Hooks: Shared logic
  • UI Hooks: Interface state

Backend Integration

Connecting to Supabase and external services.

Supabase Client Architecture

Client Configuration:

// Centralized Supabase client
const supabase = createClient(
  SUPABASE_URL,
  SUPABASE_ANON_KEY,
  {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
    }
  }
);

Database Operations:

  • Row Level Security (RLS)
  • Real-time subscriptions
  • Optimistic updates
  • Error recovery

API Layer Design

Service Pattern:

// Service layer abstraction
class CrittrService {
  async getCrittrs(havenId: string) {
    const { data, error } = await supabase
      .from('crittrs')
      .select('*')
      .eq('haven_id', havenId);
    
    if (error) throw error;
    return data;
  }
}

Performance Architecture

Optimizations for speed and efficiency.

Code Splitting

Route-Based Splitting:

// Lazy loading routes
const Settings = lazy(() => import('./pages/Settings'));
const Reports = lazy(() => import('./pages/Reports'));

Caching Strategy

Multi-Level Cache:

  1. React Query cache (memory)
  2. Service Worker cache (offline)
  3. Browser cache (assets)
  4. CDN cache (static files)

Bundle Optimization

Vite Configuration:

// Optimized build settings
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          ui: ['@radix-ui/*'],
        }
      }
    }
  }
};

Mobile Architecture

PWA and native app considerations.

Progressive Web App

PWA Features:

  • Service worker for offline
  • Web app manifest
  • Push notifications
  • Install prompts

Capacitor Integration

Native Bridge:

// Native feature access
import { Camera } from '@capacitor/camera';

const photo = await Camera.getPhoto({
  quality: 90,
  source: CameraSource.Camera,
});

Responsive Design

Mobile-First Approach:

  • Touch-optimized interfaces
  • Gesture support
  • Viewport management
  • Performance budgets

Error Handling Architecture

Graceful failure and recovery patterns.

Error Boundaries

Component Protection:

// Error boundary wrapper
<ErrorBoundary fallback={<ErrorFallback />}>
  <RiskyComponent />
</ErrorBoundary>

Global Error Handling

Centralized Error Management:

  • API error interceptors
  • Form validation errors
  • Network failure recovery
  • User-friendly messages

Security Architecture

Protecting user data and application integrity.

Authentication Flow

User Login → Supabase Auth → JWT Token → Secure Session
                    ↓
            Row Level Security → Data Access

Security Layers

Defense in Depth:

  1. Client-side validation
  2. API input sanitization
  3. Database RLS policies
  4. Encrypted connections

Development Patterns

Best practices for contributing code.

TypeScript Usage

Type Safety:

// Strongly typed components
interface CrittrProps {
  id: string;
  name: string;
  species: Species;
  measurements?: Measurement[];
}

Component Development

Development Flow:

  1. Define TypeScript interfaces
  2. Create component structure
  3. Implement business logic
  4. Add error handling
  5. Write unit tests

Code Organization

File Naming:

  • Components: PascalCase.tsx
  • Hooks: camelCase.ts
  • Utils: kebab-case.ts
  • Types: types.ts

Testing Architecture

Ensuring quality and reliability.

Testing Strategy

Test Pyramid:

  • Unit tests (components)
  • Integration tests (features)
  • E2E tests (workflows)

Testing Tools

Test Stack:

  • Vitest for unit tests
  • React Testing Library
  • MSW for API mocking
  • Playwright for E2E

Build & Deployment

From development to production.

Build Pipeline

Source Code → TypeScript Check → Build → Optimize → Deploy
                    ↓                         ↓
                Linting                   Bundle Analysis

Environment Management

Configuration:

  • Development (.env.local)
  • Staging (.env.staging)
  • Production (.env.production)

Monitoring & Analytics

Understanding application behavior.

Performance Monitoring

Metrics Tracked:

  • Core Web Vitals
  • API response times
  • Error rates
  • User flows

Analytics Architecture

Privacy-First Analytics:

  • Anonymous usage data
  • Opt-in tracking
  • GDPR compliance
  • Minimal collection

Future Architecture

Planned improvements and scaling.

Upcoming Patterns

Future Enhancements:

  • Server Components (React 19)
  • Edge computing
  • WebAssembly modules
  • AI/ML integrations

Scaling Considerations

Growth Planning:

  • Microservices migration
  • GraphQL adoption
  • Real-time collaboration
  • Multi-region deployment

Architecture Decision Records

Key decisions and rationale.

Why React Query?

Benefits:

  • Declarative data fetching
  • Automatic caching
  • Background refetching
  • Optimistic updates

Why Supabase?

Advantages:

  • Real-time subscriptions
  • Built-in authentication
  • Row Level Security
  • Open source

Why TypeScript?

Value:

  • Type safety
  • Better IDE support
  • Self-documenting code
  • Refactoring confidence

Getting Started

Begin developing with confidence.

Prerequisites

  • Node.js 18+
  • npm or pnpm
  • Git
  • VS Code (recommended)

Quick Start

# Clone repository
git clone https://github.com/crittrhavens/app

# Install dependencies
npm install

# Start development
npm run dev

Next Steps

Dive deeper into specific areas.


Building the future of reptile care management, one component at a time. 🚀