Taylor McNeil

docs-as-portfolio v1.4

GET/tutorials/mongodb-tanstack

MongoDB x TanStack

See Live Doc

A full-stack integration guide for MongoDB's official documentation.

About This Tutorial

Context

MongoDB was expanding their docs to cover frameworks with active, growing communities. TanStack Start made the list.


I picked up the assignment, researched the framework, and built a sample application that connects TanStack Start to an Atlas cluster. Then I documented the whole process. It went through MongoDB's review process and shipped as part of their official driver documentation.


What follows is an excerpt showing the structure and approach. The full tutorial covers project setup, backend configuration, frontend components, and running the application.

Overview

This guide demonstrates how to build a modern web application with TanStack Start and MongoDB. TanStack Start is a full-stack framework that integrates frontend and backend development by using React and popular libraries like TanStack Router and TanStack Query from the TanStack ecosystem.

The application in this tutorial consists of the following layers:

  • Database Layer: MongoDB stores and retrieves data.
  • Server Layer: TanStack Start provides the API endpoints and logic to connect your frontend to your MongoDB database.
  • Data Management Layer: TanStack Query manages server-side state on the frontend, unifying the logic for data fetching, loading states, and error handling.
  • Presentation Layer: React implements the UI by using the TanStack Query data.

Why MongoDB + TanStack Start?

MongoDB's document model stores data as JSON-like documents, making it easy to work with JavaScript objects without complex mapping. This aligns with TanStack Start's React components and TypeScript interfaces.

TanStack Query handles the data layer efficiently by caching MongoDB responses, managing loading states, and synchronizing data across components. This eliminates manual state management and reduces redundant database calls.

This combination works well for applications that need the following features:

  • Flexible data structures that can evolve over time
  • Real-time data updates with minimal client-side code
  • Type safety from database to UI
  • Efficient caching and background data synchronization

Quick Start Tutorial

This tutorial guides you through building a TanStack Start application that integrates with MongoDB. The application accesses sample restaurant data and displays the results on a locally hosted site. It includes instructions on connecting your MongoDB cluster hosted on MongoDB Atlas and accessing and displaying information from your database.

Tip

If you prefer to connect to MongoDB using the Node.js driver without TanStack Start, see the Get Started with the Node.js Driver guide.

Set Up Your Project

Follow the steps in this section to install project dependencies, create an Atlas cluster, and set up the application directories.

  1. 1
    Verify the prerequisites

    To create the Quick Start application, ensure you have the following software installed:

    PrerequisiteRequirement
    Node.jsVersion 20 or later
    Code EditorVisual Studio Code (or editor of your choice)
    TerminalMacOS: Terminal or similar app. Windows: PowerShell
  2. 2
    Create a MongoDB Atlas cluster

    MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, create a free cluster (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample databases into your cluster, including the sample_restaurants database that is used in this tutorial.

    To connect to your cluster, you must use a connection URI. To retrieve your connection URI, follow the instructions in the Connect to Your Cluster tutorial in the Atlas documentation.

    Tip

    Save your connection URI in a secure location.

  3. 3
    Create the project skeleton

    Use the official TanStack Start CLI to initialize the project skeleton. Open your terminal and navigate to your desired project directory.

    Run the initialization command:

    bash
    npm create @tanstack/start@latest

    The installation wizard guides you through the setup. Select the following options:

    PromptInputAction
    What would you like to name your project?Your desired project nameType the name, press Enter
    Would you like to use Tailwind CSS?YesType Y, press Enter
    Select a toolchainDefault (None)Select None, press Enter
    Select your deployment adapterDefault: (Nitro)Press Enter
    What add-ons would you like for your project?NonePress Enter
    Would you like any examples?NonePress Enter

    After installation completes, navigate into your project directory.

  4. 4
    Configure Vite for MongoDB compatibility

    TanStack Start uses Vite as the build tool. By default, Vite attempts to bundle dependencies for the browser. However, the Node.js Driver relies on mongodb-client-encryption, a server-side native module that causes errors when Vite bundles it for browser environments.

    To prevent this, configure Vite to exclude the mongodb-client-encryption module from optimization and server-side rendering.

    Navigate to vite.config.ts in your project root and replace the contents with the following code:

    typescript
    import { defineConfig } from 'vite'
    import { devtools } from '@tanstack/devtools-vite'
    import { tanstackStart } from '@tanstack/react-start/plugin/vite'
    import viteReact from '@vitejs/plugin-react'
    import viteTsConfigPaths from 'vite-tsconfig-paths'
    import tailwindcss from '@tailwindcss/vite'
    import { nitro } from 'nitro/vite'
    
    const config = defineConfig({
      plugins: [
        devtools(),
        nitro(),
        viteTsConfigPaths({
          projects: ['./tsconfig.json'],
        }),
        tailwindcss(),
        tanstackStart(),
        viteReact(),
      ],
      optimizeDeps: {
        exclude: ['mongodb-client-encryption'],
      },
      ssr: {
        external: ['mongodb-client-encryption'],
      },
    })
    
    export default config
  5. 5
    Install MongoDB & TanStack Query

    Install the Node.js Driver to allow the server code to connect to the database and install TanStack Query to manage data fetching on the frontend.

    Run the following command in your project root:

    bash
    npm install mongodb @tanstack/react-query
Note
Excerpt Ends Here

This covers the introduction, architecture overview, and tutorial setup. The full tutorial continues with Vite configuration, database connections, server functions, React components, and running the application.

Read the full tutorial on MongoDB Docs

Retrospective

Writing for official documentation means working within existing style guides and content architecture. Here's how I would approach this differently with full control over the content strategy.

1. Self-Contained Content

The tutorial links out to separate pages for common setup steps, such as "See the Connect to Your Cluster tutorial" and "follow the instructions in the Get Connection String guide." Each click takes the reader away from their task and increases cognitive load.

I prefer docs that keep readers in flow. The trade-off is repeated material across tutorials, but that's a content architecture problem rather than a writing problem.

Loading diagram...

2. Componentization

The fix for self-contained content without maintenance burden is simple: shared components.

Instead of manually copying the "get your connection string" instructions into every tutorial, create an expandable <ConnectionString /> component that lives in one place. Update it once, it updates everywhere. Readers get inline content, and writers maintain a single source of truth.

Loading diagram...

3. Clearer Product Positioning

TanStack Start is a nascent framework. We cannot assume developers are familiar with it or the wider TanStack ecosystem. The current introduction jumps straight into technical implementation without establishing the necessary context.

I would add a dedicated "What is TanStack Start?" section at the top. Position the framework against known standards like Next.js or Remix so users understand the architecture immediately. Readers need to understand the mental model—specifically the "Server Function" RPC pattern—before they worry about connecting a database.

4. Shortening the Feedback Loop

The current guide requires the user to write the entire application (Database, Server, UI, and Routing) before running npm run dev a single time. This prevents the user from validating their progress and makes debugging difficult if they made a typo in step 2.

I would restructure the guide to prioritize an immediate "Hello World." Get the server running first, then layer in the database connection, and finally add the UI components. This iterative approach keeps the user engaged and makes troubleshooting significantly easier.

5. Visualizing the Architecture

For developers new to server functions, the boundary between client and server can be invisible. The code looks like a standard function import, but it actually triggers a network request.

I would add an architecture diagram that visualizes this RPC (Remote Procedure Call) layer:

Loading diagram...

This helps the reader build a mental model of where their code is actually executing, which is often the biggest hurdle when learning a full-stack framework.