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

reading-writing-file.md

588 lines19.6 KB

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![TanStack Start Welcome Page After Setup](https://raw.githubusercontent.com/TanStack/router/main/docs/router/assets/reading-writing-file-setup.png)
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
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 }
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
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[]
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 )
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 )
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![DevJoke App with 5 DevJokes](https://raw.githubusercontent.com/TanStack/router/main/docs/router/assets/reading-writing-file-devjokes-1.png)
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 )
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 )
449```
450​
451With this, our UI should look like this:
452![DevJoke App with Form to Add Jokes](https://raw.githubusercontent.com/TanStack/router/main/docs/router/assets/reading-writing-file-devjokes-2.png)
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).