Data fetching in Next.js
In the App Router you fetch data directly inside async Server Components, with no useEffect. The real skill is avoiding waterfalls, streaming slow parts with Suspense and deduplicating repeated calls.
63.1 Fetch directly in a Server Component
- A page is a Server Component by default, so the function can be async and await fetch directly.
- No useEffect, no loading state code: the browser receives ready HTML.
- The API key (process.env.API_KEY) is safe because this code only runs on the server.
- Uncached data needs Suspense (previous video), so the orders folder also has a loading.tsx file.
React (TSX)
// app/orders/page.tsx (plus app/orders/loading.tsx)type Order = { id: number; item: string };const API = "https://api.shop.in/orders";export default async function OrdersPage() { const res = await fetch(API, { headers: { apikey: process.env.API_KEY! }, }); const orders: Order[] = await res.json(); return ( <ul> {orders.map((o) => ( <li key={o.id}>{o.item}</li> ))} </ul> );}Output
Loading... (then)Wireless mousePhone coverUSB-C cable63.2 Problem: why does the page take 3 s?
- The dashboard needs user, orders and offers; each function takes 1 second.
- getOrders does not start until getUser resolves, and offers wait the same way: 3 independent requests in a line.
React (TSX)
import { getUser, getOrders, getOffers } from "@/lib/data";export default async function Dashboard() { const user = await getUser(); // 1 s const orders = await getOrders(); // 1 s const offers = await getOffers(); // 1 s return ( <main> <h1>Hi {user.name}</h1> <p>{orders.length} orders</p> <p>{offers.length} offers</p> </main> );}Output
Loading... (then)# Hi Rahul2 orders3 offersServer: data arrived after 3 s63.3 What is a waterfall?
- await pauses the function until the promise resolves, so the next line does not run until then.
- Requests run one after another like water falling down steps: a waterfall.
- Total time = sum of all requests, even though these three do not depend on each other.
- Step 1
1.getUser: 0 to 1 s
- Step 2
2.getOrders: 1 to 2 s (waits for user)
- Step 3
3.getOffers: 2 to 3 s (waits for orders)
- Step 4
4.Page ready at 3 s = 1 + 1 + 1
With Promise.all all three run 0 to 1 s and the page is ready at 1 s
63.4 Fix: Promise.all
- Call all three functions together; all requests start at the same time and Promise.all waits for all of them.
- Total time = the slowest request, so the same page is ready in 1 second.
React (TSX)
import { getUser, getOrders, getOffers } from "@/lib/data";export default async function Dashboard() { const [user, orders, offers] = await Promise.all([ getUser(), getOrders(), getOffers(), ]); return ( <main> <h1>Hi {user.name}</h1> <p>{orders.length} orders</p> <p>{offers.length} offers</p> </main> );}Output
# Hi Rahul2 orders3 offersServer: data arrived in 1 s63.5 Checkpoint: start first, await later
- getUser (1 s) and getOrders (2 s) are called without await, then awaited.
- Answer: 2 s, not 3. The request starts the moment the function is called; await only waits for the result.
- So this is also a way to fetch in parallel.
React (TSX)
import { getUser, getOrders } from "@/lib/slow";export default async function Page() { const userP = getUser(); // 1 s const ordersP = getOrders(); // 2 s const user = await userP; const orders = await ordersP; return <p>{user.name}: {orders.length}</p>;}Output
Rahul: 2Server: ready in 2 s (not 3)63.6 Slow part: stream it with Suspense
- A Deals section from a recommendation service takes 3 s; awaiting it in the page would block everything.
- Make Deals its own async Server Component and wrap it in Suspense with a fallback.
- Heading and Loading appear at 1 s; deals stream into place 3 s later.
React (TSX)
import { Suspense } from "react";import { getUser } from "@/lib/data";import { Deals } from "./Deals"; export default async function Dashboard() { const user = await getUser(); // 1 s return ( <main> <h1>Hi {user.name}</h1> <Suspense fallback={<p>Loading...</p>}> <Deals /> </Suspense> </main> );}Output
# Hi RahulLoading... (3 seconds later)# Hi RahulDiwali sale: 20% offBank offer: 10% back- Step 1
1.Server sends shell + fallback: in the browser at 1 s
- Step 2
2.Deals fetch keeps running on the server
- Step 3
3.Data arrives: its HTML is sent as a new chunk in the same response
- Step 4
4.React swaps the fallback for the deals
loading.tsx does the same for a whole page: Next.js wraps the page in Suspense automatically
63.7 Duplicate DB call: React cache
- The account layout and the page both need getUser: normally two DB queries in one request.
- Wrap fetchUser in React's cache(): within one request the same id runs the query only once.
- Next.js already dedupes fetch to the same URL; for database calls you add cache() yourself.
TypeScript
// lib/user.tsimport { cache } from "react";import { db } from "./db"; async function fetchUser(id: string) { console.log("DB query: user", id); return db.user.findUnique({ where: { id }, });} export const getUser = cache(fetchUser);Output
$ npm run devDB query: user 763.8 Comparison: patterns and their timing
| Pattern | Requests (1 s, 1 s, 1 s) | Page ready | Use it when |
|---|---|---|---|
| Sequential await | One after another | 3 s | Request B needs A's result |
| Promise.all | All together | 1 s (slowest) | Requests are independent |
| Start, then await | All together | Slowest | Same as Promise.all, written separately |
| Suspense around slow part | Rest not blocked | Shell early, slow part streams | One section is much slower |
63.9 Common mistakes
- Awaiting independent requests one after another (waterfall).
- Fetching your own Route Handler via a localhost URL from a Server Component: an extra HTTP request to itself, and the URL does not work at build or after deploy.
- Fix: import the function the Route Handler uses and call it directly; you are already on the server.
- Myth: Suspense makes data faster. Wrong: Deals still takes 3 s; Suspense only decides what the user sees meanwhile. For speed you need caching (next video).
React (TSX)
// Wrong: extra HTTP request to itself, fails at buildexport default async function OrdersPage() { const res = await fetch( "http://localhost:3000/api/orders", ); const orders = await res.json(); return <p>{orders.length} orders</p>;}React (TSX)
// Right: call the function directlyimport { getOrders } from "@/lib/data"; export default async function OrdersPage() { const orders = await getOrders(); return <p>{orders.length} orders</p>;}63.10 4 rules of data fetching
- Fetch data in the Server Component right where it is needed; duplicate calls in a request get deduped.
- Run independent requests in parallel with Promise.all; keep sequential only what depends on a previous result.
- Give every slow section its own Suspense boundary.
- Pass a Client Component only the data it needs as props, never API keys.
63.11 Interview tips
- Server Components are async, so I await fetch or DB calls directly in the component and secrets stay on the server.
- I run independent requests with Promise.all so no waterfall forms.
- I wrap slow parts in Suspense to stream them; the rest of the page is not blocked.
- When one DB call is needed in many places, I dedupe it per request with React cache.
- Never fetch your own API route from a Server Component; call the data function directly.