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
- 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
- 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
- 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
- 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
Authentication Endpoints - /api/auth
Authentication Endpoints - /api/auth
POST /api/auth/register
- Register new user (seller or admin)
- Hashes password with bcrypt
- Returns JWT token
- Authenticate user with email/password
- Returns JWT token with 10-day expiration
- Update seller verification details
- Requires JWT authentication
- Upload identity documents and selfie
Horse Endpoints - /api/horses
Horse Endpoints - /api/horses
GET /api/horses
- List all horses with pagination
- Filter by breed, discipline, location, price
- Full-text search support
- Get individual horse details
- Increments view count
- Populates seller information
- Create new horse listing
- Requires JWT authentication
- Validates minimum 3 photos
- Auto-generates video embed URLs
- Update horse listing
- Owner verification required
- Delete horse listing
- Owner or admin only
Admin Endpoints - /api/admin
Admin Endpoints - /api/admin
GET /api/admin/sellers/pending
- List sellers pending verification
- Admin role required
- Approve or reject seller verification
- Admin role required
- Moderate horse listings
- View all listings regardless of status
Chat Endpoints - /api/chat
Chat Endpoints - /api/chat
GET /api/chat/conversations
- List user’s conversations
- Returns last message preview
- Get conversation message history
- Paginated results
- Create new conversation between users
Health Check Endpoints - /health
Health Check Endpoints - /health
GET /health
- Basic server health check
- Returns environment info
- Check MongoDB connection status
- 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
TheapiFetch utility provides automatic database reconnection:
client/app/utils/apiFetch.ts
- Automatic retry on server errors (5xx)
- Database reconnection for MongoDB Atlas sleep
- Network error handling
- Transparent to consumers
Security Architecture
Authentication Flow
Security Layers
Transport Security
- HTTPS in production
- Secure WebSocket connections (wss://)
- HTTP-only cookies prevent XSS attacks
Application Security
- Helmet.js for security headers
- CORS with origin validation
- Rate limiting (global + auth-specific)
- Request validation with express-validator
Authentication Security
- JWT with RS256 or HS256 signing
- bcrypt password hashing (12 rounds)
- Token expiration (10 days)
- Secure cookie storage (httpOnly, secure, sameSite)
Rate Limiting Strategy
Deployment Architecture
Environment Configuration
- Development
- Production
Recommended Deployment Stack
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:- Separation of Concerns: Keep client and server code separate
- Type Safety: Use TypeScript for all new code
- Security First: Validate all inputs, authenticate all requests
- RESTful Design: Follow REST conventions for API endpoints
- Real-time When Needed: Use Socket.io only for truly real-time features
- Error Handling: Always provide meaningful error messages
- Documentation: Document complex logic and architectural decisions
Back to Quickstart
Return to the quickstart guide to get the platform running

