# Architecture Documentation: Trello Clone
## 1. Project Structure
```
trello-clone/
├── src/
│ ├── app/ # Next.js 14 App Router
│ │ ├── (auth)/ # Auth routes group
│ │ │ ├── login/
│ │ │ └── register/
│ │ ├── (dashboard)/ # Protected routes group
│ │ │ ├── boards/
│ │ │ │ ├── [boardId]/
│ │ │ │ │ └── page.tsx # Board detail view
│ │ │ │ └── page.tsx # Boards list
│ │ │ ├── profile/
│ │ │ └── layout.tsx # Dashboard layout with sidebar
│ │ ├── api/ # API routes
│ │ │ ├── boards/
│ │ │ ├── lists/
│ │ │ ├── cards/
│ │ │ ├── webhooks/
│ │ │ └── realtime/
│ │ ├── layout.tsx # Root layout
│ │ └── page.tsx # Landing page
│ ├── components/
│ │ ├── ui/ # Reusable UI components (shadcn/ui)
│ │ │ ├── button.tsx
│ │ │ ├── card.tsx
│ │ │ ├── dialog.tsx
│ │ │ ├── dropdown-menu.tsx
│ │ │ └── ...
│ │ ├── board/ # Board-specific components
│ │ │ ├── Board.tsx
│ │ │ ├── BoardCard.tsx
│ │ │ ├── BoardHeader.tsx
│ │ │ └── BoardList.tsx
│ │ ├── list/ # List components
│ │ │ ├── List.tsx
│ │ │ ├── ListHeader.tsx
│ │ │ ├── AddList.tsx
│ │ │ └── ListMenu.tsx
│ │ ├── card/ # Card components
│ │ │ ├── Card.tsx
│ │ │ ├── CardModal.tsx
│ │ │ ├── CardDetails.tsx
│ │ │ └── AddCard.tsx
│ │ ├── auth/ # Authentication components
│ │ │ ├── LoginForm.tsx
│ │ │ └── RegisterForm.tsx
│ │ └── shared/ # Shared components
│ │ ├── Navbar.tsx
│ │ ├── Sidebar.tsx
│ │ ├── UserAvatar.tsx
│ │ └── SearchBar.tsx
│ ├── lib/
│ │ ├── supabase/ # Supabase client configuration
│ │ │ ├── client.ts # Browser client
│ │ │ ├── server.ts # Server-side client
│ │ │ └── middleware.ts # Auth middleware
│ │ ├── hooks/ # Custom React hooks
│ │ │ ├── useBoard.ts
│ │ │ ├── useCards.ts
│ │ │ ├── useLists.ts
│ │ │ └── useRealtime.ts
│ │ ├── actions/ # Server actions
│ │ │ ├── board-actions.ts
│ │ │ ├── list-actions.ts
│ │ │ ├── card-actions.ts
│ │ │ └── auth-actions.ts
│ │ ├── validations/ # Zod validation schemas
│ │ │ ├── board.ts
│ │ │ ├── list.ts
│ │ │ ├── card.ts
│ │ │ └── user.ts
│ │ ├── utils/ # Utility functions
│ │ │ ├── cn.ts # Class name utilities
│ │ │ ├── date.ts
│ │ │ └── drag-and-drop.ts
│ │ └── constants.ts # App constants
│ ├── types/
│ │ ├── database.types.ts # Generated Supabase types
│ │ ├── board.ts
│ │ ├── list.ts
│ │ ├── card.ts
│ │ └── index.ts
│ └── styles/
│ └── globals.css # Global styles with Tailwind
├── supabase/
│ ├── migrations/ # Database migrations
│ │ ├── 20240101000000_initial_schema.sql
│ │ ├── 20240102000000_add_rls_policies.sql
│ │ └── 20240103000000_add_realtime.sql
│ ├── functions/ # Edge functions
│ │ └── send-notification/
│ └── config.toml # Supabase config
├── public/
│ ├── images/
│ └── icons/
├── tests/
│ ├── unit/
│ ├── integration/
│ └── e2e/
├── .env.local # Environment variables
├── .env.example
├── next.config.js # Next.js configuration
├── tailwind.config.ts # Tailwind configuration
├── tsconfig.json # TypeScript configuration
├── package.json
└── README.md
```
## 2. System Architecture Diagrams
### High-Level System Architecture
```mermaid
C4Context
title System Context - Trello Clone Application
Person(user, "User", "Registers and manages boards, lists, and cards")
Person(collaborator, "Collaborator", "Invited team member working on shared boards")
System(trello_clone, "Trello Clone", "Project management application for organizing tasks and workflows")
System_Ext(supabase, "Supabase", "Backend-as-a-Service: Auth, Database, Storage, Realtime")
System_Ext(vercel, "Vercel", "Hosting and deployment platform")
System_Ext(cloudinary, "Cloudinary", "Image hosting and optimization")
System_Ext(resend, "Resend", "Email service for notifications")
Rel(user, trello_clone, "Creates boards, lists, and cards")
Rel(collaborator, trello_clone, "Collaborates on shared boards")
Rel(trello_clone, supabase, "Authenticates, stores data, syncs in realtime")
Rel(trello_clone, cloudinary, "Uploads and retrieves card attachments")
Rel(trello_clone, resend, "Sends email notifications")
Rel(vercel, trello_clone, "Hosts and serves application")
```
### Container Architecture
```mermaid
C4Container
title Container Diagram - Trello Clone Application
Person(user, "User", "Application user")
System_Boundary(system, "Trello Clone Application") {
Container(web_app, "Web Application", "Next.js 14 with React", "Provides UI and user interactions")
Container(api_routes, "API Routes", "Next.js API Routes", "RESTful API endpoints")
Container(server_actions, "Server Actions", "Next.js Server Actions", "Server-side mutations and data fetching")
Container(realtime_service, "Realtime Service", "Supabase Realtime", "WebSocket connections for live updates")
}
Boundary(supabase_platform, "Supabase Platform", "BaaS") {
ContainerDb(postgres, "PostgreSQL Database", "Supabase Postgres", "Stores all application data")
Container(supabase_auth, "Auth Service", "Supabase Auth", "User authentication and authorization")
Container(supabase_storage, "Storage Service", "Supabase Storage", "File storage for attachments")
Container(supabase_edge, "Edge Functions", "Deno", "Serverless functions for background jobs")
}
System_Ext(cloudinary_cdn, "Cloudinary CDN", "Image optimization and delivery")
System_Ext(email_service, "Resend", "Transactional email service")
Rel(user, web_app, "Uses [HTTPS]")
Rel(web_app, api_routes, "Calls [REST API]")
Rel(web_app, server_actions, "Invokes server functions")
Rel(web_app, realtime_service, "Subscribes [WebSocket]")
Rel(api_routes, postgres, "Reads/Writes [SQL]")
Rel(server_actions, postgres, "Reads/Writes [SQL]")
Rel(server_actions, supabase_auth, "Validates sessions")
Rel(api_routes, supabase_storage, "Uploads/Downloads files")
Rel(realtime_service, postgres, "Listens to changes [pg_notify]")
Rel(supabase_edge, email_service, "Sends emails [HTTP]")
Rel(web_app, cloudinary_cdn, "Fetches optimized images")
```
### Component Architecture (API Layer)
```mermaid
C4Component
title Component Diagram - API Routes and Server Actions
Container_Boundary(api_layer, "API and Server Layer") {
Component(auth_middleware, "Auth Middleware", "Next.js Middleware", "Validates user sessions and permissions")
Component(board_routes, "Board Routes", "API Routes", "CRUD operations for boards")
Component(list_routes, "List Routes", "API Routes", "CRUD operations for lists")
Component(card_routes, "Card Routes", "API Routes", "CRUD operations for cards")
Component(board_actions, "Board Actions", "Server Actions", "Board mutations and queries")
Component(validation, "Validation Layer", "Zod", "Input validation schemas")
Component(db_client, "Database Client", "Supabase Client", "Database connection and queries")
Component(realtime_handler, "Realtime Handler", "Supabase Realtime", "Broadcasts and subscriptions")
}
ContainerDb(db, "Database", "PostgreSQL", "Data persistence")
Container(auth_service, "Auth Service", "Supabase Auth", "User sessions")
Container(storage, "Storage Service", "Supabase Storage", "File storage")
Rel(auth_middleware, auth_service, "Validates token")
Rel(board_routes, validation, "Validates input")
Rel(list_routes, validation, "Validates input")
Rel(card_routes, validation, "Validates input")
Rel(board_actions, validation, "Validates input")
Rel(board_routes, db_client, "Queries database")
Rel(list_routes, db_client, "Queries database")
Rel(card_routes, db_client, "Queries database")
Rel(board_actions, db_client, "Queries database")
Rel(db_client, db, "Executes SQL")
Rel(db_client, realtime_handler, "Triggers events")
Rel(card_routes, storage, "Uploads attachments")
```
### Data Flow Diagram
```mermaid
flowchart TB
subgraph sources["📥 Data Sources"]
user_input["👤 User Actions<br/>(Board/List/Card operations)"]
realtime_updates["🔄 Realtime Events<br/>(Other users' changes)"]
file_uploads["📎 File Uploads<br/>(Card attachments)"]
end
subgraph client["💻 Client Layer"]
react_ui["React Components"]
state_mgmt["State Management<br/>(React Query/SWR)"]
websocket["WebSocket Client"]
end
subgraph validation["✅ Validation"]
client_validation["Client-side Validation<br/>(Zod)"]
server_validation["Server-side Validation<br/>(Zod)"]
end
subgraph server["⚙️ Server Layer"]
api_routes["API Routes"]
server_actions["Server Actions"]
auth_check["Auth Verification"]
end
subgraph storage["💾 Data Storage"]
postgres["PostgreSQL<br/>(Structured Data)"]
supabase_storage["Supabase Storage<br/>(File Attachments)"]
realtime_broadcast["Realtime Broadcast<br/>(Live Updates)"]
end
subgraph outputs["📤 Data Outputs"]
ui_render["UI Rendering"]
notifications["Email Notifications"]
webhooks["Webhook Events"]
end
user_input --> client_validation
client_validation --> react_ui
react_ui --> api_routes
react_ui --> server_actions
api_routes --> server_validation
server_actions --> server_validation
server_validation --> auth_check
auth_check --> postgres
file_uploads --> supabase_storage
postgres --> realtime_broadcast
realtime_broadcast --> websocket
websocket --> state_mgmt
state_mgmt --> ui_render
postgres --> notifications
postgres --> webhooks
realtime_updates --> websocket
postgres -.->|"Optimistic updates"| ui_render
```
### Deployment Architecture
```mermaid
C4Deployment
title Deployment Diagram - Trello Clone Production Environment
Deployment_Node(client_device, "User's Device", "Desktop/Mobile Browser") {
Container(browser, "Web Browser", "Chrome/Safari/Firefox", "Runs React application")
}
Deployment_Node(vercel_cloud, "Vercel Edge Network", "Global CDN") {
Deployment_Node(edge_locations, "Edge Locations x20+", "Vercel Edge") {
Container(next_app, "Next.js Application", "Node.js 20", "Serves SSR and API routes")
Container(static_assets, "Static Assets", "CDN", "JS, CSS, Images")
}
}
Deployment_Node(supabase_cloud, "Supabase Cloud", "AWS us-east-1") {
Deployment_Node(supabase_primary, "Primary Database", "AWS EC2") {
ContainerDb(postgres_primary, "PostgreSQL Primary", "PostgreSQL 15", "Main database with read/write")
}
Deployment_Node(supabase_replica, "Read Replica", "AWS EC2") {
ContainerDb(postgres_replica, "PostgreSQL Replica", "PostgreSQL 15", "Read-only replica for queries")
}
Deployment_Node(supabase_realtime, "Realtime Server", "AWS ECS") {
Container(realtime, "Realtime Service", "Elixir/Phoenix", "WebSocket connections")
}
Deployment_Node(supabase_storage_node, "Storage Service", "AWS S3") {
Container(storage, "Object Storage", "S3", "File attachments storage")
}
Deployment_Node(edge_functions, "Edge Functions", "Deno Deploy") {
Container(bg_jobs, "Background Jobs", "Deno", "Email notifications, webhooks")
}
}
Deployment_Node(cloudinary_cdn, "Cloudinary", "Global CDN") {
Container(image_service, "Image Service", "CDN", "Optimized image delivery")
}
Rel(browser, next_app, "HTTPS requests", "HTTPS")
Rel(browser, static_assets, "Fetches assets", "HTTPS")
Rel(browser, realtime, "WebSocket connection", "WSS")
Rel(next_app, postgres_primary, "Read/Write queries", "PostgreSQL Protocol")
Rel(next_app, postgres_replica, "Read queries", "PostgreSQL Protocol")
Rel(next_app, storage, "Upload/Download files", "HTTPS")
Rel(realtime, postgres_primary, "Listens to changes", "pg_notify")
Rel(postgres_primary, postgres_replica, "Replicates data", "Streaming Replication")
Rel(bg_jobs, postgres_primary, "Reads events", "PostgreSQL Protocol")
Rel(browser, image_service, "Fetches images", "HTTPS")
UpdateRelStyle(browser, next_app, $offsetY="-30")
UpdateRelStyle(next_app, postgres_primary, $offsetX="-40")
UpdateRelStyle(postgres_primary, postgres_replica, $offsetY="-20")
```
## 3. Core Components
### Frontend Components
#### Web Application (Next.js 14)
- **Technology**: Next.js 14 with App Router, React 18, TypeScript
- **Purpose**: Provides the user interface and client-side logic
- **Key Features**:
- Server-side rendering (SSR) for improved performance and SEO
- Client components for interactive features (drag-and-drop, modals)
- Optimistic updates for better UX
- Real-time collaboration via WebSocket connections
- **Responsibilities**:
- Rendering board, list, and card interfaces
- Handling user interactions and drag-and-drop operations
- Managing client-side state with React Query/SWR
- Establishing WebSocket connections for realtime updates
#### UI Component Library
- **Technology**: shadcn/ui with Radix UI primitives, Tailwind CSS
- **Purpose**: Reusable, accessible UI components
- **Components**:
- Buttons, inputs, dialogs, dropdown menus
- Custom components: Board cards, list containers, task cards
- Drag-and-drop components using @dnd-kit
- **Features**:
- Fully accessible (ARIA compliant)
- Customizable via Tailwind CSS
- Dark mode support
### Backend Services
#### API Routes
- **Technology**: Next.js API Routes (serverless functions)
- **Purpose**: RESTful API endpoints for CRUD operations
- **Endpoints**:
- `/api/boards` - Board management
- `/api/lists` - List operations
- `/api/cards` - Card operations
- `/api/webhooks` - External integrations
- `/api/upload` - File upload handling
- **Features**:
- JWT authentication via Supabase
- Input validation with Zod
- Error handling and logging
- Rate limiting
#### Server Actions
- **Technology**: Next.js Server Actions
- **Purpose**: Server-side mutations and data fetching
- **Actions**:
- `createBoard`, `updateBoard`, `deleteBoard`
- `createList`, `updateListOrder`, `deleteList`
- `createCard`, `moveCard`, `updateCard`, `deleteCard`
- `inviteCollaborator`, `updatePermissions`
- **Benefits**:
- Type-safe API calls
- Automatic revalidation
- Simplified error handling
### Authentication & Authorization
#### Supabase Auth
- **Technology**: Supabase Authentication service
- **Features**:
- Email/password authentication
- OAuth providers (Google, GitHub, Microsoft)
- Magic link authentication
- Session management with JWT
- Row-level security (RLS) policies
- **Implementation**:
- Auth middleware in Next.js for route protection
- Automatic token refresh
- Server-side session validation
### Realtime Collaboration
#### Supabase Realtime
- **Technology**: Supabase Realtime (Phoenix/Elixir-based WebSocket service)
- **Purpose**: Enable live collaboration features
- **Features**:
- Board presence (show active users)
- Live card updates (positions, content, assignments)
- List order synchronization
- Cursor tracking for collaborative editing
- **Implementation**:
- WebSocket subscriptions to specific boards
- Broadcast and receive change events
- Optimistic UI updates with rollback on error
## 4. Data Stores
### Primary Database: Supabase PostgreSQL
**Technology**: PostgreSQL 15 (managed by Supabase)
**Purpose**: Store all application data with relational integrity
**Schema Overview**:
```sql
-- Users (managed by Supabase Auth)
auth.users (
id uuid PRIMARY KEY,
email text UNIQUE,
created_at timestamptz
)
-- User Profiles
public.profiles (
id uuid PRIMARY KEY REFERENCES auth.users,
username text UNIQUE,
full_name text,
avatar_url text,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
)
-- Boards
public.boards (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
title text NOT NULL,
description text,
background_color text,
background_image_url text,
owner_id uuid REFERENCES auth.users NOT NULL,
is_public boolean DEFAULT false,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
)
-- Board Members (for collaboration)
public.board_members (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
board_id uuid REFERENCES boards ON DELETE CASCADE,
user_id uuid REFERENCES auth.users ON DELETE CASCADE,
role text CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
created_at timestamptz DEFAULT now(),
UNIQUE(board_id, user_id)
)
-- Lists
public.lists (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
board_id uuid REFERENCES boards ON DELETE CASCADE,
title text NOT NULL,
position integer NOT NULL,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
)
-- Cards
public.cards (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
list_id uuid REFERENCES lists ON DELETE CASCADE,
title text NOT NULL,
description text,
position integer NOT NULL,
due_date timestamptz,
labels jsonb DEFAULT '[]',
assignees uuid[] DEFAULT '{}',
created_by uuid REFERENCES auth.users,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
)
-- Card Comments
public.card_comments (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
card_id uuid REFERENCES cards ON DELETE CASCADE,
user_id uuid REFERENCES auth.users,
content text NOT NULL,
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
)
-- Card Attachments
public.card_attachments (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
card_id uuid REFERENCES cards ON DELETE CASCADE,
file_name text NOT NULL,
file_url text NOT NULL,
file_type text,
file_size integer,
uploaded_by uuid REFERENCES auth.users,
created_at timestamptz DEFAULT now()
)
-- Activity Log
public.activity_log (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
board_id uuid REFERENCES boards ON DELETE CASCADE,
user_id uuid REFERENCES auth.users,
action text NOT NULL,
entity_type text NOT NULL,
entity_id uuid,
metadata jsonb,
created_at timestamptz DEFAULT now()
)
```
**Row-Level Security (RLS) Policies**:
- Users can only read boards they own or are members of
- Only board owners and admins can modify board settings
- Members can create/edit cards and lists
- Viewers have read-only access
- Users can only see profiles of board members
**Indexes**:
- `boards.owner_id` for user's boards lookup
- `lists.board_id` with position for ordered retrieval
- `cards.list_id` with position for ordered retrieval
- `board_members.board_id` and `board_members.user_id` for permission checks
- `activity_log.board_id` with created_at for activity feed
### File Storage: Supabase Storage
**Technology**: Supabase Storage (S3-compatible object storage)
**Purpose**: Store card attachments (images, documents, files)
**Buckets**:
- `card-attachments` - Files uploaded to cards
- `board-backgrounds` - Custom board background images
- `avatars` - User profile pictures
**Configuration**:
- Public buckets for avatars and board backgrounds
- Private bucket for card attachments with RLS policies
- File size limits: 10MB per file
- Allowed file types: images, PDFs, documents
- Automatic image optimization via transformation API
**Storage Policies**:
- Users can upload to boards they have access to
- Users can read attachments from boards they're members of
- Users can delete their own uploads
- Board owners can delete any attachment on their boards
### Caching Strategy
**Client-Side Caching**:
- **Technology**: React Query (TanStack Query)
- **Purpose**: Cache API responses and manage data fetching
- **Configuration**:
- 5-minute stale time for board data
- 10-minute cache time for user profiles
- Optimistic updates for mutations
- Automatic background refetching
**Edge Caching**:
- **Technology**: Vercel Edge Network
- **Purpose**: Cache static assets and API responses
- **Configuration**:
- Static assets cached for 1 year with immutable content hashing
- API responses cached for 60 seconds with `stale-while-revalidate`
- Dynamic routes use ISR (Incremental Static Regeneration)
## 5. External Integrations
### Supabase Platform
- **Purpose**: Backend-as-a-Service providing auth, database, storage, and realtime
- **Integration Points**:
- Authentication service for user management
- PostgreSQL database for data persistence
- Storage service for file uploads
- Realtime service for WebSocket connections
- Edge functions for background jobs
- **Configuration**: Environment variables for project URL and anon key
### Vercel
- **Purpose**: Hosting and deployment platform
- **Features Used**:
- Automatic deployments from Git
- Preview deployments for pull requests
- Edge network for global CDN
- Serverless functions for API routes
- Analytics and monitoring
- **Configuration**: Connected to GitHub repository with automatic deployments
### Cloudinary (Optional)
- **Purpose**: Advanced image optimization and transformation
- **Use Cases**:
- Optimized board background images
- Automatic format conversion (WebP, AVIF)
- Responsive image delivery
- Image transformations (crop, resize, effects)
- **Integration**: URL-based transformations, fallback to Supabase Storage
### Resend
- **Purpose**: Transactional email service
- **Use Cases**:
- Welcome emails for new users
- Board invitation emails
- Card assignment notifications
- Due date reminders
- Activity digest emails
- **Integration**: API calls from Supabase Edge Functions
- **Templates**: React Email templates for consistent branding
### Sentry (Recommended)
- **Purpose**: Error tracking and performance monitoring
- **Features**:
- Real-time error reporting
- Performance monitoring
- Session replay
- Release tracking
- **Integration**: SDK in Next.js app with source map upload
## 6. Deployment Architecture
### Hosting Platform: Vercel
**Production Environment**:
- **Deployment**: Automatic deployments from `main` branch
- **Regions**: Global edge network (20+ locations)
- **Build**: Next.js optimized builds with route caching
- **Environment Variables**:
- `NEXT_PUBLIC_SUPABASE_URL`
- `NEXT_PUBLIC_SUPABASE_ANON_KEY`
- `SUPABASE_SERVICE_ROLE_KEY` (server-only)
- `CLOUDINARY_CLOUD_NAME`
- `CLOUDINARY_API_KEY`
- `CLOUDINARY_API_SECRET`
- `RESEND_API_KEY`
**Staging Environment**:
- Preview deployments for every pull request
- Separate Supabase project for staging
- Same configuration as production
### Database Deployment
**Supabase Cloud Configuration**:
- **Region**: AWS us-east-1 (or closest to user base)
- **Tier**: Pro plan with increased compute and storage
- **Backup Strategy**:
- Daily automated backups (retained for 7 days)
- Point-in-time recovery enabled
- Manual backups before major migrations
- **Read Replicas**: Enabled for read-heavy operations (optional)
- **Connection Pooling**: PgBouncer for handling concurrent connections
### CI/CD Pipeline
**GitHub Actions Workflow**:
```yaml
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '20'
- run: npm ci
- run: npm run lint
- run: npm run type-check
- run: npm run test
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- name: Deploy to Vercel
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
```
**Database Migrations**:
- Migrations stored in `supabase/migrations/`
- Applied via Supabase CLI: `supabase db push`
- Automated in CI/CD pipeline for staging
- Manual review and deployment for production
### Monitoring and Observability
**Application Monitoring**:
- Vercel Analytics for performance metrics
- Next.js built-in Web Vitals tracking
- Custom events for user interactions
**Error Tracking**:
- Sentry for frontend and backend errors
- Source maps uploaded for readable stack traces
- Error grouping and alerting
**Database Monitoring**:
- Supabase Dashboard for query performance
- Connection pooling metrics
- Slow query log analysis
**Logging**:
- Server logs via Vercel dashboard
- Database logs via Supabase dashboard
- Structured logging with correlation IDs
## 7. Security
### Authentication Security
**Supabase Auth**:
- JWT-based authentication with automatic token refresh
- Secure HTTP-only cookies for session management
- PKCE flow for OAuth providers
- Rate limiting on authentication endpoints (10 attempts per hour)
- Email verification required for new accounts
- Password requirements: minimum 8 characters, complexity rules
**Session Management**:
- Access tokens expire after 1 hour
- Refresh tokens expire after 30 days
- Automatic session refresh on client side
- Server-side session validation on protected routes
- Logout clears all tokens and sessions
### Authorization
**Row-Level Security (RLS)**:
- Enforced at database level for all tables
- Policies based on user roles and board membership
- Example policies:
```sql
-- Users can only see boards they're members of
CREATE POLICY "Users can view accessible boards"
ON boards FOR SELECT
USING (
auth.uid() = owner_id OR
EXISTS (
SELECT 1 FROM board_members
WHERE board_id = boards.id
AND user_id = auth.uid()
)
);
-- Only board members can create cards
CREATE POLICY "Members can create cards"
ON cards FOR INSERT
WITH CHECK (
EXISTS (
SELECT 1 FROM lists
JOIN boards ON boards.id = lists.board_id
LEFT JOIN board_members ON board_members.board_id = boards.id
WHERE lists.id = cards.list_id
AND (boards.owner_id = auth.uid() OR board_members.user_id = auth.uid())
)
);
```
**Role-Based Access Control**:
- **Owner**: Full control over board settings, members, deletion
- **Admin**: Can modify board, invite members, delete cards/lists
- **Member**: Can create/edit cards and lists, cannot change settings
- **Viewer**: Read-only access to board content
### Data Protection
**Encryption**:
- All data encrypted at rest in PostgreSQL (AES-256)
- All data encrypted in transit (TLS 1.3)
- Supabase Storage uses S3 encryption
- Sensitive environment variables encrypted in Vercel
**Data Privacy**:
- User data isolated by RLS policies
- No cross-tenant data leakage possible
- Personal data minimization (only essential info collected)
- GDPR-compliant data handling
- User data export feature available
- Right to deletion (cascade delete on user account removal)
### API Security
**Input Validation**:
- All API inputs validated with Zod schemas
- SQL injection prevention via parameterized queries
- XSS prevention via input sanitization
- CSRF protection via SameSite cookies
**Rate Limiting**:
- API routes limited to 100 requests per minute per user
- Authentication endpoints limited to 10 attempts per hour
- File upload limited to 10 files per minute
- Implemented via Vercel Edge Middleware
**CORS Configuration**:
- Strict CORS policy allowing only application domain
- Credentials included for authenticated requests
- Preflight requests handled appropriately
### Security Headers
**Implemented via Next.js Configuration**:
```javascript
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-XSS-Protection', value: '1; mode=block' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{
key: 'Content-Security-Policy',
value: "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()'
}
]
}
]
}
}
```
### File Upload Security
**Supabase Storage Security**:
- File type validation (whitelist approach)
- File size limits enforced (10MB max)
- Virus scanning via Edge Function (optional integration)
- Signed URLs for private files
- RLS policies on storage buckets
- Automatic file deletion on card/board deletion
### Dependency Security
**Supply Chain Security**:
- Regular dependency updates via Dependabot
- npm audit run in CI/CD pipeline
- Lock files committed to repository
- No known vulnerabilities in production
- Minimal dependency footprint
## 8. Development Workflow
### Local Development Setup
**Prerequisites**:
- Node.js 20+ and npm
- Git
- Supabase CLI
- Code editor (VS Code recommended)
**Setup Steps**:
1. **Clone Repository**:
```bash
git clone https://github.com/[org]/trello-clone.git
cd trello-clone
```
2. **Install Dependencies**:
```bash
npm install
```
3. **Set Up Supabase Project**:
```bash
# Login to Supabase
supabase login
# Initialize project
supabase init
# Link to your project
supabase link --project-ref [your-project-ref]
# Start local Supabase services
supabase start
```
4. **Configure Environment Variables**:
```bash
cp .env.example .env.local
```
Edit `.env.local` with your Supabase credentials:
```
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
```
5. **Run Database Migrations**:
```bash
supabase db push
```
6. **Generate TypeScript Types**:
```bash
npm run types:generate
# This runs: supabase gen types typescript --local > src/types/database.types.ts
```
7. **Start Development Server**:
```bash
npm run dev
```
Application runs at `http://localhost:3000`
### Development Tools
**Code Quality**:
- **ESLint**: Linting with Next.js and TypeScript rules
- **Prettier**: Code formatting with consistent style
- **TypeScript**: Strict mode enabled for type safety
- **Husky**: Git hooks for pre-commit checks
**Testing**:
- **Jest**: Unit testing framework
- **React Testing Library**: Component testing
- **Playwright**: End-to-end testing
- **MSW (Mock Service Worker)**: API mocking for tests
**Database Tools**:
- **Supabase Studio**: Local database management UI
- **Prisma Studio** (optional): Alternative database GUI
- **pg_dump**: Database backup and restore
### Git Workflow
**Branch Strategy**:
- `main` - Production branch (protected)
- `develop` - Development branch (integration)
- `feature/*` - Feature branches
- `bugfix/*` - Bug fix branches
- `hotfix/*` - Critical production fixes
**Commit Convention**:
```
type(scope): message
Types: feat, fix, docs, style, refactor, test, chore
Example: feat(board): add drag-and-drop functionality
```
**Pull Request Process**:
1. Create feature branch from `develop`
2. Implement changes with tests
3. Run linting and tests locally
4. Push branch and create PR
5. Code review by team member
6. CI/CD pipeline runs tests
7. Merge to `develop` after approval
8. Deploy to staging automatically
9. Test in staging environment
10. Merge to `main` for production deployment
### Testing Strategy
**Unit Tests** (Target: 80% coverage):
- Test utility functions
- Test validation schemas
- Test data transformation logic
- Location: `tests/unit/`
**Integration Tests**:
- Test API routes with database
- Test server actions
- Test Supabase client interactions
- Location: `tests/integration/`
**End-to-End Tests**:
- Test critical user flows:
- User registration and login
- Creating boards, lists, and cards
- Drag-and-drop operations
- Real-time collaboration
- Location: `tests/e2e/`
- Run via: `npm run test:e2e`
**Running Tests**:
```bash
# Unit tests
npm run test:unit
# Integration tests (requires local Supabase)
npm run test:integration
# E2E tests
npm run test:e2e
# All tests
npm test
# Test coverage
npm run test:coverage
```
### Code Style Guidelines
**TypeScript**:
- Use strict mode
- Define interfaces for all data structures
- Use type guards for runtime checks
- Prefer `interface` over `type` for objects
- Use `const` assertions for immutable data
**React**:
- Functional components with hooks
- Custom hooks for reusable logic
- Proper component composition
- Memoization for expensive computations
- Error boundaries for error handling
**File Naming**:
- Components: PascalCase (e.g., `BoardCard.tsx`)
- Utilities: camelCase (e.g., `dateUtils.ts`)
- Constants: UPPER_SNAKE_CASE
- Tests: `*.test.ts` or `*.test.tsx`
### Database Development
**Migration Workflow**:
```bash
# Create new migration
supabase migration new [migration_name]
# Edit the migration file in supabase/migrations/
# Apply migrations locally
supabase db reset
# Test migrations
npm run test:integration
# Push to remote (staging)
supabase db push
# For production, apply via CI/CD after review
```
**Schema Changes Checklist**:
- [ ] Create migration file
- [ ] Test migration locally
- [ ] Update TypeScript types
- [ ] Update API routes/server actions
- [ ] Update tests
- [ ] Document changes
- [ ] Review with team
- [ ] Deploy to staging
- [ ] Test in staging
- [ ] Deploy to production
## 9. Future Considerations
### Scalability Improvements
**Database Optimization**:
- **Read Replicas**: Add read replicas for heavy read workloads
- **Connection Pooling**: Implement PgBouncer for better connection management
- **Query Optimization**: Analyze and optimize slow queries with EXPLAIN ANALYZE
- **Partitioning**: Consider table partitioning for large datasets (activity logs)
- **Archiving Strategy**: Archive old boards to separate storage after 1 year of inactivity
**Caching Layer**:
- **Redis Integration**: Add Redis for session storage and frequently accessed data
- **Cached Endpoints**: Cache board metadata and user profiles
- **CDN Optimization**: Move more static assets to CDN with aggressive caching
**Frontend Performance**:
- **Code Splitting**: Implement dynamic imports for large components
- **Virtual Scrolling**: Use virtual scrolling for large lists (100+ cards)
- **Web Workers**: Offload heavy computations to background threads
- **Progressive Web App**: Add offline support with service workers
### Feature Roadmap
**Phase 1 (Next 3 Months)**:
- [ ] Advanced card features (checklists, due date reminders, labels)
- [ ] Board templates (predefined layouts for common use cases)
- [ ] Activity feed and notifications
- [ ] Search functionality (full-text search across boards)
- [ ] Export boards to PDF/JSON
**Phase 2 (3-6 Months)**:
- [ ] Mobile applications (iOS and Android via React Native)
- [ ] Advanced collaboration (comments, mentions, reactions)
- [ ] Integrations (Slack, GitHub, Google Calendar)
- [ ] Automation rules (e.g., auto-move cards based on triggers)
- [ ] Custom fields for cards
**Phase 3 (6-12 Months)**:
- [ ] Advanced analytics and reporting
- [ ] Time tracking for cards
- [ ] Gantt chart view
- [ ] Mind map view
- [ ] API for third-party integrations
- [ ] Workspace management (multiple boards grouping)
- [ ] Advanced permissions (custom roles)
### Technical Debt
**Current Known Issues**:
- Drag-and-drop performance needs optimization for boards with 200+ cards
- Realtime presence shows stale users occasionally (need heartbeat improvement)
- Image upload error handling could be more graceful
- Some API routes need better error messages
**Planned Refactoring**:
- Extract common validation logic to shared utilities
- Consolidate duplicate Supabase client configurations
- Improve error boundary implementation
- Standardize loading states across components
- Migrate to newer React patterns (use() hook when stable)
### Infrastructure Improvements
**Observability**:
- Implement distributed tracing with OpenTelemetry
- Add custom metrics for business KPIs
- Set up alerting for critical errors and performance degradation
- Create dashboards for real-time monitoring
**Disaster Recovery**:
- Document recovery procedures for database failure
- Implement automated backups to separate cloud provider
- Create runbooks for common incidents
- Test recovery procedures quarterly
**Cost Optimization**:
- Analyze Supabase and Vercel usage patterns
- Optimize database queries to reduce compute costs
- Implement smart caching to reduce API calls
- Consider reserved capacity for predictable workloads
### Security Enhancements
**Planned Security Features**:
- Two-factor authentication (TOTP)
- Audit log for sensitive actions
- IP whitelisting for enterprise users
- Session management dashboard (view and revoke sessions)
- Security headers audit and enhancement
- Penetration testing (annually)
- SOC 2 Type II compliance preparation
### Mobile Strategy
**React Native App**:
- Shared business logic with web app
- Native drag-and-drop experience
- Offline support with sync
- Push notifications
- Biometric authentication
- Camera integration for card attachments
**Progressive Web App**:
- Add service worker for offline support
- Implement background sync
- Add to home screen prompt
- Web share API integration
## 10. Project Identification
**Project Name**: Trello Clone
**Version**: 1.0.0
**Repository**: https://github.com/[org]/trello-clone
**Primary Contact**: Development Team <dev-team@example.com>
**Last Updated**: 2024-01-20
**Technology Stack**:
- Frontend: Next.js 14, React 18, TypeScript 5, Tailwind CSS 3
- Backend: Supabase (PostgreSQL, Auth, Storage, Realtime)
- Hosting: Vercel
- Additional Services: Cloudinary, Resend
**Project Status**: Active Development
**Team**:
- Project Lead: [Name]
- Frontend Developer: [Name]
- Backend Developer: [Name]
- DevOps Engineer: [Name]
- Product Manager: [Name]
**Documentation**:
- Technical Docs: `/docs`
- API Documentation: Automatically generated OpenAPI spec
- User Guide: `/docs/user-guide.md`
## 11. Glossary
**Board**: A collection of lists representing a project or workflow. Equivalent to a Trello board.
**List**: A vertical column within a board containing cards. Represents a stage or category in a workflow.
**Card**: An individual task or item within a list. Can contain descriptions, comments, attachments, and assignees.
**Workspace**: A collection of boards belonging to a user or organization (future feature).
**Row-Level Security (RLS)**: PostgreSQL security feature that restricts database row access based on user identity.
**Server Actions**: Next.js feature allowing server-side functions to be called directly from client components.
**SSR (Server-Side Rendering)**: Rendering pages on the server before sending to the client for improved performance and SEO.
**ISR (Incremental Static Regeneration)**: Next.js feature allowing static pages to be regenerated on-demand.
**Edge Functions**: Serverless functions running at the edge (close to users) for reduced latency.
**WebSocket**: Protocol enabling real-time, bidirectional communication between client and server.
**JWT (JSON Web Token)**: Token-based authentication standard used for secure session management.
**BaaS (Backend-as-a-Service)**: Cloud platform providing backend services like databases, authentication, and storage.
**Optimistic Update**: UI pattern where the interface updates immediately before server confirmation for better UX.
**Drag-and-Drop (DnD)**: User interface feature allowing items to be moved by clicking, dragging, and releasing.
**CRUD**: Create, Read, Update, Delete - basic database operations.
**Realtime Subscription**: Connection to server for receiving live updates as database changes occur.
**Presence**: Feature showing which users are currently active on a board.
**Migration**: Script defining database schema changes in a version-controlled manner.
**Type Safety**: Using TypeScript types to catch errors at compile-time rather than runtime.