Skip to content

Starter Monorepo using Turbo of Nodejs + Fastify + OrchidORM + tRPC + Reactjs with opentelemetry setup

License

Notifications You must be signed in to change notification settings

teziapp/connected-repo-starter

Repository files navigation

Full-Stack TypeScript Monorepo

A production-ready Turborepo monorepo for building full-stack TypeScript applications with end-to-end type safety.

Tech Stack

Backend

  • Runtime: Node.js 22+
  • Framework: Fastify - Fast and low overhead web framework
  • API Layer:
    • tRPC - End-to-end typesafe APIs for internal/frontend communication
    • REST/OpenAPI - External product APIs with automatic Swagger documentation
  • Database: PostgreSQL with Orchid ORM
  • API Gateway: API key authentication, rate limiting, CORS validation, IP whitelisting, subscription management
  • Observability: OpenTelemetry integration
  • Security: Helmet, CORS, Rate Limiting, OAuth2 (Google)
  • Deployment: Docker support with automated migrations

Frontend

  • Framework: React 19 with Vite
  • Routing: React Router
  • Data Fetching: TanStack Query + tRPC Client
  • Type Safety: Direct TypeScript imports from backend

Tooling

  • Package Manager: Yarn (v1.22.22)
  • Monorepo: Turborepo
  • Linting: Biome
  • Formatting: Biome
  • TypeScript: v5.8.x with strict mode

Project Structure

.
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ backend/                      # Fastify server
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ modules/              # Feature modules
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ api-gateway/      # External REST API with OpenAPI
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth/             # OAuth2 + session management
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ journal-entries/  # Journal entry feature (tRPC)
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ users/            # User management (tRPC)
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ teams/            # Teams & members
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ subscriptions/    # API subscriptions
β”‚   β”‚   β”‚   β”‚   └── logs/             # API request logs
β”‚   β”‚   β”‚   β”œβ”€β”€ routers/              # Route aggregation
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ app.router.ts     # Main router
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ openapi.plugin.ts # OpenAPI/Swagger setup
β”‚   β”‚   β”‚   β”‚   └── trpc.router.ts    # tRPC routes
β”‚   β”‚   β”‚   β”œβ”€β”€ db/                   # Database layer
β”‚   β”‚   β”‚   β”œβ”€β”€ configs/              # App configuration
β”‚   β”‚   β”‚   β”œβ”€β”€ middlewares/          # Global middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ server.ts             # Entry point
β”‚   β”‚   β”‚   β”œβ”€β”€ app.ts                # Fastify setup
β”‚   β”‚   β”‚   └── trpc.ts               # tRPC initialization
β”‚   β”‚   β”œβ”€β”€ Dockerfile                # Docker configuration
β”‚   β”‚   β”œβ”€β”€ DEPLOYMENT.md             # Deployment guide
β”‚   β”‚   └── package.json
β”‚   └── frontend/                     # React + Vite
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ components/           # Reusable components
β”‚       β”‚   β”œβ”€β”€ pages/                # Page components
β”‚       β”‚   β”œβ”€β”€ modules/              # Feature modules
β”‚       β”‚   β”œβ”€β”€ App.tsx
β”‚       β”‚   └── router.tsx
β”‚       └── package.json
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ typescript-config/            # Shared TypeScript configs
β”‚   β”œβ”€β”€ ui-mui/                       # Material-UI component library
β”‚   └── zod-schemas/                  # Shared Zod schemas for validation
β”œβ”€β”€ turbo.json
└── package.json

Getting Started

Prerequisites

  • Node.js 22+
  • Yarn 1.22.22
  • PostgreSQL database

Installation

  1. Clone the repository:
git clone git@github.com:teziapp/connected-repo-starter.git
cd connected-repo-starter
  1. Install dependencies:
yarn install
  1. Set up environment variables:
# Copy environment examples
cp .env.example .env
cp apps/backend/.env.example apps/backend/.env
cp apps/frontend/.env.example apps/frontend/.env
  1. Configure your database connection in apps/backend/.env

  2. Create a PostgreSQL database, run migrations & seed data:

yarn run db create;
yarn run db up;
yarn run db seed;

Development

Start both frontend and backend in development mode:

yarn dev

Or run them individually:

# Backend only (http://localhost:3000)
cd apps/backend && yarn dev

# Frontend only (http://localhost:5173)
cd apps/frontend && yarn dev

Available Scripts

Development

  • yarn dev - Start all apps in watch mode
  • yarn build - Build all apps and packages
  • yarn lint - Run Biome linter across all workspaces
  • yarn format - Format code with Biome
  • yarn check-types - Type check all workspaces
  • yarn clean - Remove node_modules and build artifacts

Production

# Build and start the backend
cd apps/backend
yarn build
yarn start

Key Features

Dual API Architecture

