Skip to content

Commit e41cdf2

Browse files
Small update to guide on fetching external API (#5900)
* small fix to server function * ci: apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 8f3f7fc commit e41cdf2

File tree

2 files changed

+29
-24
lines changed

2 files changed

+29
-24
lines changed

docs/start/framework/react/tutorial/fetching-external-api.md

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,9 @@ At this point, the project structure should look like this:
6767
6868
```
6969

70-
Once your project is set up, you can access your app at localhost:3000. You should see the default TanStack Start welcome page.
70+
Once your project is set up, you can access your app at `localhost:3000`. You should see the default TanStack Start welcome page.
7171

72-
## Step 1: Setup a .env file with TMDB_AUTH_TOKEN
72+
## Step 1: Setup a `.env` file with TMDB_AUTH_TOKEN
7373

7474
To fetch movies from the TMDB API, you need an authentication token. You can get this for free at themoviedb.org.
7575

@@ -115,36 +115,34 @@ export interface TMDBResponse {
115115

116116
## Step 3: Creating the Route with API Fetch Function
117117

118-
Now let's create our route that fetches data from the TMDB API. Create a new file at `src/routes/fetch-movies.tsx`:
118+
To call the TMDB API, we're going to create a server function that fetches data on the server. This approach keeps our API credentials secure by never exposing them to the client.
119+
Let's create our route that fetches data from the TMDB API. Create a new file at `src/routes/fetch-movies.tsx`:
119120

120121
```typescript
121122
// src/routes/fetch-movies.tsx
122123
import { createFileRoute } from '@tanstack/react-router'
123124
import type { Movie, TMDBResponse } from '../types/movie'
125+
import { createServerFn } from '@tanstack/react-start'
124126

125127
const API_URL =
126128
'https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc'
127129

128-
async function fetchPopularMovies(): Promise<TMDBResponse> {
129-
const token = process.env.TMDB_AUTH_TOKEN
130-
if (!token) {
131-
throw new Error('Missing TMDB_AUTH_TOKEN environment variable')
132-
}
133-
134-
const response = await fetch(API_URL, {
135-
headers: {
136-
accept: 'application/json',
137-
Authorization: `Bearer ${token}`,
138-
},
139-
})
140-
141-
if (!response.ok) {
142-
throw new Error(`Failed to fetch movies: ${response.statusText}`)
143-
}
144-
145-
const data = (await response.json()) as TMDBResponse
146-
return data
147-
}
130+
const fetchPopularMovies = createServerFn().handler(
131+
async (): Promise<TMDBResponse> => {
132+
const response = await fetch(API_URL, {
133+
headers: {
134+
accept: 'application/json',
135+
Authorization: `Bearer ${process.env.TMDB_AUTH_TOKEN}`,
136+
},
137+
})
138+
139+
if (!response.ok) {
140+
throw new Error(`Failed to fetch movies: ${response.statusText}`)
141+
}
142+
143+
return response.json()
144+
},
145+
)
148146

149147
export const Route = createFileRoute('/fetch-movies')({
150148
component: MoviesPage,
@@ -160,6 +158,13 @@ export const Route = createFileRoute('/fetch-movies')({
160158
})
161159
```
162160

161+
_What's happening here:_
162+
163+
- `createServerFn()` creates a server-only function that runs exclusively on the server, ensuring our `TMDB_AUTH_TOKEN` environment variable never gets exposed to the client. The server function makes an authenticated request to the TMDB API and returns the parsed JSON response.
164+
- The route loader runs on the server when a user visits /fetch-movies, calling our server function before the page renders
165+
- Error handling ensures the component always receives valid data structure - either the movies or an empty array with an error message
166+
- This pattern provides server-side rendering, automatic type safety, and secure API credential handling out of the box.
167+
163168
## Step 4: Building the Movie Components
164169

165170
Now let's create the components that will display our movie data. Add these components to the same `fetch-movies.tsx` file:

docs/start/framework/react/tutorial/reading-writing-file.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ id: reading-and-writing-file
33
title: Building a Full Stack DevJokes App with TanStack Start
44
---
55

6-
This tutorial will guide you through building a complete full-stack application using TanStack Start. You'll create a DevJokesapp where users can view and add developer-themed jokes, demonstrating key concepts of TanStack Start including server functions, file-based data storage, and React components.
6+
This 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 React components.
77

88
Here's a demo of the app in action:
99

0 commit comments

Comments
 (0)