Skip to content

codeSTACKr/tanstack-start-mongodb

Repository files navigation

MongoDB + TanStack Start Demo

A full-stack demonstration of MongoDB integration with TanStack Start, featuring end-to-end type safety, serverless-optimized connection pooling, and modern React patterns.

TanStack Start + MongoDB MongoDB TypeScript

Home Page Screenshot πŸ”— Live Demo

✨ Features

  • πŸ”’ End-to-end type safety from MongoDB β†’ Server functions β†’ React components
  • πŸš€ Serverless-optimized connection pooling (prevents connection exhaustion)
  • ⚑ Optimistic updates with TanStack Query for instant UI feedback
  • 🎯 Smart caching with stale-while-revalidate strategies
  • 🎨 Modern UI with Shadcn components, Tailwind CSS 4, and dark/light/system themes
  • πŸ“¦ No ORM - native MongoDB driver for full control and flexibility
  • πŸ”„ Full CRUD operations with a complete todo app example

πŸ› οΈ Tech Stack

πŸš€ Quick Start

Prerequisites

  • Node.js 22+ and pnpm installed
  • MongoDB instance (local or MongoDB Atlas)

Installation

  1. Clone and install:

    git clone <your-repo-url>
    cd tanstack-start-mongodb
    pnpm install
  2. Configure MongoDB:

    cp .env.example .env

    Edit .env and set your MongoDB connection string:

    # For local MongoDB
    MONGODB_URI=mongodb://localhost:27017/tanstack-todos
    
    # Or for MongoDB Atlas
    MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/tanstack-todos
  3. Start development server:

    pnpm dev

    Open http://localhost:3000

πŸ“ Project Structure

src/
β”œβ”€β”€ config/
β”‚   └── mongodb.ts           # Centralized MongoDB configuration
β”œβ”€β”€ server/
β”‚   β”œβ”€β”€ todos.ts             # Server functions (CRUD operations)
β”‚   β”œβ”€β”€ mongodb-status.ts    # Connection status check
β”‚   └── theme.ts             # SSR theme detection
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ mongodb.ts           # Serverless-optimized connection singleton
β”‚   β”œβ”€β”€ types.ts             # Type definitions + Zod schemas
β”‚   └── utils.ts             # Utility functions
β”œβ”€β”€ queries/
β”‚   └── todos.ts             # TanStack Query factories
β”œβ”€β”€ hooks/
β”‚   └── useTodos.ts          # Custom hooks with optimistic updates
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ __root.tsx           # Root layout with devtools
β”‚   β”œβ”€β”€ index.tsx            # Landing page
β”‚   └── todos.tsx            # Todo demo page
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ TodoList.tsx         # Main todo container
β”‚   β”œβ”€β”€ TodoItem.tsx         # Individual todo with actions
β”‚   β”œβ”€β”€ AddTodoForm.tsx      # Input form
β”‚   └── ui/                  # Shadcn UI components
└── integrations/
    └── tanstack-query/      # Query client setup

πŸ“œ Available Scripts

# Development
pnpm dev              # Start development server (port 3000)
pnpm build            # Build for production
pnpm serve            # Preview production build

# Code Quality
pnpm lint             # Lint code with ESLint
pnpm format           # Format code with Prettier
pnpm check            # Format and fix all issues

# Database
pnpm init-db          # Initialize MongoDB indexes

# UI Components
pnpx shadcn@latest add <component>    # Add Shadcn components

🌐 Deployment

This application uses a multi-branch deployment strategy with platform-specific configurations:

Branch Structure

Branch Purpose Platform
main Base implementation Generic serverless
netlify Netlify deployment Netlify
cloudflare Basic Cloudflare deployment Cloudflare Workers
cloudflare-durable-objects Advanced Cloudflare deployment Cloudflare Workers + Durable Objects

Deploying to Netlify

  1. Switch to netlify branch:

    git checkout netlify
  2. Install dependencies:

    pnpm install
  3. Deploy to Netlify:

    pnpm netlify deploy --build
  4. Set environment variables in Netlify:

    • MONGODB_URI - Your MongoDB connection string

Features:

  • Uses @netlify/vite-plugin-tanstack-start
  • Node.js 22+ runtime
  • Official TanStack Start partner

Deploying to Cloudflare Workers

Basic Deployment (cloudflare branch)

  1. Switch to cloudflare branch:

    git checkout cloudflare
  2. Install dependencies:

    pnpm install
  3. Deploy to Cloudflare:

    pnpm build
    pnpm wrangler deploy
  4. Set environment variables:

    pnpm wrangler secret put MONGODB_URI

Features:

  • Uses @cloudflare/vite-plugin
  • Node.js compatibility v2
  • Official TanStack Start partner

Advanced Deployment (cloudflare-durable-objects branch)

  1. Switch to cloudflare-durable-objects branch:

    git checkout cloudflare-durable-objects
  2. Install dependencies:

    pnpm install
  3. Deploy with Durable Objects:

    pnpm build
    pnpm wrangler deploy
  4. Set environment variables:

    pnpm wrangler secret put MONGODB_URI

Features:

  • MongoDB connection managed via Durable Objects
  • Better state persistence across Workers instances
  • Custom server entry point
  • Ideal for production Cloudflare deployments

Other Platforms

The main branch supports deployment to:

  • Vercel - Standard serverless deployment
  • AWS Lambda - Standard serverless deployment
  • Node.js hosting - Railway, Render, Fly.io, etc.
  • Any platform with Node.js 22+ and MongoDB access

Set the MONGODB_URI environment variable in your platform's settings.

πŸ—οΈ Architecture Highlights

Serverless-Optimized MongoDB Connection

The application implements connection pooling best practices for serverless:

  • Singleton pattern with global caching across function invocations
  • Connection reuse to prevent connection exhaustion
  • Promise caching for concurrent connection requests
  • Optimized pool settings: maxPoolSize: 10, idle timeout: 5s
  • User-friendly error handling for common MongoDB issues

See src/lib/mongodb.ts and src/config/mongodb.ts for implementation.

Type-Safe Server Functions

Uses TanStack Start's createServerFn for type-safe server operations:

// Automatic type inference from server to client
export const getTodos = createServerFn().handler(async () => {
  const collection = await getTodosCollection()
  return await collection.find({}).sort({ createdAt: -1 }).toArray()
})
  • Full TypeScript type safety
  • Zod validation with .inputValidator()
  • No HTTP overhead for internal calls
  • Seamless client-server communication

Optimistic Updates with TanStack Query

All mutations implement optimistic updates for instant UI feedback:

// Update UI immediately, rollback on error
const { mutate } = useUpdateTodo()
mutate({ id: todo.id, completed: !todo.completed })
  • Instant UI updates before server confirmation
  • Automatic rollback on errors
  • Cache synchronization with onSettled
  • Retry logic with exponential backoff

Theme System

SSR-compatible theme support with zero flash:

  • Dark, light, and system theme modes
  • Theme stored in cookies for SSR consistency
  • Blocking script prevents theme flash on page load
  • Smooth transitions between themes

πŸ“š Learn More

πŸ“ Contributing

See CLAUDE.md for detailed architecture documentation and development patterns.

πŸ“„ License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors