npm package: @odvi/dtt-framework
Description: [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![Version](https://img.shields.io/badge/version-0.1.0-green.svg)](package.json) [![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com
Latest version: 0.1.1

# DTT Framework

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-0.1.0-green.svg)](package.json)
[![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/yourusername/dtt-framework)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)

A production-ready Next.js boilerplate framework designed for building enterprise applications with integrated services. The DTT Framework provides a comprehensive foundation for developing modern web applications with authentication, database management, storage, edge computing, data warehousing, and API integration capabilities.

---

## Table of Contents

- [Introduction](#introduction)
- [Key Features](#key-features)
- [Why Use This Framework](#why-use-this-framework)
- [Tech Stack](#tech-stack)
- [Quick Start](#quick-start)
- [Folder Structure](#folder-structure)
- [Configuration](#configuration)
- [Health Check System](#health-check-system)
- [Authentication](#authentication)
- [Development](#development)
- [Deployment](#deployment)
- [Documentation](#documentation)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

---

## Introduction

The DTT Framework is a modern, full-stack application framework built on top of Next.js 15 with the App Router. It provides a complete starting point for developers who need to quickly scaffold applications that require multiple service integrations.

### What is DTT Framework?

DTT Framework is a carefully curated collection of technologies and best practices for building enterprise-grade applications. It includes:

- **Authentication & Authorization**: Built-in user management with Clerk
- **Database Operations**: PostgreSQL via Supabase with Drizzle ORM
- **File Storage**: Supabase Storage for uploads and downloads
- **Serverless Computing**: Supabase Edge Functions
- **Data Analytics**: Snowflake data warehouse integration
- **API Layer**: Lightweight Hono framework for backend routes
- **State Management**: TanStack Query and Zustand for data handling
- **Health Monitoring**: Comprehensive health check dashboard

### Target Audience

This framework is ideal for:

- **Enterprise Developers**: Building business applications with complex integrations
- **Startups**: Rapidly prototyping and scaling applications
- **AI-Assisted Development (Vibe Coding)**: AI assistants can understand the structure and help with development
- **Full-Stack Teams**: Needing a unified stack for both frontend and backend
- **Data-Driven Applications**: Requiring analytics and reporting capabilities

---

## Key Features

### 1. Authentication & User Management
- **Clerk Integration**: Complete authentication solution with sign-in, sign-up, and user management
- **Organization Support**: Multi-tenant architecture with organization memberships
- **Webhook Synchronization**: Automatic user data sync to local database
- **Protected Routes**: Middleware-based route protection

### 2. Database Layer
- **PostgreSQL**: Robust relational database via Supabase
- **Drizzle ORM**: Type-safe database queries with excellent TypeScript support
- **Connection Pooling**: Optimized for Supabase Transaction mode
- **Schema Management**: Migration-based schema evolution

### 3. Storage & Edge Computing
- **Supabase Storage**: File upload/download with signed URLs
- **Edge Functions**: Serverless compute with auth header passthrough
- **Bucket Management**: Organized file storage structure

### 4. Data Warehouse
- **Snowflake Integration**: Direct connection to Snowflake data warehouse
- **Query Execution**: Execute SQL queries from the application
- **Warehouse Configuration**: Support for multiple warehouses and databases

### 5. API Layer
- **Hono Framework**: Lightweight and fast API framework
- **Middleware Support**: Authentication, logging, CORS
- **Route Organization**: Modular route structure
- **Type Safety**: Full TypeScript support with inferred types

### 6. State Management
- **TanStack Query**: Server state management with caching and synchronization
- **Zustand**: Lightweight client state management
- **React Hooks**: Custom hooks for common patterns

### 7. Health Check System
- **Comprehensive Monitoring**: Health checks for all integrated services
- **Dashboard UI**: Visual health status display
- **Response Time Tracking**: Performance monitoring
- **Error Reporting**: Detailed error messages and status codes

### 8. Developer Experience
- **TypeScript**: Full type safety across the stack
- **Tailwind CSS**: Utility-first styling
- **Shadcn/ui**: Beautiful, accessible UI components
- **Hot Reload**: Fast development with Next.js Turbo
- **Linting & Formatting**: ESLint and Prettier configured

---

## Why Use This Framework

### Rapid Development
Get started in minutes with pre-configured services and integrations. Focus on building your business logic instead of setting up infrastructure.

### Production Ready
Built with best practices for scalability, security, and performance. Every component is designed to handle production workloads.

### Type Safety First
Leverage TypeScript at every layer for compile-time error detection. Catch bugs before they reach production.

### AI-Friendly Structure
Clear naming conventions and modular architecture make it easy for AI assistants to understand and help with development.

### Comprehensive Documentation
Detailed guides for every aspect of the framework, from setup to deployment.

---

## Tech Stack

### Technology Summary

| Category | Technology | Version | Purpose |
|----------|------------|---------|---------|
| **Framework** | Next.js | ^15.2.3 | Full-stack React framework with App Router |
| **Language** | TypeScript | ^5.8.2 | Type-safe development |
| **Runtime** | Node.js | 20+ | JavaScript runtime |
| **Package Manager** | pnpm | 10.26.1 | Fast, disk space efficient package manager |
| **Styling** | Tailwind CSS | ^4.0.15 | Utility-first CSS framework |
| **UI Components** | Shadcn/ui | Latest | Accessible component primitives |
| **Icons** | Lucide React | ^0.562.0 | Icon library |
| **Authentication** | Clerk | ^6.36.5 | User authentication & management |
| **Webhooks** | Svix | ^1.82.0 | Webhook delivery and verification |
| **Database** | Supabase (PostgreSQL) | Latest | Primary database |
| **ORM** | Drizzle ORM | ^0.41.0 | Type-safe database queries |
| **Database Driver** | postgres | ^3.4.4 | PostgreSQL driver |
| **Storage** | Supabase Storage | Latest | File storage |
| **Edge Functions** | Supabase Edge Functions | Latest | Serverless compute |
| **Data Warehouse** | Snowflake SDK | ^2.3.3 | Analytics & reporting |
| **API Framework** | Hono | ^4.11.3 | Lightweight API framework |
| **Server State** | TanStack Query | ^5.90.14 | Data fetching & caching |
| **Client State** | Zustand | ^5.0.9 | UI state management |
| **Validation** | Zod | ^3.24.2 | Schema validation |
| **Environment** | @t3-oss/env-nextjs | ^0.12.0 | Type-safe environment variables |

### Detailed Tech Stack Documentation

For a complete breakdown of all technologies, their purposes, and why they were chosen, see the [Tech Stack Documentation](docs/framework/02-techstack.md).

---

## Quick Start

### Prerequisites

Before you begin, ensure you have the following installed:

- **Node.js** 20 or higher ([Download](https://nodejs.org/))
- **pnpm** 10 or higher ([Install](https://pnpm.io/installation))
- **Supabase account** ([Sign up](https://supabase.com/)) - for database, storage, and edge functions
- **Clerk account** ([Sign up](https://clerk.com/)) - for authentication
- **Snowflake account** (optional) - for data warehouse integration

### Installation via CLI

The easiest way to get started is using the CLI:

```bash
pnpm create dtt-framework@latest my-app
cd my-app
```

### Manual Installation

1. **Clone the repository:**
   ```bash
   git clone https://github.com/yourusername/dtt-framework.git
   cd dtt-framework
   ```

2. **Install dependencies:**
   ```bash
   pnpm install
   ```

3. **Configure environment variables:**
   ```bash
   cp .env.example .env
   # Edit .env with your credentials
   ```

4. **Set up the database:**
   ```bash
   pnpm db:push
   ```

5. **Start the development server:**
   ```bash
   pnpm dev
   ```

6. **Open your browser:**
   ```
   http://localhost:3000
   ```

7. **Deploy Edge Functions (Required for Health Checks):**
   The framework uses Supabase Edge Functions. You must deploy the included `health-check` function for the health dashboard to fully pass.
   
   ```bash
   # Login to Supabase
   npx supabase login
   
   # Link your project (get your-project-ref from Supabase dashboard URL)
   npx supabase link --project-ref your-project-ref
   
   # Deploy the function
   npx supabase functions deploy health-check
   ```

### Environment Setup

Copy the [`.env.example`](.env.example) file to `.env` and fill in your credentials:

```bash
# Application
NEXT_PUBLIC_APP_URL=http://localhost:3000

# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxx
CLERK_SECRET_KEY=sk_test_xxx
CLERK_WEBHOOK_SECRET=whsec_xxx
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/health
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/health

# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJxxx
SUPABASE_SERVICE_ROLE_KEY=eyJxxx
DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres

# Snowflake (Optional)
SNOWFLAKE_ACCOUNT=ef19411.ap-southeast-1
SNOWFLAKE_AUTHENTICATOR=SNOWFLAKE_JWT
SNOWFLAKE_USERNAME=APP_USER_WITH_KEY_AUTH
SNOWFLAKE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
        -----END PRIVATE KEY-----"
SNOWFLAKE_PRIVATE_KEY_PASSPHRASE="<password>"
SNOWFLAKE_WAREHOUSE=COMPUTE_WH
SNOWFLAKE_ROLE=ACCOUNTADMIN
SNOWFLAKE_LOGGING=true
```

For detailed environment variable configuration, see [Environment Variables Documentation](docs/framework/environment-variables.md).

### Running the Development Server

```bash
# Start development server with Turbo mode
pnpm dev

# Or without Turbo
pnpm dev --no-turbo
```

The application will be available at `http://localhost:3000`.

### Accessing the Health Dashboard

Once the server is running, visit the health dashboard to verify all services are working:

```
http://localhost:3000/health
```

---

## Folder Structure

```
dtt-framework/
├── docs/                          # Framework documentation
│   └── framework/                 # Detailed documentation files
│       ├── 01-overview.md         # Framework overview
│       ├── 02-techstack.md        # Technology stack details
│       ├── api-layer.md           # API layer documentation
│       ├── clerk-authentication.md # Clerk setup guide
│       ├── cli-installation.md    # CLI installation guide
│       ├── environment-variables.md # Environment variables reference
│       ├── health-check-system.md # Health check system guide
│       ├── implementation.md      # Implementation details
│       ├── snowflake-integration.md # Snowflake setup
│       ├── state-management.md    # State management patterns
│       ├── supabase-integration.md # Supabase setup
│       ├── testing-guide.md       # Testing patterns
│       └── what-did-i-miss.md     # Checklist
│
├── public/                        # Static assets
│   └── favicon.ico                # Favicon
│
├── src/                           # Source code
│   ├── app/                       # Next.js App Router
│   │   ├── (auth)/               # Auth routes group
│   │   │   ├── layout.tsx        # Auth layout
│   │   │   ├── sign-in/          # Sign-in page
│   │   │   │   └── [[...sign-in]]/
│   │   │   │       └── page.tsx
│   │   │   └── sign-up/          # Sign-up page
│   │   │       └── [[...sign-up]]/
│   │   │           └── page.tsx
│   │   │
│   │   ├── (dashboard)/          # Protected dashboard routes
│   │   │   ├── layout.tsx        # Dashboard layout
│   │   │   ├── page.tsx          # Dashboard home
│   │   │   └── health/           # Health check page
│   │   │       └── page.tsx
│   │   │
│   │   ├── api/                  # API routes (Hono mount point)
│   │   │   ├── [[...route]]/     # Hono catch-all route
│   │   │   │   └── route.ts
│   │   │   └── webhooks/         # Webhook handlers
│   │   │       └── clerk/
│   │   │           └── route.ts
│   │   │
│   │   ├── layout.tsx            # Root layout
│   │   ├── page.tsx              # Landing page
│   │   └── providers.tsx         # React providers
│   │
│   ├── components/               # React components
│   │   ├── ui/                  # Shadcn/ui components
│   │   │   ├── badge.tsx
│   │   │   ├── button.tsx
│   │   │   ├── card.tsx
│   │   │   └── collapsible.tsx
│   │   ├── layouts/             # Layout components
│   │   │   └── navbar.tsx
│   │   └── shared/              # Shared components
│   │       └── loading-spinner.tsx
│   │
│   ├── features/               # Feature modules
│   │   └── health-check/       # Health check feature
│   │       ├── components/
│   │       │   └── health-dashboard.tsx
│   │       ├── config.ts
│   │       ├── types.ts
│   │       └── index.ts
│   │
│   ├── hooks/                  # React hooks
│   │   ├── queries/           # TanStack Query hooks
│   │   │   └── use-health-checks.ts
│   │   └── utils/             # Utility hooks
│   │       └── use-debounce.ts
│   │
│   ├── lib/                    # Utility libraries
│   │   ├── supabase/          # Supabase clients
│   │   │   ├── admin.ts
│   │   │   ├── client.ts
│   │   │   └── server.ts
│   │   ├── snowflake/         # Snowflake client
│   │   │   └── client.ts
│   │   ├── nextbank/          # NextBank client
│   │   │   └── client.ts
│   │   ├── utils.ts           # Utility functions
│   │   └── validators.ts      # Zod schemas
│   │
│   ├── server/                # Server-side code
│   │   ├── api/               # Hono API setup
│   │   │   ├── index.ts       # Hono app instance
│   │   │   ├── middleware/    # API middleware
│   │   │   │   ├── auth.ts
│   │   │   │   └── logger.ts
│   │   │   └── routes/        # API routes
│   │   │       ├── users.ts
│   │   │       ├── health/
│   │   │       │   ├── index.ts
│   │   │       │   ├── clerk.ts
│   │   │       │   ├── database.ts
│   │   │       │   ├── edge-functions.ts
│   │   │       │   ├── nextbank.ts
│   │   │       │   ├── snowflake.ts
│   │   │       │   └── storage.ts
│   │   │       └── users/
│   │   └── db/                # Database setup
│   │       ├── index.ts       # Database instance
│   │       ├── schema/        # Drizzle schemas
│   │       │   ├── index.ts
│   │       │   ├── health-checks.ts
│   │       │   └── users.ts
│   │       ├── queries/       # Database queries
│   │       │   └── users.ts
│   │       └── migrations/    # Migration files
│   │
│   ├── stores/                # Zustand stores
│   │   └── ui-store.ts
│   ├── types/                 # TypeScript types
│   │   └── index.ts
│   ├── config/                # Configuration files
│   │   ├── env.ts             # Environment validation
│   │   └── site.ts            # Site configuration
│   ├── env.js                 # Environment variables
│   ├── middleware.ts          # Next.js middleware
│   └── styles/                # Styles
│       └── globals.css        # Global styles
│
├── .env.example                # Environment variables template
├── .gitignore                  # Git ignore file
├── .npmrc                      # npm configuration
├── components.json             # Shadcn/ui configuration
├── DESIGN.md                   # Design document
├── drizzle.config.ts           # Drizzle ORM configuration
├── eslint.config.js            # ESLint configuration
├── next.config.js              # Next.js configuration
├── package.json                # Dependencies and scripts
├── pnpm-lock.yaml              # pnpm lock file
├── postcss.config.js           # PostCSS configuration
├── prettier.config.js          # Prettier configuration
├── start-database.sh           # Database startup script
├── tsconfig.json               # TypeScript configuration
└── README.md                   # This file
```

### Key Folders Explained

| Folder | Purpose |
|--------|---------|
| [`docs/`](docs/) | Complete framework documentation |
| [`src/app/`](src/app/) | Next.js App Router pages and routes |
| [`src/components/`](src/components/) | Reusable React components |
| [`src/features/`](src/features/) | Feature-specific modules |
| [`src/hooks/`](src/hooks/) | Custom React hooks |
| [`src/lib/`](src/lib/) | Utility libraries and clients |
| [`src/server/`](src/server/) | Server-side code (API, database) |
| [`src/stores/`](src/stores/) | Zustand state stores |

---

## Configuration

### Environment Variables

The framework uses environment variables to configure services. All variables are validated at build time using [`@t3-oss/env-nextjs`](src/config/env.ts).

### Required Variables

#### Application
- `NEXT_PUBLIC_APP_URL` - Your application's URL

#### Clerk Authentication
- `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` - Clerk publishable key
- `CLERK_SECRET_KEY` - Clerk secret key
- `CLERK_WEBHOOK_SECRET` - Clerk webhook secret
- `NEXT_PUBLIC_CLERK_SIGN_IN_URL` - Sign-in page URL
- `NEXT_PUBLIC_CLERK_SIGN_UP_URL` - Sign-up page URL
- `NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL` - Redirect after sign-in
- `NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL` - Redirect after sign-up

#### Supabase
- `NEXT_PUBLIC_SUPABASE_URL` - Supabase project URL
- `NEXT_PUBLIC_SUPABASE_ANON_KEY` - Supabase anonymous key
- `SUPABASE_SERVICE_ROLE_KEY` - Supabase service role key
- `DATABASE_URL` - PostgreSQL connection string

### Optional Variables

#### Snowflake
- `SNOWFLAKE_ACCOUNT` - Snowflake account identifier
- `SNOWFLAKE_USERNAME` - Snowflake username
- `SNOWFLAKE_PASSWORD` - Snowflake password
- `SNOWFLAKE_WAREHOUSE` - Warehouse name
- `SNOWFLAKE_DATABASE` - Database name
- `SNOWFLAKE_SCHEMA` - Schema name
- `SNOWFLAKE_ROLE` - Role name

#### NextBank (Placeholder)
- `NEXTBANK_API` - NextBank API URL
- `NEXTBANK_API_USERNAME` - NextBank API username
- `NEXTBANK_API_PASSWORD` - NextBank API password

### Detailed Configuration

For complete details on each environment variable, how to obtain them, and security considerations, see the [Environment Variables Documentation](docs/framework/environment-variables.md).

### Service Configuration

Each service has its own configuration file:

- [`src/config/env.ts`](src/config/env.ts) - Environment variable validation
- [`src/config/site.ts`](src/config/site.ts) - Site configuration
- [`drizzle.config.ts`](drizzle.config.ts) - Drizzle ORM configuration
- [`next.config.js`](next.config.js) - Next.js configuration

---

## Health Check System

### What is the Health Check System?

The Health Check System provides comprehensive monitoring of all integrated services. It verifies that each service is properly configured and functioning correctly, providing real-time visibility into the system's health.

### Accessing the Health Dashboard

Navigate to `/health` in your application:

```
http://localhost:3000/health
```

### Dashboard Features

- **Overall System Status Card**: Shows aggregate health status with total response time
- **"Run All" Button**: Execute all health checks with a counter showing total number of checks
- **Individual Service Cards**: Each service has its own card with status badge
- **Individual Check Buttons**: Each health check has a dedicated "Run Check" button
- **Real-time Results Display**: Check results appear below each button with detailed information
- **Response Time Tracking**: Monitor performance of each service
- **Error Reporting**: Detailed error messages and status codes
- **Loading States**: Visual feedback while checks are in progress

### Available Endpoints

| Service | Endpoint | Method | Description |
|----------|----------|--------|-------------|
| **Clerk** | `/api/health/clerk/user` | GET | Get current user |
| **Clerk** | `/api/health/clerk/org` | GET | Get organization membership |
| **Clerk** | `/api/health/clerk/members` | GET | List organization members |
| **Database** | `/api/health/database/write` | POST | Write test row to database |
| **Database** | `/api/health/database/read` | GET | Read test row from database |
| **Database** | `/api/health/database/delete` | DELETE | Delete test row from database |
| **Storage** | `/api/health/storage/upload` | POST | Upload test file to storage |
| **Storage** | `/api/health/storage/download` | GET | Generate signed URL for test file |
| **Storage** | `/api/health/storage/delete` | DELETE | Delete test file from storage |
| **Edge Functions** | `/api/health/edge/ping` | GET | Ping edge function |
| **Edge Functions** | `/api/health/edge/auth` | GET | Test auth header passthrough |
| **Snowflake** | `/api/health/snowflake/connect` | GET | Test Snowflake connection |
| **Snowflake** | `/api/health/snowflake/query` | GET | Execute test query |
| **NextBank** | `/api/health/nextbank/ping` | GET | Ping NextBank API |
| **NextBank** | `/api/health/nextbank/auth` | GET | Test NextBank authentication |
| **All** | `/api/health/all` | GET | Run all health checks |

### Status Types

| Status | Description | Color |
|---------|-------------|--------|
| **healthy** | Service is functioning correctly | Green |
| **unhealthy** | Service is not functioning | Red |
| **error** | Check failed with an error | Red |
| **pending** | Check is in progress | Yellow |
| **unconfigured** | Service is not configured | Gray |

### Using the Health Check Hook

```typescript
import { useHealthChecks } from '@/hooks/queries/use-health-checks'

function MyComponent() {
  const { data, isLoading, error, refetch } = useHealthChecks()

  if (isLoading) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <div>
      <h1>Status: {data?.status}</h1>
      <button onClick={() => refetch()}>Refresh</button>
    </div>
  )
}
```

### Detailed Documentation

For complete information on the health check system, including how to add new health checks, see the [Health Check System Documentation](docs/framework/health-check-system.md).

---

## Authentication

### Clerk Setup

The framework uses [Clerk](https://clerk.com/) for authentication and user management.

### Setting Up Clerk

1. **Create a Clerk Account**
   - Go to [clerk.com](https://clerk.com/) and sign up
   - Create a new application
   - Note down your API keys from the dashboard

2. **Configure Environment Variables**
   ```bash
   NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxx
   CLERK_SECRET_KEY=sk_test_xxx
   CLERK_WEBHOOK_SECRET=whsec_xxx
   ```

3. **Configure Clerk Webhook**
   - Go to Clerk Dashboard → Your App → Webhooks
   - Add endpoint: `https://your-domain.com/api/webhooks/clerk`
   - Select events: `user.created`, `user.updated`, `user.deleted`, `organizationMembership.created`, `organizationMembership.updated`
   - Copy the webhook secret to your `.env` file

### Protected Routes

The framework uses middleware to protect routes. The middleware is configured in [`src/middleware.ts`](src/middleware.ts).

**Public Routes:**
- `/sign-in` - Sign-in page
- `/sign-up` - Sign-up page
- `/api/webhooks/*` - Webhook endpoints

**Protected Routes:**
All other routes require authentication. Unauthenticated users are redirected to the sign-in page.

### Clerk Components

The framework includes pre-configured Clerk components:

- [`<SignIn />`](src/app/(auth)/sign-in/[[...sign-in]]/page.tsx) - Sign-in page
- [`<SignUp />`](src/app/(auth)/sign-up/[[...sign-up]]/page.tsx) - Sign-up page
- [`<UserButton />`](src/components/layouts/navbar.tsx) - User menu component

### Using Clerk Hooks

```typescript
import { useAuth } from '@clerk/nextjs'

export function MyComponent() {
  const { userId, isLoaded, isSignedIn, orgId, orgRole } = useAuth()

  if (!isLoaded) return <div>Loading...</div>
  if (!isSignedIn) return <div>Not signed in</div>

  return <div>User ID: {userId}, Org: {orgId}</div>
}
```

### Server-Side Authentication

```typescript
import { getAuth } from '@clerk/nextjs/server'

export async function getServerData() {
  const auth = getAuth()

  return {
    userId: auth.userId,
    orgId: auth.orgId,
    orgRole: auth.orgRole,
  }
}
```

### Detailed Documentation

For complete information on Clerk authentication, including webhook setup, organization management, and security considerations, see the [Clerk Authentication Documentation](docs/framework/clerk-authentication.md).

---

## Development

### Available Scripts

| Script | Description |
|--------|-------------|
| `pnpm dev` | Start development server with Turbo |
| `pnpm build` | Build for production |
| `pnpm start` | Start production server |
| `pnpm preview` | Preview production build locally |
| `pnpm lint` | Run ESLint |
| `pnpm lint:fix` | Fix ESLint errors |
| `pnpm format:check` | Check code formatting |
| `pnpm format:write` | Format code with Prettier |
| `pnpm typecheck` | Run TypeScript type checking |
| `pnpm check` | Run all checks (lint + typecheck) |
| `pnpm db:generate` | Generate database migrations |
| `pnpm db:migrate` | Apply database migrations |
| `pnpm db:push` | Push schema changes to database |
| `pnpm db:studio` | Open Drizzle Studio |

### Database Migrations

The framework uses Drizzle ORM for database migrations.

**Generate a migration:**
```bash
pnpm db:generate
```

**Apply migrations:**
```bash
pnpm db:migrate
```

**Push schema changes (development only):**
```bash
pnpm db:push
```

**Open Drizzle Studio:**
```bash
pnpm db:studio
```

### Code Quality Tools

**ESLint:**
```bash
# Run linter
pnpm lint

# Fix issues
pnpm lint:fix
```

**Prettier:**
```bash
# Check formatting
pnpm format:check

# Format code
pnpm format:write
```

**TypeScript:**
```bash
# Type check
pnpm typecheck

# Run all checks
pnpm check
```

### Testing

The framework includes testing configuration. For detailed testing patterns and practices, see the [Testing Guide](docs/framework/testing-guide.md).

### Development Workflow

1. **Create a new branch:**
   ```bash
   git checkout -b feature/your-feature
   ```

2. **Make your changes**

3. **Run checks:**
   ```bash
   pnpm check
   pnpm format:write
   ```

4. **Test your changes:**
   ```bash
   pnpm dev
   ```

5. **Commit your changes:**
   ```bash
   git add .
   git commit -m "feat: add your feature"
   ```

6. **Push and create a pull request**

---

## Deployment

### Vercel Deployment

Vercel is the recommended deployment platform for Next.js applications.

**Prerequisites:**
- Vercel account ([Sign up](https://vercel.com/))
- Git repository (GitHub, GitLab, or Bitbucket)

**Steps:**

1. **Push your code to a Git repository**

2. **Import project in Vercel:**
   - Go to [vercel.com](https://vercel.com/)
   - Click "New Project"
   - Import your repository

3. **Configure environment variables:**
   - Add all required environment variables from [`.env.example`](.env.example)
   - Make sure to use production values, not test values

4. **Deploy:**
   - Click "Deploy"
   - Vercel will build and deploy your application

5. **Configure custom domain (optional):**
   - Go to project settings → Domains
   - Add your custom domain
   - Update `NEXT_PUBLIC_APP_URL` in environment variables

**Environment Variables for Vercel:**
```bash
# Application
NEXT_PUBLIC_APP_URL=https://your-app.vercel.app

# Clerk
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_xxx
CLERK_SECRET_KEY=sk_live_xxx
CLERK_WEBHOOK_SECRET=whsec_xxx

# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJxxx
SUPABASE_SERVICE_ROLE_KEY=eyJxxx
DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres
```

### DigitalOcean Deployment

For DigitalOcean deployment, you can use the App Platform or Droplets.

**Using App Platform:**

1. **Push your code to a Git repository**

2. **Create a new App in DigitalOcean:**
   - Go to DigitalOcean → Apps
   - Click "Create App"
   - Connect your repository

3. **Configure the app:**
   - Runtime: Node.js
   - Build command: `pnpm build`
   - Run command: `pnpm start`
   - Install command: `pnpm install`

4. **Add environment variables:**
   - Add all required variables from [`.env.example`](.env.example)

5. **Deploy:**
   - Click "Create Resources"
   - Wait for deployment to complete

**Using Droplets:**

1. **Create a Droplet:**
   - Choose a Droplet with Node.js support
   - SSH into the Droplet

2. **Install dependencies:**
   ```bash
   curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
   sudo apt-get install -y nodejs
   npm install -g pnpm
   ```

3. **Clone your repository:**
   ```bash
   git clone https://github.com/yourusername/dtt-framework.git
   cd dtt-framework
   ```

4. **Install and build:**
   ```bash
   pnpm install
   pnpm build
   ```

5. **Run with PM2:**
   ```bash
   npm install -g pm2
   pm2 start pnpm --name "dtt-framework" -- start
   ```

6. **Configure Nginx:**
   - Set up Nginx as a reverse proxy
   - Configure SSL with Let's Encrypt

### Domain Configuration

After deployment, configure your custom domain:

1. **Update DNS records:**
   - Add an A record pointing to your server IP
   - Or add a CNAME record for Vercel

2. **Update environment variables:**
   - Set `NEXT_PUBLIC_APP_URL` to your custom domain

3. **Configure SSL:**
   - Vercel: Automatic SSL
   - DigitalOcean: Use Let's Encrypt

### Environment Variables Setup

For production, always use production API keys:

**Clerk:**
- Use keys from the Production environment in Clerk Dashboard
- Update webhook endpoint to production URL

**Supabase:**
- Use production project URL and keys
- Ensure database connection string uses production database

**Supabase Edge Functions:**
- Deploy your health-check function:
  ```bash
  # Login to Supabase CLI
  npx supabase login
  
  # Deploy the function
  npx supabase functions deploy health-check
  ```
- **Note:** The "Test Auth Header" health check requires you to be logged into the dashboard to pass. If you are not logged in, it will show a warning.

**Snowflake:**
- Use production warehouse and credentials

### Deployment Checklist

- [ ] Update `NEXT_PUBLIC_APP_URL` to production URL
- [ ] Use production API keys for all services
- [ ] Configure webhook endpoints to production URL
- [ ] Deploy Supabase Edge Functions (`npx supabase functions deploy health-check`)
- [ ] Push database schema (`pnpm db:push` or migration)
- [ ] Set up custom domain (if applicable)
- [ ] Configure SSL/HTTPS
- [ ] Set up monitoring and error tracking
- [ ] Configure database backups
- [ ] Test all health check endpoints
- [ ] Verify authentication flow
- [ ] Test critical user flows

---

## Documentation

The DTT Framework includes comprehensive documentation to help you understand and use every aspect of the framework.

### Core Documentation

| Document | Description |
|----------|-------------|
| [Overview](docs/framework/01-overview.md) | Framework introduction and architecture |
| [Tech Stack](docs/framework/02-techstack.md) | Complete technology breakdown |
| [Environment Variables](docs/framework/environment-variables.md) | Environment variables reference |
| [CLI Installation](docs/framework/cli-installation.md) | Installation and setup guide |

### Integration Guides

| Document | Description |
|----------|-------------|
| [Clerk Authentication](docs/framework/clerk-authentication.md) | Clerk setup and configuration |
| [Supabase Integration](docs/framework/supabase-integration.md) | Database and storage setup |
| [Snowflake Integration](docs/framework/snowflake-integration.md) | Data warehouse setup |

### Development Guides

| Document | Description |
|----------|-------------|
| [API Layer](docs/framework/api-layer.md) | Hono API implementation |
| [State Management](docs/framework/state-management.md) | TanStack Query and Zustand patterns |
| [Health Check System](docs/framework/health-check-system.md) | Health monitoring guide |
| [Testing Guide](docs/framework/testing-guide.md) | Testing patterns and practices |

### Additional Resources

| Document | Description |
|----------|-------------|
| [Implementation Guide](docs/framework/implementation.md) | How the framework was built |
| [What Did I Miss](docs/framework/what-did-i-miss.md) | Setup checklist |

### How to Navigate the Docs

1. **Start with the [Overview](docs/framework/01-overview.md)** to understand the framework
2. **Review the [Tech Stack](docs/framework/02-techstack.md)** to learn about the technologies
3. **Follow the [Quick Start](#quick-start)** guide to get up and running
4. **Configure [Environment Variables](docs/framework/environment-variables.md)** for your services
5. **Set up [Clerk Authentication](docs/framework/clerk-authentication.md)** for user management
6. **Configure [Supabase Integration](docs/framework/supabase-integration.md)** for database and storage
7. **Set up [Snowflake Integration](docs/framework/snowflake-integration.md)** if needed
8. **Explore the [API Layer](docs/framework/api-layer.md)** for backend development
9. **Learn about [State Management](docs/framework/state-management.md)** patterns
10. **Use the [Health Check System](docs/framework/health-check-system.md)** to monitor services

---

## Troubleshooting

### Common Issues and Solutions

#### Issue: "Environment variable not found"

**Solution:**
```bash
# Check if .env exists
ls -la .env

# Copy from example if missing
cp .env.example .env

# Edit .env with your values
# Restart development server
pnpm dev
```

#### Issue: "Database connection failed"

**Solution:**
```bash
# Verify DATABASE_URL is correct
# Check for correct mode (Transaction vs Session)
# Transaction mode: port 6543, .pooler. domain
# Session mode: port 5432, direct domain

# Test connection
psql $DATABASE_URL
```

#### Issue: "Clerk webhook verification failed"

**Solution:**
- Verify `CLERK_WEBHOOK_SECRET` is correct
- Check that the webhook endpoint URL is correct
- Ensure the webhook is enabled in Clerk dashboard

#### Issue: "Health check shows unconfigured"

**Solution:**
- Verify environment variables are set
- Check if service credentials are correct
- Ensure service is enabled in configuration

#### Issue: "Build fails with type errors"

**Solution:**
```bash
# Run type check to see errors
pnpm typecheck

# Fix type errors in your code
# Or run with validation skipped (not recommended)
SKIP_ENV_VALIDATION=true pnpm build
```

#### Issue: "User not redirected after sign-in"

**Solution:**
- Check `NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL` environment variable
- Verify middleware configuration
- Check browser console for errors

#### Issue: "Organization ID not syncing"

**Solution:**
- Verify organization webhooks are enabled
- Check webhook logs in Clerk dashboard
- Ensure `organizationMembership.created` event is selected

#### Issue: "Snowflake connection fails"

**Solution:**
- Verify `SNOWFLAKE_ACCOUNT` format: `[account_locator].[region]`
- Check username and password are correct
- Ensure warehouse, database, and schema exist
- Verify user has necessary permissions

#### Issue: "Storage upload fails"

**Solution:**
- Verify `NEXT_PUBLIC_SUPABASE_URL` and keys are correct
- Check if storage bucket exists
- Ensure user has upload permissions
- Check Row Level Security policies

### Getting Help

If you're still having issues:

1. **Check the documentation** - Most issues are covered in the detailed guides
2. **Review the health dashboard** - Check `/health` for service status
3. **Check logs** - Review browser console and server logs
4. **Search existing issues** - Check if the issue has been reported before
5. **Create a new issue** - Include detailed information about your problem

---

## Contributing

We welcome contributions to the DTT Framework! Here's how you can help:

### How to Contribute

1. **Fork the repository**
   ```bash
   # Fork the repository on GitHub
   git clone https://github.com/yourusername/dtt-framework.git
   cd dtt-framework
   ```

2. **Create a branch**
   ```bash
   git checkout -b feature/your-feature-name
   ```

3. **Make your changes**
   - Follow the existing code style
   - Add tests for new features
   - Update documentation as needed

4. **Run checks**
   ```bash
   pnpm check
   pnpm format:write
   pnpm typecheck
   ```

5. **Commit your changes**
   ```bash
   git add .
   git commit -m "feat: add your feature description"
   ```

6. **Push to your fork**
   ```bash
   git push origin feature/your-feature-name
   ```

7. **Create a Pull Request**
   - Describe your changes
   - Reference any related issues
   - Include screenshots if applicable

### Commit Message Convention

Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:

- `feat:` - A new feature
- `fix:` - A bug fix
- `docs:` - Documentation changes
- `style:` - Code style changes (formatting, etc.)
- `refactor:` - Code refactoring
- `test:` - Adding or updating tests
- `chore:` - Maintenance tasks

Example:
```bash
git commit -m "feat: add health check dashboard"
git commit -m "fix: resolve database connection timeout"
git commit -m "docs: update README with deployment guide"
```

### Code of Conduct

- Be respectful and inclusive
- Provide constructive feedback
- Focus on what is best for the community
- Show empathy towards other community members

### Reporting Issues

When reporting issues, please include:

- A clear description of the problem
- Steps to reproduce the issue
- Expected behavior
- Actual behavior
- Environment details (OS, Node.js version, etc.)
- Relevant logs or error messages

---

## License

The DTT Framework is licensed under the MIT License.

```
MIT License

Copyright (c) 2025 DTT Framework Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

---

## Support

### Getting Help

If you need help with the DTT Framework:

1. **Documentation** - Start with the [comprehensive documentation](#documentation)
2. **GitHub Issues** - Search existing issues or create a new one
3. **Health Dashboard** - Check the `/health` endpoint for service status
4. **Community** - Join our community discussions

### Contact Information

- **GitHub**: [https://github.com/yourusername/dtt-framework](https://github.com/yourusername/dtt-framework)
- **Issues**: [https://github.com/yourusername/dtt-framework/issues](https://github.com/yourusername/dtt-framework/issues)
- **Discussions**: [https://github.com/yourusername/dtt-framework/discussions](https://github.com/yourusername/dtt-framework/discussions)

### Resources

- [Next.js Documentation](https://nextjs.org/docs)
- [Clerk Documentation](https://clerk.com/docs)
- [Supabase Documentation](https://supabase.com/docs)
- [Drizzle Documentation](https://orm.drizzle.team/docs/overview)
- [Hono Documentation](https://hono.dev/docs)
- [TanStack Query Documentation](https://tanstack.com/query/latest)
- [Zustand Documentation](https://zustand-demo.pmnd.rs/)

---

## Acknowledgments

The DTT Framework is built on top of amazing open-source projects:

- [Next.js](https://nextjs.org/) - The React framework
- [Clerk](https://clerk.com/) - Authentication solution
- [Supabase](https://supabase.com/) - Backend-as-a-service
- [Drizzle](https://orm.drizzle.team/) - Type-safe ORM
- [Hono](https://hono.dev/) - Lightweight web framework
- [TanStack Query](https://tanstack.com/query) - Data fetching library
- [Zustand](https://zustand-demo.pmnd.rs/) - State management
- [Shadcn/ui](https://ui.shadcn.com/) - UI components
- [Tailwind CSS](https://tailwindcss.com/) - CSS framework

---

**Built with ❤️ for the developer community**