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.
- Host: GitHub
- URL: https://github.com/kryptobaseddev/tanstack-forge-starter
- Owner: kryptobaseddev
- Created: 2025-03-17T19:13:26.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-18T19:45:39.000Z (about 1 year ago)
- Last Synced: 2026-01-03T16:31:32.430Z (4 months ago)
- Topics: authentication, clerk, full-stack, mongodb, prisma, react, shadcn, starter, tailwindcss, tanstack, trpc, typescript, vite
- Language: TypeScript
- Homepage: https://tanstack-forge-starter.vercel.app/
- Size: 1.09 MB
- Stars: 6
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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.