An open API service indexing awesome lists of open source software.

https://github.com/kryptobaseddev/tanstack-forge-starter

Modern full-stack starter kit built with TanStack suite (Router, Query, Form, Table), tRPC, Prisma, MongoDB, and Shadcn UI. Features type-safe APIs, file-based routing, and development mode authentication.
https://github.com/kryptobaseddev/tanstack-forge-starter

authentication clerk full-stack mongodb prisma react shadcn starter tailwindcss tanstack trpc typescript vite

Last synced: about 1 month ago
JSON representation

Modern full-stack starter kit built with TanStack suite (Router, Query, Form, Table), tRPC, Prisma, MongoDB, and Shadcn UI. Features type-safe APIs, file-based routing, and development mode authentication.

Awesome Lists containing this project

README

          

# TanStackForge

A modern, full-stack starter kit built on the TanStack suite, combining type-safe technologies for an exceptional developer experience.

Demo of app and UI here: **[TanStackForge Demo](https://tanstack-forge-starter.vercel.app/)**

## โœจ Features

- ๐Ÿšฆ **[TanStack Router](https://tanstack.com/router)** - Type-safe file-based routing with loaders and actions
- ๐Ÿ”„ **[TanStack Query](https://tanstack.com/query)** - Data fetching and caching
- ๐Ÿ“ **[TanStack Form](https://tanstack.com/form)** - Powerful form management
- ๐Ÿ“Š **[TanStack Table](https://tanstack.com/table)** - Headless UI for building data tables
- ๐Ÿ”’ **[Clerk](https://clerk.com/docs)** - Modern authentication with development mode support
- ๐Ÿ”Œ **[tRPC](https://trpc.io/docs)** - End-to-end type-safe APIs
- ๐Ÿ’พ **[Prisma ORM](https://www.prisma.io/docs/orm)** with **MongoDB** - Type-safe database access
- ๐ŸŽจ **[Shadcn UI](https://ui.shadcn.com/docs)** with **[Tailwind CSS](https://tailwindcss.com/)** - Beautiful UI components
- โšก **[Vite](https://v5.vite.dev/guide)** - Lightning fast development

## ๐Ÿš€ Getting Started

### Prerequisites

- [Node.js](https://nodejs.org/) (v18 or higher)
- [pnpm](https://pnpm.io/) (recommended) or npm/yarn
- MongoDB instance (see [Database Setup](#database-setup))
- Clerk account (see [Authentication Setup](#authentication-setup))

### Installation

1. Clone the repository:

```bash
git clone https://github.com/yourusername/tanstack-forge.git
cd tanstack-forge
```

2. Install dependencies:

```bash
pnpm install
```

3. Set up environment variables by creating a `.env` file in the root directory:

```env
# Database
DATABASE_URL="mongodb://mongo:@metro.proxy.rlwy.net:53250"

# Clerk Authentication
VITE_CLERK_PUBLISHABLE_KEY=pk_test_********************
CLERK_SECRET_KEY=sk_test_********************

# Development Mode true bypasses Clerk authentication check and uses devAuth
VITE_DEV_MODE=true
```

4. Push the database schema to your MongoDB instance:

```bash
pnpm prisma db push
```

5. Start the development server:

```bash
pnpm dev
```

6. Open [http://localhost:5173](http://localhost:5173) in your browser.

## ๐Ÿ”ง Project Structure

```
tanstack-forge/
โ”œโ”€โ”€ prisma/ # Database schema and migrations
โ”‚ โ””โ”€โ”€ schema.prisma # Prisma schema definition
โ”œโ”€โ”€ public/ # Static assets
โ”œโ”€โ”€ src/
โ”‚ โ”œโ”€โ”€ api/ # External API routes
โ”‚ โ”œโ”€โ”€ components/ # UI components
โ”‚ โ”‚ โ”œโ”€โ”€ auth/ # Authentication components
โ”‚ โ”‚ โ”œโ”€โ”€ common/ # Shared components
โ”‚ โ”‚ โ”œโ”€โ”€ features/ # Feature-specific components
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ posts/ # Post feature components
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ users/ # User feature components
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ... # Other feature components
โ”‚ โ”‚ โ”œโ”€โ”€ layouts/ # Layout components
โ”‚ โ”‚ โ””โ”€โ”€ ui/ # Shadcn UI components
โ”‚ โ”œโ”€โ”€ hooks/ # Custom React hooks
โ”‚ โ”œโ”€โ”€ lib/ # Utility functions and constants
โ”‚ โ”‚ โ”œโ”€โ”€ constants.ts # Application constants
โ”‚ โ”‚ โ”œโ”€โ”€ prisma.ts # Prisma client
โ”‚ โ”‚ โ”œโ”€โ”€ trpc.ts # tRPC setup
โ”‚ โ”‚ โ””โ”€โ”€ utils.ts # Utility functions
โ”‚ โ”œโ”€โ”€ pages/ # Page components
โ”‚ โ”‚ โ”œโ”€โ”€ about.tsx # About page route
โ”‚ โ”‚ โ”œโ”€โ”€ examples.tsx # Examples page route
โ”‚ โ”‚ โ””โ”€โ”€ features.tsx # Features page route
โ”‚ โ”œโ”€โ”€ providers/ # React context providers
โ”‚ โ”‚ โ”œโ”€โ”€ auth-provider.tsx # Authentication provider
โ”‚ โ”‚ โ””โ”€โ”€ trpc-provider.tsx # tRPC provider
โ”‚ โ”œโ”€โ”€ routes/ # File-based routing
โ”‚ โ”‚ โ”œโ”€โ”€ __root.tsx # Root layout and providers
โ”‚ โ”‚ โ”œโ”€โ”€ index.tsx # Home page route (used for the features page in this starter)
โ”‚ โ”‚ โ”œโ”€โ”€ about.tsx # About page route
โ”‚ โ”‚ โ””โ”€โ”€ examples.tsx # Examples page route
โ”‚ โ”œโ”€โ”€ server/ # Backend logic
โ”‚ โ”‚ โ”œโ”€โ”€ context.ts # tRPC context
โ”‚ โ”‚ โ”œโ”€โ”€ router.ts # Base router setup
โ”‚ โ”‚ โ””โ”€โ”€ routers/ # Route handlers
โ”‚ โ”‚ โ”œโ”€โ”€ _app.ts # Root router
โ”‚ โ”‚ โ”œโ”€โ”€ post.router.ts
โ”‚ โ”‚ โ””โ”€โ”€ user.router.ts
โ”‚ โ”œโ”€โ”€ types/ # TypeScript type definitions
โ”‚ โ”‚ โ”œโ”€โ”€ api.types.ts # API types
โ”‚ โ”‚ โ”œโ”€โ”€ auth.types.ts # Authentication types
โ”‚ โ”‚ โ”œโ”€โ”€ common.types.ts # Common types
โ”‚ โ”‚ โ”œโ”€โ”€ form.types.ts # Form types
โ”‚ โ”‚ โ”œโ”€โ”€ post.types.ts # Post types
โ”‚ โ”‚ โ”œโ”€โ”€ router.types.ts # Router types
โ”‚ โ”‚ โ”œโ”€โ”€ table.types.ts # Table types
โ”‚ โ”‚ โ””โ”€โ”€ user.types.ts # User types
โ”‚ โ”œโ”€โ”€ index.css # Global CSS and Tailwind imports
โ”‚ โ”œโ”€โ”€ routeTree.gen.ts # Route tree generator (generated from TanStack Router)
โ”‚ โ””โ”€โ”€ main.tsx # Application entry point
โ”œโ”€โ”€ .env # Environment variables
โ”œโ”€โ”€ .env.example # Example environment variables
โ”œโ”€โ”€ .gitignore # Git ignore rules
โ”œโ”€โ”€ index.html # HTML template
โ”œโ”€โ”€ package.json # Project dependencies
โ”œโ”€โ”€ tailwind.config.js # Tailwind configuration
โ”œโ”€โ”€ tsconfig.json # TypeScript configuration
โ””โ”€โ”€ vite.config.ts # Vite configuration
```

## ๐ŸŽจ Color Scheme and Styling

TanStackForge uses a sophisticated color system defined in `src/index.css`:

```css
:root {
/* Main brand colors */
--color-primary: 263.4 70% 50.4%; /* Purple */
--color-secondary: 215 27.9% 16.9%; /* Dark blue-gray */
--color-accent: 215 27.9% 16.9%; /* Accent color */

/* Semantic colors */
--color-success: 142 72% 29%; /* Green */
--color-warning: 38 92% 50%; /* Yellow/Amber */
--color-error: 0 62.8% 30.6%; /* Red */
--color-info: 199 89% 48%; /* Blue */

/* Base colors - Dark theme by default */
--background: 224 71.4% 4.1%;
--foreground: 210 20% 98%;

/* Component colors */
--card: 224 71.4% 4.1%;
--card-foreground: 210 20% 98%;
--popover: 224 71.4% 4.1%;
--popover-foreground: 210 20% 98%;
/* ... and more component-specific colors */
}
```

### Theme Features:

- **HSL Color Format**: All colors are defined in HSL format for easy manipulation
- **CSS Variables**: Enables dynamic theme switching and component-specific styling
- **Semantic Colors**: Clear naming conventions for different UI states
- **Dark Mode Ready**: Built-in dark mode support
- **Component-Specific Colors**: Dedicated variables for different UI components

## ๐Ÿ›ฃ๏ธ Routing with TanStack Router

TanStackForge uses TanStack Router's file-based routing system:

```
src/routes/
โ”œโ”€โ”€ __root.tsx # Root layout and providers
โ”œโ”€โ”€ index.tsx # Home page (/)
โ”œโ”€โ”€ about.tsx # About page (/about)
โ””โ”€โ”€ examples/
โ””โ”€โ”€ index.tsx # Examples page (/examples)
```

### Route Configuration

Routes are automatically generated from the file structure:

```typescript
// src/routes/__root.tsx
export const Route = createRootRoute({
component: () => (





),
});

// src/routes/index.tsx
export const Route = createFileRoute('/')({
component: HomePage,
});
```

## ๐Ÿ” Authentication

TanStackForge supports two authentication modes:

### Development Mode

When `VITE_DEV_MODE=true`:
- Uses a simplified authentication flow
- No external auth service required
- Perfect for development and testing

### Production Mode

When `VITE_DEV_MODE=false`:
- Uses Clerk for secure authentication
- Supports email/password and social logins
- Full user management features

When enabled, development mode:

- Shows debugging information and devtools
- Enables more detailed error messages
- Makes tRPC panel accessible
- Displays TanStack Query and Router devtools
- Bypasses certain authentication checks for faster development

Set to `false` for production-like behavior during development.

## ๐Ÿ—„๏ธ API Structure

The backend API is organized using tRPC routers:

```
src/server/
โ”œโ”€โ”€ context.ts # Request context
โ”œโ”€โ”€ router.ts # Base router setup
โ””โ”€โ”€ routers/
โ”œโ”€โ”€ _app.ts # Root router
โ”œโ”€โ”€ post.router.ts # Post-related endpoints
โ””โ”€โ”€ user.router.ts # User-related endpoints
```

### Example Router:

```typescript
// src/server/routers/user.router.ts
export const userRouter = router({
list: publicProcedure
.query(({ ctx }) => ctx.prisma.user.findMany()),

byId: protectedProcedure
.input(z.string())
.query(({ ctx, input }) => ctx.prisma.user.findUnique({
where: { id: input }
})),
});
```

## ๐Ÿ”Œ tRPC Integration

TanStackForge provides a seamless integration between tRPC, TanStack Router, and TanStack Query for end-to-end type safety.

### Base Setup
```typescript
// src/server/router.ts
const t = initTRPC.context().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.auth?.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: { auth: ctx.auth },
});
});
```

### Router Implementation
```typescript
// src/server/routers/user.router.ts
export const userRouter = router({
me: protectedProcedure
.query(({ ctx }) => ctx.prisma.user.findUnique({
where: { clerkId: ctx.auth.userId },
})),

updateProfile: protectedProcedure
.input(z.object({
name: z.string().min(2).max(50).optional(),
role: z.nativeEnum(UserRole).optional(),
}))
.mutation(({ ctx, input }) => ctx.prisma.user.update({
where: { clerkId: ctx.auth.userId },
data: input,
})),
});
```

### TanStack Router Integration
```typescript
// src/routes/user.tsx
export const Route = createFileRoute('/user')({
loader: () => trpc.user.me.ensureData(),
component: UserProfile,
});
```

### TanStack Query Usage
```typescript
// In your React components
function UserProfile() {
// Automatic type inference from your tRPC router
const { data: user } = api.user.me.useQuery();
const utils = api.useUtils();

const { mutate: updateProfile } = api.user.updateProfile.useMutation({
onSuccess: () => {
// Invalidate and refetch
utils.user.me.invalidate();
},
});

return (/* ... */);
}
```

## ๐Ÿ“ Type System

TanStackForge emphasizes type safety across the entire stack:

### Constants and Enums

Store application constants and enums in `src/lib/constants.ts`:

```typescript
// src/lib/constants.ts
export const APP_NAME = "TanStackForge";

export enum UserRole {
ADMIN = "ADMIN",
USER = "USER",
}

export enum UserStatus {
ACTIVE = "ACTIVE",
INACTIVE = "INACTIVE",
}

// Feature flags
export const FEATURES = {
DARK_MODE: true,
ANALYTICS: false,
};
```

### Type Definitions

Store shared type definitions in the `src/types` folder:

```typescript
// src/types/common.ts
export type Status = 'idle' | 'loading' | 'success' | 'error';

export interface PaginationParams {
page: number;
limit: number;
}

export interface ApiResponse {
data: T;
status: Status;
error?: string;
}
```

### End-to-End Type Safety

TanStackForge provides end-to-end type safety through:

1. **Prisma Schema to TypeScript**:
```prisma
// prisma/schema.prisma
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
clerkId String @unique
name String?
email String @unique
role String @default("USER")
status String @default("ACTIVE")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```

2. **tRPC with Zod Validation**:
```typescript
// src/server/routers/user.router.ts
const userUpdateSchema = z.object({
name: z.string().min(2).max(50).optional(),
role: z.nativeEnum(UserRole).optional(),
});

export const userRouter = router({
updateProfile: protectedProcedure
.input(userUpdateSchema)
.mutation(async ({ ctx, input }) => {
return ctx.prisma.user.update({
where: { clerkId: ctx.auth.userId },
data: input,
});
}),
});
```

## ๐Ÿ”„ Data Flow

TanStackForge implements a clean and type-safe data flow:

1. **Database Layer** (Prisma with MongoDB)
- Models defined in `prisma/schema.prisma`
- Type-safe database queries via Prisma Client

2. **API Layer** (tRPC)
- Route handlers in `src/server/routers/`
- Input validation with Zod
- Business logic processing
- Type-safe responses

3. **Client Layer** (TanStack Query + tRPC)
- Auto-generated hooks from tRPC procedures
- Automatic cache management
- Optimistic updates
- Type-safe mutations

4. **UI Layer** (React + Shadcn UI)
- Type-safe props and state
- Strongly typed event handlers
- Component composition with TypeScript

## ๐Ÿงช Testing

TanStackForge includes a comprehensive testing setup:

### Unit Tests
```typescript
// src/__tests__/utils.test.ts
import { describe, it, expect } from 'vitest';
import { formatDate } from '@/lib/utils';

describe('utils', () => {
it('formats date correctly', () => {
const date = new Date('2024-01-01');
expect(formatDate(date)).toBe('Jan 1, 2024');
});
});
```

### Component Tests
```typescript
// src/__tests__/components/Button.test.tsx
import { render, screen } from '@testing-library/react';
import { Button } from '@/components/ui/button';

describe('Button', () => {
it('renders correctly', () => {
render(Click me);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
});
```

### API Tests
```typescript
// src/__tests__/api/user.test.ts
import { createInnerTRPCContext } from '@/server/context';
import { appRouter } from '@/server/routers/_app';

describe('User API', () => {
it('returns user profile', async () => {
const ctx = createInnerTRPCContext({ auth: mockAuth });
const caller = appRouter.createCaller(ctx);
const result = await caller.user.me();
expect(result).toHaveProperty('id');
});
});
```

Run tests with:
```bash
pnpm test # Run all tests
pnpm test:watch # Run tests in watch mode
pnpm test:ui # Run tests with UI
pnpm test:coverage # Run tests with coverage report
```

## ๐Ÿ“š Learn More

- [TanStack Router Documentation](https://tanstack.com/router/latest/docs/framework/react/overview)
- [TanStack Query Documentation](https://tanstack.com/query/latest/docs/react/overview)
- [tRPC Documentation](https://trpc.io/docs)
- [Prisma Documentation](https://www.prisma.io/docs)
- [Clerk Documentation](https://clerk.com/docs)
- [Shadcn UI Documentation](https://ui.shadcn.com/docs)

## ๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.