Explain it simply
Server data fetching in plain language
Fetching data in a client-side React app is like going shopping after the guests arrive: the page appears empty, useEffect fetches, a loading state shows, and only then is the data filled in. In a Server Component you shop before the guests come: make the component async, await the data and send ready-made HTML.
Because this runs on the server, the browser never sees your API keys or database password, and being close to the data source usually makes it faster.
Problem → Why → Solution
The problem: a useEffect fetch and an unchecked response
The component below, copied from the React lessons, still works in Next.js, but it has two problems. The user first sees only 'Loading…', and search engines do not find the note titles in the HTML. Second, on the day the API returns a 500, the error JSON is treated as the notes array and the page crashes with notes.map is not a function.
"use client";
import { useEffect, useState } from "react";
export default function NotesPage() {
const [notes, setNotes] = useState<{ id: string; title: string }[] | null>(null);
useEffect(() => {
fetch("https://api.example.com/notes")
.then((response) => response.json()) // a 500 body is parsed as "notes" too
.then(setNotes);
}, []);
if (!notes) return <p>Loading…</p>; // this is all crawlers and slow phones see
return <ul>{notes.map((note) => <li key={note.id}>{note.title}</li>)}</ul>;
}Why this matters
fetch() rejects only when the network itself fails; a 404 or 500 is an ordinary response with ok: false. Skip the status check and an error body gets shown as if it were data. In a Server Component the data is loaded before rendering, and throwing on a bad status lets lesson 10's error.tsx catch it, while successful pages arrive with the data already in the HTML.
Core concept: await before you render
A Server Component can be an async function, so you write await fetch(...) or await db.query(...) right inside the body that renders. Using an ORM or database client directly keeps the credentials out of the client bundle. As lesson 20 will show, you still have to check that the user is allowed to see the data.
Using fetch follows three steps: send the request, check response.ok and throw an error that includes the status when it fails, and only then call response.json(). response.json() is typed as any, so a return type such as Promise<Note[]> is a promise to the compiler, not a runtime check; validate untrusted APIs with a library such as zod.
Mind the caching default across versions. Next.js 14 cached fetch by default, but from Next.js 15 fetch results are not cached by default, so every request gets fresh data. To cache, use "use cache" from lesson 15, and see the Fetching Data and Caching pages of the Next.js docs for details. Caching is different from memoization: within one render, identical fetch calls (same URL and options) are sent only once, so several components can fetch the same data themselves instead of passing it down as props.
For data inside your own app, do not call your own Route Handler (/api/notes) over HTTP from a Server Component. Both run on the server, so it adds a network round trip, and it can fail at build time when no server is running yet. Import and call the same getNotes() function that the Route Handler uses. If several components call a database function during one request, wrap it in React's cache() so the query runs only once.
- Request arrives; async component runs
- Await fetch or the database
- Not ok? throw, error.tsx shows
- Send HTML with the data inside
The browser receives HTML that already contains the data, with no loading state; if the wait is long, use streaming from lesson 14.
General pattern
async function loadThing(): Promise<Thing> {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
}
export default async function Page() {
const thing = await loadThing();
return <View thing={thing} />;
}Keep data loading in one typed function that checks the status. The page simply awaits that function and renders the result.
Worked example: loading the note list on the server
This page replaces the useEffect version from the problem section. There is no "use client", no useState and no loading branch any more, and the API URL lives in one place, getNotes.
type Note = { id: string; title: string };
async function getNotes(): Promise<Note[]> {
const response = await fetch("https://api.example.com/notes");
if (!response.ok) throw new Error("Could not load notes");
return response.json();
}
export default async function NotesPage() {
const notes = await getNotes();
return (
<ul>
{notes.map((note) => <li key={note.id}>{note.title}</li>)}
</ul>
);
}Code breakdown
- A typed loader
async function getNotes(): Promise<Note[]> {All loading logic sits in one function, so switching to a database later means changing only this spot.
- Check the status
if (!response.ok) throw new Error("Could not load notes");fetch does not reject on 404/500, so the code throws itself, and the nearest error.tsx catches it.
- An async page
export default async function NotesPage() {The page component itself is async, so it can wait for the data before rendering.
- Await, then render
const notes = await getNotes();JSX is returned only after this line, so the HTML that reaches the browser already contains the note titles.
Note titles fetched on the server show up as an HTML list.- await fetch(url)
- check response.ok
- return response.json()
ok: true (200-299)
Data is rendered into the HTML
ok: false (404, 500...)
throw: the nearest error.tsx shows
Avoiding waterfalls with Promise.all
Two awaits written one after another in a component mean the second request starts only after the first finishes. If the second does not need the first one's result, start both and wait for them together with Promise.all. If one request fails, the whole Promise.all fails, so use Promise.allSettled when partial results are acceptable. When the second request really needs the first result, such as an artist id before their albums, the order is unavoidable; lesson 14 shows how to stream that second part instead of blocking the page.
Sequential vs parallel (1 s + 2 s requests)
-------------------------------------------
sequential: [ notes 1s ][ stats 2s ] -> about 3 s
parallel: [ notes 1s ]
[ stats 2s ] -> about 2 sexport default async function DashboardPage() {
// both requests start now; neither waits for the other
const [notes, stats] = await Promise.all([getNotes(), getStats()]);
return <Dashboard notes={notes} stats={stats} />;
}In real projects
In real projects
Production projects rarely scatter fetch calls across pages; they collect data-access functions in a lib/ or data/ folder. Pages call only those functions, and URLs, headers and error handling are maintained in one place (lesson 19).
- A function that loads blog posts from a headless CMS reads the API token from process.env and is used only in Server Components, so the token never reaches the browser.
- A dashboard page loads users, orders and revenue together with Promise.all and waits only as long as the slowest request.
- ORM queries are wrapped in React's cache(), so even when both the layout and the page call getCurrentUser(), the database is asked once per request.
- During development, the logging option in next.config can print every server fetch with its URL, which makes slow or repeated requests easy to spot.
Common mistakes
Common mistakes when fetching data
Calling response.json() without checking response.ok
When the server answers 500 with { "error": "..." }, that object reaches the page as Note[] and fails later in map with a confusing error. Check the status first and throw an error message that includes the URL and status.
Calling your own Route Handler through a localhost URL
await fetch("http://localhost:3000/api/notes") works in development, but after deployment the host may be wrong, and during next build there is no server to answer. Let the Route Handler and the page both import the same data function.
Awaiting independent requests one by one
In const a = await getA(); const b = await getB();, if getB does not need a, that is wasted time. Combine them with Promise.all.
Best practices
Best practices
- Fetch data close to the component that uses it; thanks to memoization, the same request made in two places is sent once.
- Put the URL path and status in error messages so the failing request is obvious in the server logs.
- Keep API keys in environment variables without the NEXT_PUBLIC_ prefix and read them only from Server Components.
- When an external API's JSON is not trustworthy, validate it at runtime instead of relying on a TypeScript type alone.
Mini challenge
Mini challenge: a data layer for a dashboard
Write two data functions for a dashboard page. getJson<T> fetches a URL and throws an error containing the path and status when the response is not OK. loadDashboard loads /notes and /stats in parallel and returns the list of titles and the total. The fake API in the starter lets you run it directly in Node.
- getJson throws an error like 'GET /path failed with 500' when response.ok is false
- loadDashboard sends both requests at once with Promise.all
- The result is { titles: string[], total: number }
- Call /broken and print the error message
import express from "express";
import type { AddressInfo } from "node:net";
type Note = { id: string; title: string };
type Stats = { total: number };
// TODO: fetch the URL, throw "GET <path> failed with <status>" if not ok,
// otherwise return the parsed JSON as T
async function getJson<T>(url: string): Promise<T> {}
// TODO: load `${base}/notes` and `${base}/stats` in parallel
async function loadDashboard(base: string) {}
// Fake API: /notes, /stats and /broken (always 500)
const app = express();
app.get("/notes", (_req, res) => {
res.json([{ id: "1", title: "Routing" }, { id: "2", title: "Caching" }]);
});
app.get("/stats", (_req, res) => {
res.json({ total: 2 });
});
app.get("/broken", (_req, res) => {
res.status(500).json({ error: "database is down" });
});
// TODO: listen on port 0, print loadDashboard(base), then the /broken error,
// then close the serverExpected: It prints { titles: [ 'Routing', 'Caching' ], total: 2 } and then GET /broken failed with 500 on the next line. The server is closed, so the program exits by itself.
Show hint
Use new URL(url).pathname to get the path. Read the server's port from (server.address() as AddressInfo).port and build base as http://127.0.0.1:<port>.
Show solution
import express from "express";
import type { AddressInfo } from "node:net";
type Note = { id: string; title: string };
type Stats = { total: number };
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`GET ${new URL(url).pathname} failed with ${response.status}`);
}
return (await response.json()) as T;
}
async function loadDashboard(base: string) {
const [notes, stats] = await Promise.all([
getJson<Note[]>(`${base}/notes`),
getJson<Stats>(`${base}/stats`),
]);
return { titles: notes.map((note) => note.title), total: stats.total };
}
const app = express();
app.get("/notes", (_req, res) => {
res.json([{ id: "1", title: "Routing" }, { id: "2", title: "Caching" }]);
});
app.get("/stats", (_req, res) => {
res.json({ total: 2 });
});
app.get("/broken", (_req, res) => {
res.status(500).json({ error: "database is down" });
});
const server = app.listen(0, async () => {
const { port } = server.address() as AddressInfo;
const base = `http://127.0.0.1:${port}`;
console.log(await loadDashboard(base));
try {
await getJson<Note[]>(`${base}/broken`);
} catch (error) {
console.log((error as Error).message);
}
server.close();
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Make Server Components async and await fetch or the database before rendering.
- fetch does not reject on 404/500, so check response.ok and throw; error.tsx will catch it.
- Since Next.js 15 fetch is not cached by default, though identical requests in one render are memoized.
- Send independent requests with Promise.all, and never call your own Route Handler over HTTP.
Next.js — Fetching Data — Next.js
Next.js — Fetching Data — Next.js