Open History to see the last commit
1---
2id: reading-and-writing-file
3title: Building a Full Stack DevJokes App with TanStack Start
4redirect_from:
5 - /framework/solid/guide/reading-writing-file
6---
7β
8This tutorial will guide you through building a complete full-stack application using TanStack Start. You'll create a DevJokes app where users can view and add developer-themed jokes, demonstrating key concepts of TanStack Start including server functions, file-based data storage, and Solid components.
9β
10Here's a demo of the app in action:
11β
12<iframe width="560" height="315" src="https://www.youtube.com/embed/zd0rtKbtlgU?si=7W1Peoo0W0WvZmAd" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
13β
14The complete code for this tutorial is available on [GitHub](https://github.com/shrutikapoor08/devjokes).
15β
16## What You'll Learn
17β
181. Setting up a TanStack Start project
192. Implementing server functions
203. Reading and writing data to files
214. Building a complete UI with Solid components
225. Using TanStack Router for data fetching and navigation
23β
24## Prerequisites
25β
26- Basic knowledge of Solid and TypeScript.
27- Node.js and `pnpm` installed on your machine
28β
29## Nice to know
30β
31- [Server Side Rendering (SSR)](/router/latest/docs/framework/solid/guide/ssr)
32- [TanStack Router concepts](/router/latest/docs/framework/solid/routing/routing-concepts)
33- [Solid Query concepts](/query/latest/docs/framework/solid/overview)
34β
35## Setting up a TanStack Start Project
36β
37First, let's create a new TanStack Start project:
38β
39```bash
40pnpx @tanstack/cli@latest create --framework solid devjokes
41cd devjokes
42```
43β
44When this script runs, it will ask you a few setup questions. You can either pick choices that work for you or just press enter to accept the defaults.
45β
46Optionally, you can pass in a `--add-on` flag to get options such as Shadcn, Clerk, Convex, TanStack Query, etc.
47β
48Once setup is complete, install dependencies and start the development server:
49β
50```bash
51pnpm i
52pnpm dev
53```
54β
55For this project, we'll need the `uuid` package:
56β
57```bash
58# Install uuid for generating unique IDs
59pnpm add uuid
60```
61β
62## Understanding the project structure
63β
64At this point, the project structure should look like this -
65β
66```
67/devjokes
68βββ src/
69β βββ routes/
70β β βββ demo/ # Demo routes
71β β βββ __root.tsx # Root layout
72β β βββ index.tsx # Home page
73β βββ components/ # Solid components
74β βββ data/ # Data files
75β βββ router.tsx # Router configuration
76β βββ routeTree.gen.ts # Generated route tree
77β βββ styles.css # Global styles
78βββ public/ # Static assets
79βββ vite.config.ts or rsbuild.config.ts # TanStack Start configuration
80βββ package.json # Project dependencies
81βββ tsconfig.json # TypeScript configuration
82```
83β
84This structure might seem overwhelming at first, but here are the key files you need to focus on:
85β
861. `src/router.tsx` - Sets up routing for your application
872. `src/routes/__root.tsx` - The root layout component where you can add global styles and components
883. `src/routes/index.tsx` - Your home page
89β
90Once your project is set up, you can access your app at `localhost:3000`. You should see the default TanStack Start welcome page.
91β
92At this point, your app will look like this:
93β
94
95β
96## Step 1: Reading Data From a File
97β
98Let's start by creating a file-based storage system for our jokes.
99β
100### Step 1.1: Create a JSON File with Jokes
101β
102Let's set up a list of jokes that we can use to render on the page. Create a `jokes.json` file within `src/data`:
103β
104```bash
105touch src/data/jokes.json
106```
107β
108Now, let's add some sample jokes to this file:
109β
110```json
111[
112 {
113 "id": "1",
114 "question": "Why don't keyboards sleep?",
115 "answer": "Because they have two shifts"
116 },
117 {
118 "id": "2",
119 "question": "Are you a RESTful API?",
120 "answer": "Because you GET my attention, PUT some love, POST the cutest smile, and DELETE my bad day"
121 },
122 {
123 "id": "3",
124 "question": "I used to know a joke about Java",
125 "answer": "But I ran out of memory."
126 },
127 {
128 "id": "4",
129 "question": "Why do Front-End Developers eat lunch alone?",
130 "answer": "Because, they don't know how to join tables."
131 },
132 {
133 "id": "5",
134 "question": "I am declaring a war.",
135 "answer": "var war;"
136 }
137]
138```
139β
140### Step 1.2: Create Types for Our Data
141β
142Let's create a file to define our data types. Create a new file at `src/types/index.ts`:
143β
144```typescript
145// src/types/index.ts
146export interface Joke {
147 id: string
148 question: string
149 answer: string
150}
151β
152export type JokesData = Joke[]
153```
154β
155### Step 1.3: Create Server Functions to Read the File
156β
157Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/solid/guide/server-functions).
158β
159```tsx
160// src/serverActions/jokesActions.ts
161import { createServerFn } from '@tanstack/solid-start'
162import * as fs from 'node:fs'
163import type { JokesData } from '../types'
164β
165const JOKES_FILE = 'src/data/jokes.json'
166β
167export const getJokes = createServerFn({ method: 'GET' }).handler(async () => {
168 const jokes = await fs.promises.readFile(JOKES_FILE, 'utf-8')
169 return JSON.parse(jokes) as JokesData
170})
171```
172β
173In this code, we are using `createServerFn` to create a server function that reads the jokes from the JSON file. The `handler` function is where we are using the `fs` module to read the file.
174β
175### Step 1.4: Consume Server Function on the Client Side
176β
177Now to consume this server function, we can simply call it in our code using TanStack Router which already comes with TanStack Start!
178β
179Now let's create a new component `JokesList` to render the jokes on the page with a little Tailwind styling sprinkle.
180β
181```tsx
182// src/components/JokesList.tsx
183import { Joke } from '../types'
184β
185interface JokesListProps {
186 jokes: Joke[]
187}
188β
189export function JokesList({ jokes }: JokesListProps) {
190 if (!jokes || jokes.length === 0) {
191 return <p class="text-gray-500 italic">No jokes found. Add some!</p>
192 }
193β
194 return (
195 <div class="space-y-4">
196 <h2 class="text-xl font-semibold">Jokes Collection</h2>
197 {jokes.map((joke) => (
198 <div
199 key={joke.id}
200 class="bg-white p-4 rounded-lg shadow-md border border-gray-200"
201 >
202 <p class="font-bold text-lg mb-2">{joke.question}</p>
203 <p class="text-gray-700">{joke.answer}</p>
204 </div>
205 ))}
206 </div>
207 )
208}
209```
210β
211Now let's call our server function inside `index.tsx` using TanStack Router which already comes with TanStack Start!
212β
213```jsx
214// src/routes/index.tsx
215import { createFileRoute } from '@tanstack/solid-router'
216import { getJokes } from './serverActions/jokesActions'
217import { JokesList } from './JokesList'
218β
219export const Route = createFileRoute('/')({
220 loader: async () => {
221 // Load jokes data when the route is accessed
222 return getJokes()
223 },
224 component: App,
225})
226β
227const App = () => {
228 const jokes = Route.useLoaderData() || []
229β
230 return (
231 <div class="max-w-2xl mx-auto py-12 px-4 space-y-6">
232 <h1 class="text-4xl font-bold text-center mb-10">DevJokes</h1>
233 <JokesList jokes={jokes} />
234 </div>
235 )
236}
237```
238β
239When the page loads, `jokes` will have data from the `jokes.json` file already!
240β
241With a little Tailwind styling, the app should look like this:
242β
243
244β
245## Step 2: Writing Data to a File
246β
247So far, we have been able to read from the file successfully! We can use the same approach to write to the `jokes.json` file using `createServerFunction`.
248β
249### Step 2.1: Create Server Function to Write to the File
250β
251It's time to modify the `jokes.json` file so that we can add new jokes to it. Let's create another server function but this time with a `POST` method to write to the same file.
252β
253```tsx
254// src/serverActions/jokesActions.ts
255import { createServerFn } from '@tanstack/solid-start'
256import * as fs from 'node:fs'
257import { v4 as uuidv4 } from 'uuid' // Add this import
258import type { Joke, JokesData } from '../types'
259β
260const JOKES_FILE = 'src/data/jokes.json'
261β
262export const getJokes = createServerFn({ method: 'GET' }).handler(async () => {
263 const jokes = await fs.promises.readFile(JOKES_FILE, 'utf-8')
264 return JSON.parse(jokes) as JokesData
265})
266β
267// Add this new server function
268export const addJoke = createServerFn({ method: 'POST' })
269 .validator((data: { question: string; answer: string }) => {
270 // Validate input data
271 if (!data.question || !data.question.trim()) {
272 throw new Error('Joke question is required')
273 }
274 if (!data.answer || !data.answer.trim()) {
275 throw new Error('Joke answer is required')
276 }
277 return data
278 })
279 .handler(async ({ data }) => {
280 try {
281 // Read the existing jokes from the file
282 const jokesData = await getJokes()
283β
284 // Create a new joke with a unique ID
285 const newJoke: Joke = {
286 id: uuidv4(),
287 question: data.question,
288 answer: data.answer,
289 }
290β
291 // Add the new joke to the list
292 const updatedJokes = [...jokesData, newJoke]
293β
294 // Write the updated jokes back to the file
295 await fs.promises.writeFile(
296 JOKES_FILE,
297 JSON.stringify(updatedJokes, null, 2),
298 'utf-8',
299 )
300β
301 return newJoke
302 } catch (error) {
303 console.error('Failed to add joke:', error)
304 throw new Error('Failed to add joke')
305 }
306 })
307```
308β
309In this code:
310β
311- We are using `createServerFn` to create server functions that run on the server but can be called from the client. This server function is used to write data to the file.
312- We are going to first use `validator` to validate the input data. This is a good practice to ensure that the data we are receiving is in the correct format.
313- We are going to perform the actual write operation in the `handler` function.
314- `getJokes` reads the jokes from our JSON file.
315- `addJoke` validates the input data and adds a new joke to our file.
316- We're using `uuidv4()` to generate unique IDs for our jokes.
317β
318### Step 2.2: Adding a Form to Add Jokes to our JSON File
319β
320Now, let's modify our home page to display jokes and provide a form to add new ones. Let's create a new component called `JokeForm.jsx` and add the following form to it:
321β
322```tsx
323// src/components/JokeForm.tsx
324import { createSignal } from 'solid'
325import { useRouter } from '@tanstack/solid-router'
326import { addJoke } from '../serverActions/jokesActions'
327β
328export function JokeForm() {
329 const router = useRouter()
330 const [question, setQuestion] = createSignal('')
331 const [answer, setAnswer] = createSignal('')
332 const [isSubmitting, setIsSubmitting] = createSignal(false)
333 const [error, setError] = createSignal<string | null>(null)
334β
335 return (
336 <form onSubmit={handleSubmit} class="mb-8">
337 {error && (
338 <div class="bg-red-100 text-red-700 p-2 rounded mb-4">{error}</div>
339 )}
340β
341 <div class="flex flex-col sm:flex-row gap-4 mb-8">
342 <input
343 id="question"
344 type="text"
345 placeholder="Enter joke question"
346 class="w-full p-2 border rounded focus:ring focus:ring-blue-300 flex-1"
347 value={question()}
348 onChange={(e) => setQuestion(e.target.value)}
349 required
350 />
351β
352 <input
353 id="answer"
354 type="text"
355 placeholder="Enter joke answer"
356 class="w-full p-2 border rounded focus:ring focus:ring-blue-300 flex-1 py-4"
357 value={answer()}
358 onChange={(e) => setAnswer(e.target.value)}
359 required
360 />
361β
362 <button
363 type="submit"
364 disabled={isSubmitting()}
365 class="bg-blue-500 hover:bg-blue-600 text-white font-medium rounded disabled:opacity-50 px-4"
366 >
367 {isSubmitting() ? 'Adding...' : 'Add Joke'}
368 </button>
369 </div>
370 </form>
371 )
372}
373```
374β
375### Step 2.3: Wire Up the Form to the Server Function
376β
377Now, let's wire the form up to our `addJoke` server function in the `handleSubmit` function. Calling a server action is simple! It's just a function call.
378β
379```tsx
380//JokeForm.tsx
381import { createSignal } from 'solid'
382import { useRouter } from '@tanstack/solid-router'
383import { addJoke } from '../serverActions/jokesActions'
384β
385export function JokeForm() {
386 const router = useRouter()
387 const [question, setQuestion] = createSignal('')
388 const [answer, setAnswer] = createSignal('')
389 const [isSubmitting, setIsSubmitting] = createSignal(false)
390 const [error, setError] = createSignal<string | null>(null)
391β
392 const handleSubmit = async () => {
393 if (!question() || !answer() || isSubmitting()) return
394 try {
395 setIsSubmitting(true)
396 await addJoke({
397 data: { question(), answer() },
398 })
399β
400 // Clear form
401 setQuestion('')
402 setAnswer('')
403β
404 // Refresh data
405 router.invalidate()
406 } catch (error) {
407 console.error('Failed to add joke:', error)
408 setError('Failed to add joke')
409 } finally {
410 setIsSubmitting(false)
411 }
412 }
413β
414 return (
415 <form onSubmit={handleSubmit} class="mb-8">
416 {error && (
417 <div class="bg-red-100 text-red-700 p-2 rounded mb-4">{error}</div>
418 )}
419 <div class="flex flex-col sm:flex-row gap-4 mb-8">
420 <input
421 id="question"
422 type="text"
423 placeholder="Enter joke question"
424 class="w-full p-2 border rounded focus:ring focus:ring-blue-300 flex-1"
425 value={question()}
426 onChange={(e) => setQuestion(e.target.value)}
427 required
428 />
429 <input
430 id="answer"
431 type="text"
432 placeholder="Enter joke answer"
433 class="w-full p-2 border rounded focus:ring focus:ring-blue-300 flex-1 py-4"
434 value={answer()}
435 onChange={(e) => setAnswer(e.target.value)}
436 required
437 />
438 <button
439 type="submit"
440 disabled={isSubmitting()}
441 class="bg-blue-500 hover:bg-blue-600 text-white font-medium rounded disabled:opacity-50 px-4"
442 >
443 {isSubmitting() ? 'Adding...' : 'Add Joke'}
444 </button>
445 </div>
446 </form>
447 )
448}
449```
450β
451With this, our UI should look like this:
452
453β
454## Understanding How It All Works Together
455β
456Let's break down how the different parts of our application work together:
457β
4581. **Server Functions**: These run on the server and handle data operations
459 - `getJokes`: Reads the jokes from our JSON file
460 - `addJoke`: Adds a new joke to our JSON file
461β
4622. **TanStack Router**: Handles routing and data loading
463 - The loader function fetches jokes data when the route is accessed
464 - `useLoaderData` makes this data available in our component
465 - `router.invalidate()` refreshes the data when we add a new joke
466β
4673. **Solid Components**: Build the UI of our application
468 - `JokesList`: Displays the list of jokes
469 - `JokeForm`: Provides a form for adding new jokes
470β
4714. **File-Based Storage**: Stores our jokes in a JSON file
472 - Reading and writing are handled by Node.js `fs` module
473 - Data is persisted between server restarts
474β
475## How Data Flows Through the Application
476β
477### Data Flow
478β
479```mermaid
480sequenceDiagram
481autonumber
482actor User
483participant UI as Browser (HomePage + Form)
484participant Loader as Route Loader (loader)
485participant Server
486participant Store as jokes.json
487β
488%% Visiting the Home Page
489User ->> UI: Visit /
490UI ->> Loader: loader() calls getJokes()
491Loader ->> Server: getJokes()
492Server ->> Store: Read jokes.json
493Store -->> Server: jokes data
494Server -->> Loader: jokes[]
495Loader -->> UI: useLoaderData() β jokes[]
496β
497%% Adding a New Joke
498User ->> UI: Fill form and submit
499UI ->> Server: handleSubmit β addJoke(newJoke)
500Server ->> Store: Read jokes.json
501Server ->> Store: Write updated jokes.json
502Server -->> UI: addJoke() resolved
503UI ->> Loader: router.invalidate() (re-run loader)
504Loader ->> Server: getJokes()
505Server ->> Store: Read jokes.json
506Store -->> Server: updated jokes[]
507Server -->> Loader: updated jokes[]
508Loader -->> UI: useLoaderData() β updated jokes[]
509```
510β
511When a user visits the home page:
512β
5131. The `loader` function in the route calls `getJokes()` server function
5142. The server reads `jokes.json` and returns the jokes data
5153. This data is passed to the `HomePage` component through `useLoaderData()`
5164. The `HomePage` component passes the data to the `JokesList` component
517β
518When a user adds a new joke:
519β
5201. They fill out the form and submit it
5212. The `handleSubmit` function calls the `addJoke()` server function
5223. The server reads the current jokes, adds the new joke, and writes the updated data back to `jokes.json`
5234. After the operation completes, we call `router.invalidate()` to refresh the data
5245. This triggers the loader again, fetching the updated jokes
5256. The UI updates to show the new joke in the list
526β
527Here's a demo of the app in action:
528β
529<iframe width="560" height="315" src="https://www.youtube.com/embed/zd0rtKbtlgU?si=7W1Peoo0W0WvZmAd" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
530β
531## Common Issues and Debugging
532β
533Here are some common issues you might encounter when building your TanStack Start application and how to resolve them:
534β
535### Server Functions Not Working
536β
537If your server functions aren't working as expected:
538β
5391. Check that you're using the correct HTTP method (`GET`, `POST`, etc.)
5402. Ensure file paths are correct and accessible to the server
5413. Check the server console for error messages
5424. Make sure you're not using client-only APIs in server functions
543β
544### Route Data Not Loading
545β
546If route data isn't loading properly:
547β
5481. Verify that your loader function is properly implemented
5492. Check that you're using `useLoaderData()` correctly
5503. Look for errors in the browser console
5514. Make sure your server function is working correctly
552β
553### Form Submission Issues
554β
555If form submissions aren't working:
556β
5571. Check for validation errors in your server function
5582. Verify that form event prevention (`e.preventDefault()`) is working
5593. Make sure state updates are happening correctly
5604. Look for network errors in the browser's Developer Tools
561β
562### File Reading/Writing Issues
563β
564When working with file-based storage:
565β
5661. Ensure file paths are correct
5672. Check file permissions
5683. Make sure you're handling async operations properly with `await`
5694. Add proper error handling for file operations
570β
571## Conclusion
572β
573Congratulations! You've built a full-stack DevJokes app using TanStack Start. In this tutorial, you've learned:
574β
575- How to set up a TanStack Start project
576- How to implement server functions for data operations
577- How to read and write data to files
578- How to build Solid components for your UI
579- How to use TanStack Router for routing and data fetching
580β
581This simple application demonstrates the power of TanStack Start for building full-stack applications with a minimal amount of code. You can extend this app by adding features like:
582β
583- Joke categories
584- Ability to edit and delete jokes
585- User authentication
586- Voting for favorite jokes
587β
588The complete code for this tutorial is available on [GitHub](https://github.com/shrutikapoor08/devjokes).