Backend Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The backend for the YouTube Channel Analyzer is a Node.js application built with Express and tRPC. It serves as the API layer for the React frontend, handling business logic, data processing, authentication, and communication with external services like the YouTube Data API and Google Gemini AI. The architecture emphasizes a feature-based organization, type safety, and a clear separation of concerns.
The system is structured as part of a Turborepo monorepo, allowing for shared code between the frontend (web) and backend (api) applications. Key shared packages include @repo/types for TypeScript definitions, @repo/auth for authentication logic, and @repo/db for database interactions. This structure ensures consistency and reduces code duplication across the full stack.
Sources: README.md:5-41, apps/api/package.json
Core Technologies & Structure
The backend is built upon a modern TypeScript stack. The primary components and their roles are outlined below.
| Technology / Package | Role |
|---|---|
express | Core web server framework for handling HTTP requests and middleware. |
@trpc/server | Enables building fully type-safe APIs without code generation. |
better-auth | Handles all authentication, session management, and authorization. |
@google/genai | Client library for interacting with the Google Gemini AI API. |
zod | Used for schema declaration and validation, especially with tRPC. |
cors | Manages Cross-Origin Resource Sharing policies. |
@repo/db | Shared package for database schema (Drizzle ORM) and client (pg). |
@repo/auth | Shared package containing better-auth configuration. |
@repo/types | Shared package for common TypeScript types and interfaces. |
Sources: apps/api/package.json:15-25, README.md:44-48, packages/db/package.json:20-22
The following diagram illustrates the high-level interaction between the main components of the backend system.
Sources: README.md:5-41
Server Entrypoint & Middleware
The main entry point for the backend server is apps/api/src/index.ts. It initializes an Express application and configures the middleware stack. The order of middleware is critical for correct functionality, particularly for authentication.
Sources: apps/api/src/index.ts
Middleware Execution Flow
The server processes incoming requests through a specific sequence of middleware.
This diagram shows the request flow. The better-auth handler is mounted before express.json() to handle auth-related routes, which is a requirement of the library. All other API requests are parsed as JSON and then passed to the tRPC middleware.
Sources: apps/api/src/index.ts:20-41
Key Middleware Configuration
cors: Configured to allow requests from the frontend development server (http://localhost:3000) in development mode.
Sources: apps/api/src/index.ts:20-25better-authhandler: Mounted at/api/auth/*splat, it intercepts all authentication-related requests (e.g., sign-in, sign-up, provider callbacks). It must be placed before the JSON body parser.
Sources: apps/api/src/index.ts:31-32express.json(): Parses incoming request bodies with JSON payloads.
Sources: apps/api/src/index.ts:35trpcExpress.createExpressMiddleware: The main tRPC endpoint mounted at/trpc. It links theappRouterand thecreateContextfunction to handle all tRPC procedure calls.
Sources: apps/api/src/index.ts:38-44
API Layer (tRPC)
The project uses tRPC to create a type-safe API layer. This eliminates the need for manual type synchronization between the frontend and backend. The backend follows a "Server Services Pattern" where tRPC routers are thin layers that call business logic in service files.
Sources: README.md:83-85
Router and Service Structure
*.router.ts: Defines tRPC procedures and their input validation schemas (using Zod). These files are responsible for the API contract.*.service.ts: Contains the actual business logic, database queries, and calls to external APIs. This separates API definitions from their implementation.
The main appRouter merges feature-specific routers, such as ai.router.ts and youtube.router.ts.
Sources: README.md:23-33
Authentication and Authorization
Authentication is managed by the better-auth library, configured in the @repo/auth package. This provides a comprehensive solution for user management, sessions, and social logins.
Sources: packages/auth/src/auth.config.ts
Configuration (auth.config.ts)
- Database: Uses
drizzleAdapterto connectbetter-authto the project's PostgreSQL database via Drizzle ORM. - Providers: Supports both email/password and social OAuth providers (Google, Facebook).
- Session: Sessions are configured to expire in 7 days.
- Organization Plugin: The
organizationplugin is used to implement multi-tenancy, allowing users to be part of workspaces. - Database Hooks: A
databaseHooks.user.create.afterhook is implemented to automatically create a personal organization for every new user upon signup.
Sources: packages/auth/src/auth.config.ts:12-92
User Signup Flow
The following sequence diagram illustrates the user signup process, including the custom hook that creates a personal workspace.
Service Layer: AI Analysis
The AI feature logic resides in apps/api/src/features/ai/ai.service.ts. This service is responsible for interacting with the Google Gemini AI to analyze YouTube videos.
Sources: apps/api/src/features/ai/ai.service.ts
analyzeVideo Function
This function orchestrates the AI analysis of a given YouTube video.
- Initialization: It creates an instance of the
GoogleGenAIclient. - Prompt Engineering: It constructs a detailed prompt for the
gemini-2.5-flashmodel, including the video URL, title, description, and top comments to provide context. - Google Search Grounding: The request is configured with
tools: [{ googleSearch: {} }], allowing the AI model to access the public internet to find information about the video URL provided. - JSON Output: The prompt explicitly instructs the AI to return a strictly valid JSON object with a predefined structure (
summary,hooks,viralReasons,contentIdeas). - Response Parsing: The service parses the JSON from the AI's text response, with fallback logic to handle minor formatting inconsistencies.
- Source Extraction: It extracts the web sources used by the AI for grounding from the response metadata and appends them to the result.
Sources: apps/api/src/features/ai/ai.service.ts:11-78, apps/web/src/features/ai/components/video-analyzer.component.tsx:298-316
The flow is visualized below:
Database Schema
The application uses a PostgreSQL database with a schema managed by Drizzle ORM. The schema definitions are derived from Drizzle's snapshot files and the better-auth configuration. The core tables support authentication and multi-tenancy.
Sources: packages/db/drizzle/meta/0002_snapshot.json, packages/auth/src/auth.config.ts:12-16
Entity Relationship Diagram
This diagram shows the relationships between the main entities related to users, authentication, and organizations.