Skip to main content

Architecture Overview

Horse Trust is built as a modern, full-stack web application following a monorepo structure with clear separation between client and server applications. This document provides a comprehensive overview of the system architecture, technology choices, and how different components interact.

System Architecture Diagram

Monorepo Structure

The project follows a monorepo architecture with clear separation of concerns:

Technology Stack

Frontend Technologies

Next.js 16

React framework with App Router
  • Server-side rendering (SSR)
  • Server Actions for data mutations
  • File-based routing
  • Automatic code splitting
  • Built-in optimization

React 19

Latest React features
  • Improved concurrent rendering
  • Server Components
  • Enhanced hooks
  • Better TypeScript integration

TypeScript 5

Type-safe JavaScript
  • Static type checking
  • Enhanced IDE support
  • Better refactoring
  • Compile-time error detection

Tailwind CSS 4

Utility-first CSS framework
  • Rapid UI development
  • Dark mode support
  • Responsive design
  • Custom design system
Additional Frontend Libraries:
  • lucide-react (v0.575.0): Modern icon library
  • @tailwindcss/postcss (v4): PostCSS integration

Backend Technologies

Express.js 5

Fast, minimalist web framework
  • RESTful API design
  • Middleware ecosystem
  • Route handling
  • Error management

Socket.io 4.8

Real-time bidirectional communication
  • WebSocket protocol
  • Event-based messaging
  • Room-based broadcasting
  • Automatic reconnection

MongoDB + Mongoose

NoSQL database with ODM
  • Flexible schema design
  • Document relationships
  • Query building
  • Validation and middleware

JWT Authentication

Secure token-based auth
  • Stateless authentication
  • HTTP-only cookies
  • 10-day token expiration
  • bcrypt password hashing
Additional Backend Libraries:
  • bcryptjs (v3.0.3): Password hashing with 12 salt rounds
  • helmet (v8.1.0): Security headers
  • morgan (v1.10.1): HTTP request logging
  • express-rate-limit (v8.2.1): Rate limiting
  • express-validator (v7.3.1): Request validation
  • dotenv (v17.3.1): Environment variable management
  • nodemon (v3.1.11): Development auto-reload
  • ts-node (v10.9.2): TypeScript execution

Data Models

User Model

The User model handles authentication and role-based access control:
server/src/models/User.ts
Key Features:
  • Email validation with regex
  • Automatic password hashing with bcrypt (12 salt rounds)
  • Role-based access control (admin/seller)
  • Seller verification workflow
  • Secure JSON serialization (removes sensitive fields)

Horse Model

The Horse model manages horse listings with rich media support:
server/src/models/Horse.ts
Key Features:
  • Minimum 3 photos requirement with validation
  • Automatic YouTube/Vimeo embed URL generation
  • Full-text search in Spanish
  • Geolocation support with coordinates
  • Multi-currency pricing
  • Status workflow (draft → active → sold/paused)
  • View count tracking

Veterinary Records & Chat

server/src/models/VetRecord.ts

API Architecture

Express Application Setup

The Express app (server/src/app.ts) is configured with security and middleware:
server/src/app.ts

API Endpoints

POST /api/auth/register
  • Register new user (seller or admin)
  • Hashes password with bcrypt
  • Returns JWT token
POST /api/auth/login
  • Authenticate user with email/password
  • Returns JWT token with 10-day expiration
PUT /api/auth/seller-profile
  • Update seller verification details
  • Requires JWT authentication
  • Upload identity documents and selfie
Rate Limit: 10 requests per 15 minutes
GET /api/horses
  • List all horses with pagination
  • Filter by breed, discipline, location, price
  • Full-text search support
GET /api/horses/:id
  • Get individual horse details
  • Increments view count
  • Populates seller information
POST /api/horses
  • Create new horse listing
  • Requires JWT authentication
  • Validates minimum 3 photos
  • Auto-generates video embed URLs
PUT /api/horses/:id
  • Update horse listing
  • Owner verification required
DELETE /api/horses/:id
  • Delete horse listing
  • Owner or admin only
GET /api/admin/sellers/pending
  • List sellers pending verification
  • Admin role required
PUT /api/admin/sellers/:id/verify
  • Approve or reject seller verification
  • Admin role required
GET /api/admin/horses
  • Moderate horse listings
  • View all listings regardless of status
GET /api/chat/conversations
  • List user’s conversations
  • Returns last message preview