tRPC for Internal APIs:

  • Type-safe APIs for frontend-backend communication
  • Zero code generation - types flow automatically
  • Routes: /trpc/*
  • Example: trpc.journalEntry.create.useMutation()

REST/OpenAPI for External APIs:

  • Automatic Swagger documentation at /api/documentation
  • OpenAPI 3.1.0 spec generation from Zod schemas
  • Routes: /api/v1/*
  • Full middleware chain: API key auth, rate limiting, CORS validation, IP whitelist, subscription tracking

API Gateway Features

Authentication & Authorization:

  • API key-based authentication (x-api-key + x-team-id headers)
  • Team-based access control with scrypt-hashed API keys
  • User-specific subscriptions (teamId + userId + productSku)
  • Bearer token authentication for webhooks

Security:

  • Global rate limiting (2 req/sec, burst 5 req/10sec in production)
  • Global CORS allows all origins; team-specific CORS validation via middleware
  • Per-team rate limiting (configurable requests per minute)
  • CORS validation against team's allowed domains with preflight handling
  • IP whitelist per team
  • OpenAPI security schemes (apiKey, teamId headers)
  • Request logging to api_product_request_logs table
  • 404 route protection with stricter rate limiting

Subscription Management:

  • Quota enforcement per subscription
  • Atomic real-time usage tracking
  • 90% usage threshold triggers webhook alert
  • Webhook queue with retry logic (3 max attempts, exponential backoff)
  • Batch processing limit: 50 webhooks per run
  • Configuration constants in api-gateway/constants/apiGateway.constants.ts

End-to-End Type Safety & Shared Schemas

The monorepo achieves full type safety without code generation:

  1. Backend exports router type from router.trpc.ts
  2. Frontend imports this type directly via TypeScript workspace references
  3. Shared Zod schemas in packages/zod-schemas/:
    • Entity schemas: <entity>CreateInputZod, <entity>UpdateInputZod, <entity>SelectAllZod
    • API product schemas with OpenAPI metadata
    • Enum definitions for request status, webhook status, etc.
  4. All API calls have autocomplete and compile-time type checking
// tRPC usage (internal)
const { data } = trpc.journalEntry.getAll.useQuery();
const create = trpc.journalEntry.create.useMutation();

// OpenAPI usage (external)
// See interactive docs at /api/documentation

Database Layer & Shared Validation

  • ORM: Orchid ORM with automatic snake_case conversion
  • Type Safety: Zod schemas for input validation across backend and frontend
  • Timestamps: Epoch milliseconds (number) not Date objects
  • Naming: Descriptive IDs (userId, teamId) and FKs (authorUserId)
  • Tables: Organized by feature module in modules/<feature>/tables/
  • Indexes: Composite indexes on frequently queried columns for performance

Key tables: users, sessions, teams, team_members, journal_entries, subscriptions, api_product_request_logs, webhook_call_queue

Error Handling

Multi-layer error handling system:

  • tRPC Layer: Transforms errors into structured responses
  • Error Parser: Converts database/validation errors to user-friendly messages
  • Fastify Handler: Catches unhandled errors

Security

Global:

  • Rate limiting: 2 req/sec, burst 5 req/10sec (production)
  • CORS allows all origins globally (team validation via middleware)
  • Helmet security headers
  • 404 route protection (stricter rate limiting)
  • Environment-based configuration

API Gateway:

  • API key authentication (scrypt hashed) via x-api-key + x-team-id headers
  • Team-based access control
  • Per-team rate limiting (configurable per minute)
  • Per-team CORS validation against allowedDomains with preflight handling
  • Per-team IP whitelist validation
  • OpenAPI security schemes defined
  • Internal routes secured by bearer token (INTERNAL_API_SECRET)
  • Webhook endpoints secured by bearer token (team.subscriptionAlertWebhookBearerToken)

Observability

  • OpenTelemetry integration for tracing
  • Custom spans for tRPC errors

Adding New Features

New Database Table

  1. Create table in apps/backend/src/modules/<feature>/tables/<entity>.table.ts
    • Use descriptive IDs: userId, teamId (not generic id)
    • Use descriptive FKs: authorUserId (not just authorId)
    • Use timestampNumber for timestamps (epoch milliseconds)
  2. Create Zod schemas in packages/zod-schemas/src/<entity>.zod.ts
  3. Register table in apps/backend/src/db/db.ts
  4. Run yarn run db g <migration_name> then yarn run db up

New tRPC Endpoint (Internal API)

  1. Import schema from @connected-repo/zod-schemas/<entity>.zod
  2. Create procedure in apps/backend/src/modules/<feature>/<feature>.trpc.ts
  3. Register in apps/backend/src/routers/trpc.router.ts
  4. Use protectedProcedure for operations requiring auth
  5. Frontend auto-gets types via tRPC router type import

New API Product Endpoint (External OpenAPI)

  1. Define Zod schemas in packages/zod-schemas/src/<entity>.zod.ts
  2. Add product to API_PRODUCTS array in packages/zod-schemas/src/enums.zod.ts
  3. Create handler in apps/backend/src/modules/api-gateway/handlers/<product>.handler.ts
  4. Add route in apps/backend/src/modules/api-gateway/api-gateway.router.ts:
    • Use .withTypeProvider<FastifyZodOpenApiTypeProvider>()
    • Apply middleware chain (apiKeyAuth, CORS, whitelist, rateLimit, subscriptionCheck)
  5. Test via Swagger UI at /api/documentation

New Frontend Page

  1. Create component in apps/frontend/src/pages/ or modules/<feature>/pages/
  2. Add route in apps/frontend/src/router.tsx with lazy loading
  3. Use tRPC hooks for data fetching

Turborepo

This monorepo uses Turborepo for task orchestration. Key tasks:

  • build - Builds with dependency graph awareness
  • dev - Runs development servers (persistent, no cache)
  • check-types - Type checking across workspaces
  • clean - Cleanup task

Learn more:

Documentation

API Documentation

Interactive API Documentation:

Endpoints:

License

[AGPL-3.0] (./LICENSE) Copyright (c) 2025 Tezi Communications LLP, India

About

Starter Monorepo using Turbo of Nodejs + Fastify + OrchidORM + tRPC + Reactjs with opentelemetry setup

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 5