Open History to see the last commit
1---
2id: fetching-external-api
3title: Calling an external API using TanStack Start
4---
5β
6This guide demonstrates how to integrate external API calls into your TanStack Start application using route loaders. We will use TMDB API to fetch popular movies using TanStack Start and understand how to fetch data in a TanStack Start app.
7β
8The complete code for this tutorial is available on [GitHub](https://github.com/shrutikapoor08/tanstack-start-movies).
9β
10## What You'll Learn
11β
121. Setting up external API integration with TanStack Start
131. Implementing route loaders for server-side data fetching
141. Building responsive UI components with fetched data
151. Handling loading states and error management
16β
17## Prerequisites
18β
19- Basic knowledge of React and TypeScript
20- Node.js (v18+) and `pnpm` installed on your machine
21- A TMDB API key (free at [themoviedb.org](https://www.themoviedb.org))
22β
23## Nice to know
24β
25- [TanStack Router](/router/latest/docs/framework/react/routing/routing-concepts)
26β
27## Setting up a TanStack Start Project
28β
29First, let's create a new TanStack Start project:
30β
31```bash
32pnpx create-start-app movie-discovery
33cd movie-discovery
34```
35β
36When 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.
37β
38Optionally, you can pass in a `--add-on` flag to get options such as Shadcn, Clerk, Convex, TanStack Query, etc.
39β
40Once setup is complete, install dependencies and start the development server:
41β
42```bash
43pnpm i
44pnpm dev
45```
46β
47## Understanding the Project Structure
48β
49At this point, the project structure should look like this:
50β
51```text
52/movie-discovery
53βββ src/
54β βββ routes/
55β β βββ __root.tsx # Root layout
56β β βββ index.tsx # Home page
57β β βββ fetch-movies.tsx # Movie fetching route
58β βββ types/
59β β βββ movie.ts # Movie type definitions
60β βββ router.tsx # Router configuration
61β βββ routeTree.gen.ts # Generated route tree
62β βββ styles.css # Global styles
63βββ public/ # Static assets
64βββ vite.config.ts or rsbuild.config.ts # TanStack Start configuration
65βββ package.json # Project dependencies
66βββ tsconfig.json # TypeScript configuration
67β
68```
69β
70Once your project is set up, you can access your app at `localhost:3000`. You should see the default TanStack Start welcome page.
71β
72## Step 1: Setup a `.env` file with TMDB_AUTH_TOKEN
73β
74To fetch movies from the TMDB API, you need an authentication token. You can get this for free at themoviedb.org.
75β
76First, let's set up environment variables for our API key. Create a `.env` file in your project root:
77β
78```bash
79touch .env
80β
81```
82β
83Add your TMDB API token to this file:
84β
85```dotenv
86TMDB_AUTH_TOKEN=your_bearer_token_here
87```
88β
89_Important_: Make sure to add `.env` to your `.gitignore` file to keep your API keys secure.
90β
91## Step 2: Defining Data Types
92β
93Let's create TypeScript interfaces for our movie data. Create a new file at `src/types/movie.ts`:
94β
95```ts
96// src/types/movie.ts
97export interface Movie {
98 id: number
99 title: string
100 overview: string
101 poster_path: string | null
102 backdrop_path: string | null
103 release_date: string
104 vote_average: number
105 popularity: number
106}
107β
108export interface TMDBResponse {
109 page: number
110 results: Movie[]
111 total_pages: number
112 total_results: number
113}
114```
115β
116## Step 3: Creating the Route with API Fetch Function
117β
118To 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.
119Let's create our route that fetches data from the TMDB API. Create a new file at `src/routes/fetch-movies.tsx`:
120β
121```typescript
122// src/routes/fetch-movies.tsx
123import { createFileRoute } from '@tanstack/react-router'
124import type { Movie, TMDBResponse } from '../types/movie'
125import { createServerFn } from '@tanstack/react-start'
126β
127const API_URL =
128 'https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc'
129β
130const 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)
146β
147export const Route = createFileRoute('/fetch-movies')({
148 component: MoviesPage,
149 loader: async (): Promise<{ movies: Movie[]; error: string | null }> => {
150 try {
151 const moviesData = await fetchPopularMovies()
152 return { movies: moviesData.results, error: null }
153 } catch (error) {
154 console.error('Error fetching movies:', error)
155 return { movies: [], error: 'Failed to load movies' }
156 }
157 },
158})
159```
160β
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β
168## Step 4: Building the Movie Components
169β
170Now let's create the components that will display our movie data. Add these components to the same `fetch-movies.tsx` file:
171β
172```tsx
173// MovieCard component
174const MovieCard = ({ movie }: { movie: Movie }) => {
175 return (
176 <div
177 className="bg-white/10 border border-white/20 rounded-lg overflow-hidden backdrop-blur-sm shadow-md hover:shadow-xl transition-all duration-300 hover:scale-105"
178 aria-label={`Movie: ${movie.title}`}
179 role="group"
180 >
181 {movie.poster_path && (
182 <img
183 src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
184 alt={movie.title}
185 className="w-full h-64 object-cover"
186 />
187 )}
188 <div className="p-4">
189 <MovieDetails movie={movie} />
190 </div>
191 </div>
192 )
193}
194β
195// MovieDetails component
196const MovieDetails = ({ movie }: { movie: Movie }) => {
197 return (
198 <>
199 <h3 className="text-lg font-semibold mb-2 line-clamp-2">{movie.title}</h3>
200 <p className="text-sm text-gray-300 mb-3 line-clamp-3 h-10">
201 {movie.overview}
202 </p>
203 <div className="flex justify-between items-center text-xs text-gray-400">
204 <span>{movie.release_date}</span>
205 <span className="flex items-center">
206 βοΈ {movie.vote_average.toFixed(1)}
207 </span>
208 </div>
209 </>
210 )
211}
212```
213β
214## Step 5: Creating the MoviesPage Component
215β
216Finally, let's create the main component that consumes the loader data:
217β
218```tsx
219// MoviesPage component
220const MoviesPage = () => {
221 const { movies, error } = Route.useLoaderData()
222β
223 return (
224 <div
225 className="flex items-center justify-center min-h-screen p-4 text-white"
226 style={{
227 backgroundColor: '#000',
228 backgroundImage:
229 'radial-gradient(ellipse 60% 60% at 0% 100%, #444 0%, #222 60%, #000 100%)',
230 }}
231 role="main"
232 aria-label="Popular Movies Section"
233 >
234 <div className="w-full max-w-6xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10">
235 <h1 className="text-3xl mb-6 font-bold text-center">Popular Movies</h1>
236β
237 {error && (
238 <div
239 className="text-red-400 text-center mb-4 p-4 bg-red-900/20 rounded-lg"
240 role="alert"
241 >
242 {error}
243 </div>
244 )}
245β
246 {movies.length > 0 ? (
247 <div
248 className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
249 aria-label="Movie List"
250 >
251 {movies.slice(0, 12).map((movie) => (
252 <MovieCard key={movie.id} movie={movie} />
253 ))}
254 </div>
255 ) : (
256 !error && (
257 <div className="text-center text-gray-400" role="status">
258 Loading movies...
259 </div>
260 )
261 )}
262 </div>
263 </div>
264 )
265}
266```
267β
268### Understanding How It All Works Together
269β
270```mermaid
271sequenceDiagram
272 autonumber
273 actor U as User
274 participant R as Router (TanStack Start)
275 participant L as Route Loader (/fetch-movies)
276 participant A as External API (TMDB)
277 participant V as MoviesPage (UI)
278β
279 U->>R: Navigate to /fetch-movies
280 R->>L: Invoke loader (server-side)
281 L->>A: GET /movie/popular\nAuthorization: Bearer <TOKEN>
282 A-->>L: JSON TMDBResponse
283 alt response.ok
284 L-->>R: { movies, error: null }
285 R->>V: Render SSR with movies
286 V-->>U: HTML with movie grid
287 else non-ok / error
288 L-->>R: { movies: [], error: "Failed to load movies" }
289 R->>V: Render SSR with error alert
290 V-->>U: HTML with error state
291 end
292β
293 note over L,V: Loader validates response.ok,\nreturns data or error for initial render
294```
295β
296Let's break down how the different parts of our application work together:
297β
2981. Route loader: When a user visits `/fetch-movies`, the loader function runs on the server
2992. API call: The loader calls `fetchPopularMovies()` which makes an HTTP request to TMDB
3003. Server-Side rendering: The data is fetched on the server reducing the load on the client side
3014. Component rendering: The `MoviesPage` component receives the data via `Route.useLoaderData()`
3025. Rendering UI: The movie cards are rendered with the fetched data
303β
304## Step 6: Testing Your Application
305β
306Now you can test your application by visiting [http://localhost:3000/fetch-movies](http://localhost:3000/fetch-movies). If everything is set up correctly, you should see a grid of popular movies with their posters, titles, and ratings. Your app should look like this:
307β
308
309β
310## Conclusion
311β
312You've successfully built a movie discovery app that integrates with an external API using TanStack Start. This tutorial demonstrated how to use route loaders for server-side data fetching and building UI components with external data.
313β
314While fetching data at build time in TanStack Start is perfect for static content like blog posts or product pages, it's not ideal for interactive apps. If you need features like real-time updates, caching, or infinite scrolling, you'll want to use [TanStack Query](/query/latest) on the client side instead. TanStack Query makes it easy to handle dynamic data with built-in caching, background updates, and smooth user interactions. By using TanStack Start for static content and TanStack Query for interactive features, you get fast loading pages plus all the modern functionality users expect.