Open History to see the last commit
1---
2id: build-from-scratch
3title: Build a Project from Scratch
4---
5β
6> [!NOTE]
7> If you already created a project with the CLI or by cloning an example from the [Getting Started](./getting-started) guide, you can skip this guide and move on to the [Routing](./guide/routing) guide.
8β
9_So you want to build a TanStack Start project from scratch?_
10β
11This guide will help you build a **very** basic TanStack Start web application. Together, we will use TanStack Start to:
12β
13- Serve an index page
14- Display a counter
15- Increment the counter on the server and client
16β
17[Here is what that will look like](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-counter)
18β
19Let's create a new project directory and initialize it.
20β
21```shell
22mkdir myApp
23cd myApp
24npm init -y
25```
26β
27> [!NOTE]
28> We use `npm` in all of these examples, but you can use your package manager of choice instead.
29β
30## TypeScript Configuration
31β
32We highly recommend using TypeScript with TanStack Start. Create a `tsconfig.json` file with at least the following settings:
33β
34```json
35{
36 "compilerOptions": {
37 "jsx": "react-jsx",
38 "moduleResolution": "Bundler",
39 "module": "ESNext",
40 "target": "ES2022",
41 "skipLibCheck": true,
42 "strictNullChecks": true
43 }
44}
45```
46β
47> [!NOTE]
48> Enabling `verbatimModuleSyntax` can result in server bundles leaking into client bundles. It is recommended to keep this option disabled.
49β
50## Install Dependencies
51β
52TanStack Start is powered by [TanStack Router](https://tanstack.com/router) and supports [Vite](https://vite.dev/) or [Rsbuild](https://rsbuild.dev/) as the build tool.
53β
54To install Start and Router, run:
55β
56```shell
57npm i @tanstack/react-start @tanstack/react-router
58```
59β
60You'll also need React:
61β
62```shell
63npm i react react-dom
64```
65β
66Install the build tool and React integration you want to use:
67β
68<!-- ::start:tabs variant="bundler" -->
69β
70# Vite
71β
72```shell
73npm i -D vite @vitejs/plugin-react
74```
75β
76# Rsbuild
77β
78```shell
79npm i -D @rsbuild/core @rsbuild/plugin-react
80```
81β
82<!-- ::end:tabs -->
83β
84If you use Vite, you can also use `@vitejs/plugin-react-swc` instead of `@vitejs/plugin-react`.
85β
86and some TypeScript:
87β
88```shell
89npm i -D typescript @types/react @types/react-dom @types/node
90```
91β
92## Update Configuration Files
93β
94We'll then update our `package.json` to use your build tool's CLI and set `"type": "module"`:
95β
96<!-- ::start:tabs variant="bundler" -->
97β
98# Vite
99β
100```json
101{
102 // ...
103 "type": "module",
104 "scripts": {
105 "dev": "vite dev",
106 "build": "vite build"
107 }
108}
109```
110β
111# Rsbuild
112β
113```json
114{
115 // ...
116 "type": "module",
117 "scripts": {
118 "dev": "rsbuild dev",
119 "build": "rsbuild build"
120 }
121}
122```
123β
124<!-- ::end:tabs -->
125β
126Then configure TanStack Start's build tool plugin:
127β
128<!-- ::start:tabs variant="bundler" -->
129β
130# Vite
131β
132```ts title="vite.config.ts"
133import { defineConfig } from 'vite'
134import { tanstackStart } from '@tanstack/react-start/plugin/vite'
135import viteReact from '@vitejs/plugin-react'
136β
137export default defineConfig({
138 server: {
139 port: 3000,
140 },
141 resolve: {
142 tsconfigPaths: true,
143 },
144 plugins: [
145 tanstackStart(),
146 // react's vite plugin must come after start's vite plugin
147 viteReact(),
148 ],
149})
150```
151β
152# Rsbuild
153β
154```ts title="rsbuild.config.ts"
155import { defineConfig } from '@rsbuild/core'
156import { pluginReact } from '@rsbuild/plugin-react'
157import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
158β
159export default defineConfig({
160 server: {
161 port: 3000,
162 },
163 plugins: [pluginReact(), tanstackStart()],
164})
165```
166β
167<!-- ::end:tabs -->
168β
169## Add the Basic Templating
170β
171There are 2 required files for TanStack Start usage:
172β
1731. The router configuration
1742. The root of your application
175β
176Once configuration is done, we'll have a file tree that looks like the following:
177β
178```
179.
180βββ src/
181β βββ routes/
182β β βββ `__root.tsx`
183β βββ `router.tsx`
184β βββ `routeTree.gen.ts`
185βββ `vite.config.ts` or `rsbuild.config.ts`
186βββ `package.json`
187βββ `tsconfig.json`
188```
189β
190## The Router Configuration
191β
192This is the file that will dictate the behavior of TanStack Router used within Start. Here, you can configure everything
193from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading).
194β
195> [!NOTE]
196> You won't have a `routeTree.gen.ts` file yet. This file will be generated when you run TanStack Start for the first time.
197β
198```tsx
199// src/router.tsx
200import { createRouter } from '@tanstack/react-router'
201import { routeTree } from './routeTree.gen'
202β
203export function getRouter() {
204 const router = createRouter({
205 routeTree,
206 scrollRestoration: true,
207 })
208β
209 return router
210}
211```
212β
213## The Root of Your Application
214β
215Finally, we need to create the root of our application. This is the entry point for all other routes. The code in this file will wrap all other routes in the application.
216β
217```tsx
218// src/routes/__root.tsx
219import type { ReactNode } from 'react'
220import {
221 Outlet,
222 createRootRoute,
223 HeadContent,
224 Scripts,
225} from '@tanstack/react-router'
226β
227export const Route = createRootRoute({
228 head: () => ({
229 meta: [
230 {
231 charSet: 'utf-8',
232 },
233 {
234 name: 'viewport',
235 content: 'width=device-width, initial-scale=1',
236 },
237 {
238 title: 'TanStack Start Starter',
239 },
240 ],
241 }),
242 component: RootComponent,
243})
244β
245function RootComponent() {
246 return (
247 <RootDocument>
248 <Outlet />
249 </RootDocument>
250 )
251}
252β
253function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
254 return (
255 <html>
256 <head>
257 <HeadContent />
258 </head>
259 <body>
260 {children}
261 <Scripts />
262 </body>
263 </html>
264 )
265}
266```
267β
268## Writing Your First Route
269β
270Now that we have the basic templating setup, we can write our first route. This is done by creating a new file in the `src/routes` directory.
271β
272```tsx
273// src/routes/index.tsx
274import * as fs from 'node:fs'
275import { createFileRoute, useRouter } from '@tanstack/react-router'
276import { createServerFn } from '@tanstack/react-start'
277β
278const filePath = 'count.txt'
279β
280async function readCount() {
281 return parseInt(
282 await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
283 )
284}
285β
286const getCount = createServerFn({
287 method: 'GET',
288}).handler(() => {
289 return readCount()
290})
291β
292const updateCount = createServerFn({ method: 'POST' })
293 .validator((d: number) => d)
294 .handler(async ({ data }) => {
295 const count = await readCount()
296 await fs.promises.writeFile(filePath, `${count + data}`)
297 })
298β
299export const Route = createFileRoute('/')({
300 component: Home,
301 loader: async () => await getCount(),
302})
303β
304function Home() {
305 const router = useRouter()
306 const state = Route.useLoaderData()
307β
308 return (
309 <button
310 type="button"
311 onClick={() => {
312 updateCount({ data: 1 }).then(() => {
313 router.invalidate()
314 })
315 }}
316 >
317 Add 1 to {state}?
318 </button>
319 )
320}
321```
322β
323That's it! π€― You've now set up a TanStack Start project and written your first route. π
324β
325You can now run `npm run dev` to start your server and navigate to `http://localhost:3000` to see your route in action.
326β
327You want to deploy your application? Check out the [hosting guide](./guide/hosting.md).