Hello! Welcome to your first lesson on mastering TanStack Start.
Given your extensive background in front-end development, we'll move quickly through the basics and focus on the architectural concepts and specific conventions that make TanStack Start a modern, powerful framework for building server-rendered applications.
Lesson 1: Project Initialization and Environment Configuration
Today's Goal:
By the end of this 60-minute lesson, you will be able to initialize a new TanStack Start project and correctly configure environment variables for both server and client contexts. This is the foundational step for everything we'll build in this course, from server-side data fetching to secure authentication.
What we will cover:
- Project Scaffolding: Using the official CLI to create a new TanStack Start application.
- Core Project Structure: Understanding the key files and directories, including
vite.config.tsand thesrc/routesdirectory. - Environment Variable Management: Differentiating between secure server-side variables and public client-side variables, a critical concept in SSR.
Let's get started.
1. Initializing Your TanStack Start Project
While you could build a project from scratch by manually installing dependencies and creating configuration files, the recommended and most efficient method is to use the command-line interface (CLI). The CLI guides you through a series of questions to scaffold a project tailored to your needs.
To see this process in action, let's start with a short video walkthrough.
TanStack Start Full Course 2025 | Become a TanStack Start Pro in 1 Hour
This video from PedroTech provides a clear, up-to-date demonstration of initializing a TanStack Start project using the create-ts-router-app command. It will walk you through the setup prompts.
Watch the section from 00:59 to 05:38. Pay close attention to the questions asked by the CLI, particularly the choice between file-based and code-based routing.
Now, it's your turn to create the project we'll be using throughout this course.
Action: Create Your Project
- Open your terminal and navigate to the directory where you want to create your project.
- Run the following command:
Note: The video usesnpm create tanstack-start@latestcreate-ts-router-app, which is an older command. Thecreate-tanstack-startcommand is the current standard. - When prompted, make the following selections:
- Project Name: Enter
.to use your current directory, or provide a new name. - Which framework would you like to use? Select React.
- Which router would you like to use? Select File-based Router. This is the convention we'll follow.
- Would you like to use Tailwind CSS? Select Yes.
- Would you like to add linting? Select Yes.
- Would you like to add any addons? For now, press Enter without selecting any. We'll add features like TanStack Query manually later to better understand the integration.
- Would you like to add any examples? Select No.
- Project Name: Enter
Once the installation is complete, open the project in your code editor and run the development server:
npm run dev
You should now see your new TanStack Start application running on http://localhost:3000.
2. Understanding the Project Structure
The generated project has a structure that is both familiar and unique to the TanStack ecosystem. It's built on Vite, so you'll see a vite.config.ts file, but the routing and server-side capabilities are handled by TanStack-specific plugins and conventions.
The following video segment gives a good tour of the key files.
Getting Started with TanStack Start RC
This clip from Maximilian Schwarzmüller explores the generated project structure, pointing out the most important files you'll interact with.
Watch from 11:32 to 14:52. The presenter discusses vite.config.ts, router.tsx, the routes folder, and the auto-generated routeTree.gen.ts file.
Here is a summary of the most critical files and directories:
vite.config.ts: This is the heart of your application's build system. The key line istanstackStart(), which is the Vite plugin that enables all of TanStack Start's magic, including file-based routing, server functions, and SSR.src/routes/: This directory implements file-based routing. Each.tsxfile inside it becomes a route in your application. We will explore this in detail in a future lesson.src/router.tsx: This file configures the instance of TanStack Router. You can set global router behaviors here, such as scroll restoration.src/routeTree.gen.ts: Do not edit this file. It is automatically generated by the framework whenever you add, remove, or change files in thesrc/routes/directory. Its purpose is to create a typed representation of your entire route structure, which enables the powerful type-safe navigation features of TanStack Router.
3. Configuring Environment Variables
In an SSR application, managing environment variables is more nuanced than in a traditional SPA. Some variables, like API keys or database connection strings, must exist only on the server. Others, like a public app title or a feature flag, need to be accessible by the client-side code running in the browser.
TanStack Start, using Vite, has a clear and secure system for this. The official documentation provides the best overview.
Environment Variables | TanStack Start React Docs
This documentation page is the definitive guide to environment variables in TanStack Start. It clearly explains the different contexts and security rules.
Please read the 'Quick Start' and 'Environment Variable Contexts' sections. Focus on the distinction between process.env for the server and import.meta.env for the client, and the role of the VITE_ prefix.
The Two Golden Rules:
- Server-Only Variables: Any variable defined in your
.envfile (e.g.,DATABASE_URL) is accessible on the server viaprocess.env.DATABASE_URL. It will never be bundled or exposed to the client. - Client-Safe Variables: To expose a variable to the client, you must prefix it with
VITE_(e.g.,VITE_PUBLIC_API_URL). It will be accessible on the client viaimport.meta.env.VITE_PUBLIC_API_URL.
Practical Exercise
Let's apply this knowledge.
-
Create a
.envfile in the root of your project. -
Add the following variables to your new
.envfile:# Server-only secret API_SECRET_KEY="my-super-secret-key-that-stays-on-the-server" # Public variable for the client VITE_APP_NAME="My First TanStack Start App" -
Restart your development server. Vite only loads environment variables on startup.
-
Modify the home route. Open
src/routes/index.tsxand replace its contents with the following code. We are introducing aloaderfunction here, which is a server-side function that runs before the component renders. We will cover loaders in depth later.// src/routes/index.tsx import { createFileRoute } from '@tanstack/react-router'; export const Route = createFileRoute('/')({ // This 'loader' function runs ONLY on the server loader: () => { // Accessing the server-only variable const secret = process.env.API_SECRET_KEY; console.log('✅ Server-side API Secret:', secret); // We return data from the loader to the component return { serverHasSecret: !!secret }; }, component: HomeComponent, }); function HomeComponent() { // Use the data returned from the server-side loader const { serverHasSecret } = Route.useLoaderData(); // Accessing the client-safe variable const appName = import.meta.env.VITE_APP_NAME; // This will be undefined, as it's not prefixed with VITE_ const unavailableSecret = import.meta.env.API_SECRET_KEY; console.log('❌ Client-side API Secret:', unavailableSecret); return ( <div className="p-4"> <h1 className="text-2xl font-bold mb-4">{appName}</h1> <p> Server has access to secret key: <span className="font-mono bg-gray-200 p-1 rounded ml-2"> {String(serverHasSecret)} </span> </p> <p className="mt-2"> Client can access secret key: <span className="font-mono bg-gray-200 p-1 rounded ml-2"> {String(!!unavailableSecret)} </span> </p> <p className="text-sm text-gray-600 mt-4"> Check your browser and terminal consoles for logs. </p> </div> ); }
When you run this, check your terminal console (where you ran npm run dev). You will see the ✅ Server-side API Secret log with the key. Now, check your browser's developer console. You will see the ❌ Client-side API Secret log with undefined, proving the security boundary is working as intended.
Conclusion
Excellent work! In this lesson, you've successfully set up a TanStack Start project and mastered the fundamental, security-critical concept of managing environment variables in an SSR context.
Key Takeaways:
- You can scaffold a new project using
npm create tanstack-start@latest. - The project structure is centered around Vite, with
vite.config.tsand thetanstackStart()plugin being the core. - Type-safe routing is enabled by the auto-generated
routeTree.gen.tsfile. - Server-only environment variables are accessed via
process.envand are never exposed to the client. - Client-side variables must be prefixed with
VITE_and are accessed viaimport.meta.env.
Next Lesson Preview:
Now that we have a project running, our next step is to look under the hood. In the next lesson, "Configure the Vinxi bundler for Server-Side Rendering (SSR) and client hydration," we will explore how TanStack Start's underlying bundler, Vinxi, processes your code to create separate server and client bundles and how the initial server-rendered HTML is "hydrated" into a fully interactive application in the browser.
Can't find a good explanation? Sign up and we'll make it for you
Sign up