Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

build-from-scratch.md

327 lines7.1 KB

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
36 "compilerOptions": {
37 "jsx": "react-jsx",
38 "moduleResolution": "Bundler",
39 "module": "ESNext",
40 "target": "ES2022",
41 "skipLibCheck": true,
42 "strictNullChecks": true
43 }
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
102 // ...
103 "type": "module",
104 "scripts": {
105 "dev": "vite dev",
106 "build": "vite build"
107 }
109```
110​
111# Rsbuild
112​
113```json
115 // ...
116 "type": "module",
117 "scripts": {
118 "dev": "rsbuild dev",
119 "build": "rsbuild build"
120 }
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```
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
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 )
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 )
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 )
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 )
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).