Lesson 178 of 296
Fetching data on the server
What you will learn
- Fetching in async Server Components
- Talking to the database directly
- Avoiding request waterfalls with parallel fetching
- Sharing data between components without prop drilling
- Where to fetch in Client Components
On this page
Async Server Components
A Server Component can be an async function and simply await data:
type Lesson = { id: number; title: string; minutes: number };
async function getLessons(): Promise<Lesson[]> {
const res = await fetch("https://api.example.com/lessons");
if (!res.ok) throw new Error(`Failed to load lessons: ${res.status}`);
return (await res.json()) as Lesson[];
}
export default async function LessonsPage() {
const lessons = await getLessons();
return (
<ul>
{lessons.map((l) => (
<li key={l.id}>
{l.title} ({l.minutes} min)
</li>
))}
</ul>
);
}No useEffect, no loading state variables: the HTML arrives with the data already in it. A thrown error is caught by the nearest error.tsx (Lesson 180).
Use the database directly
If the data is in your own database, do not call your own API route from a Server Component (that is an extra, unnecessary network hop). Call the data layer directly:
import { getProduct } from "@/lib/db";
export async function ProductSummary({ sku }: { sku: string }) {
const product = await getProduct(sku);
return product ? <p>{product.name}</p> : <p>Not found</p>;
}A good structure: a data access layer (for example lib/data/products.ts, marked server-only) that does authorisation checks and returns only the fields the UI needs. Pages call it. This keeps security in one place (Part 20).
Waterfalls: fetch in parallel
A waterfall happens when requests run one after another even though they do not depend on each other:
const user = await getUser(id); 200 ms
const orders = await getOrders(id); 300 ms
const reviews = await getReviews(id); 250 ms total about 750 msStart them together with Promise.all (Lesson 79):
type Account = { id: string; name: string };
type Order = { id: string; totalPence: number };
declare function getUser(id: string): Promise<Account>;
declare function getOrders(id: string): Promise<Order[]>;
export async function AccountOverview({ id }: { id: string }) {
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);
return (
<section>
<h2>{user.name}</h2>
<p>{orders.length} orders</p>
</section>
);
}Total time is now the slowest request, not the sum. Only keep requests sequential when one truly needs the other's result (for example, you need the user's company ID to load the company).
Nested components can also create waterfalls: a parent awaits its data before rendering a child that then awaits its own. Streaming with Suspense (Lesson 180) lets independent sections load at the same time and appear when ready.
Sharing data without prop drilling
Several components on one page need the current user. Instead of fetching once and passing it down, each component can call the same function. Wrap the function with React's cache() so it runs once per request, however many times it is called:
import { cache } from "react";
type CurrentUser = { id: string; name: string };
declare function readSessionUser(): Promise<CurrentUser | null>;
export const getCurrentUser = cache(async (): Promise<CurrentUser | null> => {
return readSessionUser();
});This is called request memoisation. Next.js also automatically de-duplicates identical fetch calls (same URL and options) during one render.
Reading cookies and headers
import { cookies, headers } from "next/headers";
export async function Greeting() {
const cookieStore = await cookies();
const headerList = await headers();
const theme = cookieStore.get("theme")?.value ?? "light";
const language = headerList.get("accept-language") ?? "en-GB";
return <p data-theme={theme}>Language: {language}</p>;
}In Next.js 15 and 16 these functions are async. Using them makes the page dynamic (it must be rendered per request, Lesson 183), because the result depends on the request.
Fetching in Client Components
Sometimes data must be fetched in the browser: data that changes as the user interacts (live search, infinite scroll), or user-specific data on an otherwise static page. Use TanStack Query or SWR (Lesson 174), calling a route handler (Lesson 181). Avoid hand-written useEffect fetching where you can.
Another pattern: start a fetch in a Server Component without awaiting it, pass the promise to a Client Component, and read it there with React's use() inside Suspense (Lesson 173). The page shell renders immediately while the data streams.
How to say it in an interview
"In the App Router I fetch in async Server Components, so HTML arrives with the data and no client fetching code is shipped. For my own data I call a server-only data access layer directly rather than my own API, with authorisation checks inside it. I avoid waterfalls by starting independent requests together with Promise.all and by streaming sections with Suspense. React's cache de-duplicates a function like getCurrentUser within one request so components can each call it instead of prop drilling. cookies and headers are async and make a route dynamic. For interactive client-side data I use TanStack Query against route handlers."
Key words
| Word | Meaning |
|---|---|
| Data access layer | Server-only functions that load data and check permissions |
| Waterfall | Independent requests running one after another |
| Parallel fetching | Starting independent requests at the same time |
| Request memoisation | Running the same function once per request |
| cache() | React function that memoises a function per request |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.