GET /api/chat/conversations/:id/messages
  • Get conversation message history
  • Paginated results
POST /api/chat/conversations
  • Create new conversation between users
Note: Real-time messaging uses Socket.io (see below)
GET /health
  • Basic server health check
  • Returns environment info
GET /health/db
  • Check MongoDB connection status
POST /health/db/reconnect
  • Manually trigger database reconnection
  • Used by auto-retry logic in client

Socket.io Real-time Architecture

The platform uses Socket.io for real-time bidirectional communication:
server/src/index.ts

Socket.io Events

connection

Client connects with JWT token in handshake auth. User joins personal room for notifications.

join_conversation

User joins a specific conversation room to receive messages in real-time.

send_message

Send a message to a conversation. Persists to DB and broadcasts to all participants.

new_message

Broadcast event when a new message is sent. All conversation participants receive it.

message_notification

Personal notification sent to recipient’s user room with message preview.

typing

Notify conversation participants that user is typing.

user_typing

Broadcast typing indicator to other conversation participants.

disconnect

Socket connection closed. Cleanup and logging.

Client-Side Architecture

Next.js App Router Structure

The client uses Next.js 16’s App Router with server-side rendering:
client/app/layout.tsx

Server Actions

Next.js Server Actions handle data mutations:
client/app/actions/auth.ts

API Client with Auto-Retry

The apiFetch utility provides automatic database reconnection:
client/app/utils/apiFetch.ts
Key Features:
  • Automatic retry on server errors (5xx)
  • Database reconnection for MongoDB Atlas sleep
  • Network error handling
  • Transparent to consumers

Security Architecture

Authentication Flow

Security Layers

1

Transport Security

  • HTTPS in production
  • Secure WebSocket connections (wss://)
  • HTTP-only cookies prevent XSS attacks
2

Application Security

  • Helmet.js for security headers
  • CORS with origin validation
  • Rate limiting (global + auth-specific)
  • Request validation with express-validator
3

Authentication Security

  • JWT with RS256 or HS256 signing
  • bcrypt password hashing (12 rounds)
  • Token expiration (10 days)
  • Secure cookie storage (httpOnly, secure, sameSite)
4

Database Security

  • MongoDB authentication
  • Input sanitization via Mongoose
  • Schema validation
  • Index optimization for performance

Rate Limiting Strategy

Deployment Architecture

Environment Configuration

Vercel

Frontend Hosting
  • Automatic Next.js optimization
  • Edge network CDN
  • Serverless functions
  • Preview deployments

Railway / Render

Backend Hosting
  • Node.js runtime support
  • WebSocket support for Socket.io
  • Environment variable management
  • Auto-scaling

MongoDB Atlas

Database Hosting
  • Managed MongoDB cluster
  • Automatic backups
  • Global distribution
  • Free tier available

Cloudinary

Media Storage
  • Image/video CDN
  • Automatic optimization
  • Transformation API
  • Free tier available

Performance Optimization

Database Indexing

Caching Strategy

Next.js automatically caches Server Components and API responses. Use revalidatePath() to invalidate cache after mutations.

Monitoring and Logging

Server-side Logging

Client-side Error Handling

Scalability Considerations

Horizontal Scaling

  • Stateless Express servers behind load balancer
  • Socket.io adapter (Redis) for multi-server WebSocket
  • MongoDB replica sets for read scaling

Vertical Scaling

  • Increase server resources (CPU, RAM)
  • MongoDB sharding for large datasets
  • CDN for static assets (Cloudinary)

Caching

  • Redis for session storage
  • Browser caching with proper headers
  • Next.js automatic static optimization

Database Optimization

  • Compound indexes for complex queries
  • Query projection to limit fields
  • Pagination for large result sets
  • Connection pooling

Contributing to the Architecture

When contributing to Horse Trust, follow these architectural principles:
  1. Separation of Concerns: Keep client and server code separate
  2. Type Safety: Use TypeScript for all new code
  3. Security First: Validate all inputs, authenticate all requests
  4. RESTful Design: Follow REST conventions for API endpoints
  5. Real-time When Needed: Use Socket.io only for truly real-time features
  6. Error Handling: Always provide meaningful error messages
  7. Documentation: Document complex logic and architectural decisions
For detailed contribution guidelines, see the CONTRIBUTING.md file.

Back to Quickstart

Return to the quickstart guide to get the platform running