Better SaaS Docs

Architecture

Architecture Overview

Better SaaS is built with a modern, scalable architecture that follows industry best practices. This document provides an in-depth look at the system design, components, and architectural patterns used throughout the application.

System Architecture

High-Level Architecture

Client (Web)Next.js App(Frontend)API GatewayNext.js API(Backend)DatabasePostgreSQLCDN/AssetsVercel/StaticExternal APIsStripe, OAuthFile StorageCloudflare R2

Core Components

1. Frontend Layer (Next.js App Router)

  • Pages & Routing: App Router with internationalized routes
  • Components: Reusable UI components with Radix UI
  • State Management: Zustand for client-side state
  • Styling: Tailwind CSS with custom design system
  • Data Fetching: SWR for caching and synchronization

2. Backend Layer (Next.js API Routes)

  • API Endpoints: RESTful APIs with type-safe routing
  • Authentication: Better Auth with multiple providers
  • Database: Drizzle ORM with PostgreSQL
  • File Handling: Secure upload and storage management
  • Payment Processing: Stripe integration with webhooks

3. Data Layer

  • Database: PostgreSQL with optimized schema
  • ORM: Drizzle for type-safe database operations
  • Caching: Redis for session and data caching
  • File Storage: Cloudflare R2 for static assets

Authentication Flow

Multi-Provider Authentication

User Login(Email/OAuth)Better AuthMiddlewareDatabaseSessionsJWT TokenGenerationRole-BasedAccess ControlUser ProfileManagement

Authentication Features

  • Session Management: Database-persisted sessions with configurable expiration
  • Role-Based Access Control: Admin, user, and custom role permissions
  • Social Login: GitHub, Google OAuth integration
  • Security: Password hashing, CSRF protection, secure cookies
  • Password Reset: Email-based password recovery flow

Database Design

Core Tables

Users Table

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  image TEXT,
  role VARCHAR(50) DEFAULT 'user',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Sessions Table

CREATE TABLE sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  token VARCHAR(255) UNIQUE NOT NULL,
  expires_at TIMESTAMP NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);

Files Table

CREATE TABLE files (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  filename VARCHAR(255) NOT NULL,
  original_name VARCHAR(255) NOT NULL,
  mime_type VARCHAR(100) NOT NULL,
  size INTEGER NOT NULL,
  url TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);

Payments Table

CREATE TABLE payments (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  stripe_customer_id VARCHAR(255),
  stripe_subscription_id VARCHAR(255),
  status VARCHAR(50) NOT NULL,
  plan VARCHAR(50) NOT NULL,
  amount INTEGER NOT NULL,
  currency VARCHAR(3) DEFAULT 'usd',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Database Relationships

Users(1)Sessions(N)Files(N)Payments(N)

File Management Architecture

Upload Flow

Client Upload(Form/Drag)API Endpoint/api/uploadValidationSize/TypeFile Storage(R2/S3)DatabaseMetadataResponseURL/Status

File Management Features

  • Secure Uploads: Validation, size limits, and type restrictions
  • Image Processing: Thumbnail generation and optimization
  • Access Control: User-based file permissions
  • Cloud Storage: Integration with Cloudflare R2/AWS S3
  • Metadata Tracking: File information and usage analytics

Payment System Architecture

Stripe Integration

Checkout Flow(Frontend)Stripe API(Payment)WebhookHandlerSubscriptionManagementDatabaseUpdateEmailNotification

Payment Features

  • Subscription Management: Multiple plans with billing cycles
  • Webhook Processing: Real-time payment event handling
  • Invoice Generation: Automated billing and receipts
  • Trial Periods: Configurable free trial functionality
  • Payment Recovery: Failed payment retry logic

Testing Architecture

Test Structure

  • Unit Tests: Component logic and utility functions
  • Integration Tests: API endpoints and database operations
  • E2E Tests: Complete user workflows and scenarios
  • Visual Tests: Screenshot comparison for UI consistency
  • Performance Tests: Load testing and optimization

Internationalization Architecture

i18n Structure

Route Locale[locale]/MessageResolutionContentRenderingLanguageDetectionTranslationFilesLocalizedComponents

i18n Features

  • Route-Based Localization: Automatic locale detection
  • Message Management: Centralized translation files
  • Dynamic Content: Runtime language switching
  • SEO Optimization: Localized meta tags and URLs
  • Fallback Handling: Default language fallbacks

Security Architecture

Security Layers

  1. Application Security

    • CSRF protection with tokens
    • XSS prevention with sanitization
    • SQL injection protection with ORM
    • Rate limiting on API endpoints
  2. Authentication Security

    • Secure password hashing (bcrypt)
    • JWT token validation
    • Session management with secure cookies
    • OAuth provider integration
  3. Data Security

    • Database encryption at rest
    • Secure file upload validation
    • Environment variable protection
    • API key management
  4. Infrastructure Security

    • HTTPS enforcement
    • Security headers (CSP, HSTS)
    • Dependency vulnerability scanning
    • Regular security updates

Performance Optimization

Frontend Optimization

  • Code Splitting: Dynamic imports and route-based splitting
  • Image Optimization: Next.js Image component with WebP
  • Caching: Browser caching and CDN optimization
  • Bundle Analysis: Tree shaking and dead code elimination

Backend Optimization

  • Database Indexing: Optimized queries and indexes
  • API Caching: Response caching with Redis
  • Connection Pooling: Database connection optimization
  • Lazy Loading: On-demand resource loading

Deployment Architecture

Production Deployment

GitHub Repo(Source)Vercel(Build/Deploy)ProductionEnvironmentCI/CDPipelineEnvironmentVariablesMonitoring& Analytics

Deployment Features

  • Automated Deployment: GitHub Actions CI/CD pipeline
  • Environment Management: Staging and production environments
  • Health Monitoring: Application performance monitoring
  • Rollback Capability: Quick rollback on deployment issues
  • Scalability: Auto-scaling based on traffic

Monitoring & Analytics

Application Monitoring

  • Error Tracking: Real-time error monitoring and alerting
  • Performance Metrics: Response times and resource usage
  • User Analytics: User behavior and engagement tracking
  • Business Metrics: Revenue, conversions, and growth metrics

This architecture provides a solid foundation for building scalable, secure, and maintainable SaaS applications. The modular design allows for easy extension and customization based on specific business requirements.