Fetching, Streaming and Caching Server Data
Fetch in Server Components without waterfalls, stream slow sections behind Suspense, and control caching by time and on demand with request memoisation.
Contentsand lesson path
On this page
- The brief
- Step 1: Stop the waterfall
- Step 2: Stream the slow panel
- Step 3: Cache on purpose
- Check your understanding
- Apply it
- Review prompt
Lessons of Server Components & Rendering Modes
- Rendering Strategies Side by Side: CSR, SSR, SSG and Streaming Concept · 25 min
- Server and Client Components: Boundaries, Secrets and Sessions Worked example · 30 min
- Fetching, Streaming and Caching Server Data Worked example · 30 min
- Server Actions, Revalidation and Hydration Pitfalls Worked example · 25 min
- Lab: Move a Signed-In Dashboard to the Server Lab · 30 min
- Check: Pick the Rendering Mode Knowledge check · 10 questions
What you will learn
- Fetch data in Server Components, stream slow sections with Suspense, and control caching and revalidation by time and on demand.
Prerequisites: Next.js App Router & Routing
01. The brief
The dashboard needs three pieces of data: the signed-in user's holdings (a fast query), the note count (fast), and a volatility feed from a slow external risk API (about two seconds). The first version of the page was written the way async code is usually written first — one await after another. The page took two seconds to appear, all of it spent waiting, and nothing else could render meanwhile.
This lesson fixes the page in three moves: fetch independent data concurrently, stream the genuinely slow panel behind Suspense, and cache what can be cached — per request and across requests — without ever caching one user's data into another user's page. The client-side fetching these steps replace is covered in Fetching data safely; on the server the same care shifts to ordering, streaming and cache scope.
02. Step 1: Stop the waterfall
Each await suspends until its promise settles, so sequential awaits add up. The calls below do not depend on each other, yet the page waits for all three in a row. Starting them together — Promise.all — turns three waits into the longest one.
// Before: three independent calls in a row (~900 ms)
const portfolio = await getPortfolio(user);
const notes = await listNotes(user);
const risk = await getRiskFeed(user);
// After: all three start now (~300 ms)
const [portfolio, notes, risk] = await Promise.all([
getPortfolio(user),
listNotes(user),
getRiskFeed(user),
]);You can check the arithmetic without a database. The script below replaces the three calls with fake 300 ms waits and rounds each measurement to the nearest 100 ms, because the exact figure drifts by a few milliseconds from run to run. Predict both lines before you run it with node waterfall.mjs.
// Three independent calls of 300 ms each, awaited two ways.
const call = () => new Promise((resolve) => setTimeout(resolve, 300));
const about = (ms) => `about ${Math.round(ms / 100) * 100} ms`;
let start = performance.now();
await call();
await call();
await call();
console.log(`sequential awaits: ${about(performance.now() - start)}`);
start = performance.now();
await Promise.all([call(), call(), call()]);
console.log(`Promise.all: ${about(performance.now() - start)}`);sequential awaits: about 900 ms
Promise.all: about 300 msReserve sequential awaits for data that genuinely depends on an earlier result — the order id you can only get after loading the order. One caution: Promise.all rejects as soon as any call fails, so wrap calls whose failure should not sink the page in their own error handling, or use Promise.allSettled when partial results are better than none.
03. Step 2: Stream the slow panel
Concurrency fixed the fast sections, but Promise.all still holds the whole page hostage to the slowest call: even after the fix, first paint waits two seconds for the risk feed. Streaming removes that wait from the critical path. The page renders the shell and the fast sections, wraps the slow panel in <Suspense> with a fallback, and the server flushes the panel's HTML whenever the API answers. The key is where the slow fetch happens: inside the suspended component. Awaiting the risk feed in the page above the boundary would block the shell again.
export default async function DashboardPage() {
const session = await getSession();
if (!session) return <p>Please sign in to view your portfolio.</p>;
const portfolio = await getPortfolio(session.user); // fast, ships in the shell
return (
<main>
<h1>Portfolio for {session.user}</h1>
<p>Total value: {portfolio.total}</p>
<Suspense fallback={<p role="status">Loading risk data…</p>}>
<RiskPanel user={session.user} />
</Suspense>
</main>
);
}
async function RiskPanel({ user }: { user: string }) {
const rows = await getRiskFeed(user); // slow fetch lives here
return <section aria-labelledby="risk-heading">{/* table of rows */}</section>;
}[ 168 ms] shell:yes fallback:yes panel:no
[ 169 ms] shell:yes fallback:yes panel:no
[2150 ms] shell:no fallback:no panel:yes
[2152 ms] shell:no fallback:no panel:yes
[2154 ms] shell:no fallback:no panel:no
[2155 ms] doneThis is the lab's own measuring script, which prints one line per chunk of the response. The first chunks arrive as soon as the shell is rendered and contain the heading and the fallback; the panel's HTML arrives about two seconds later and the browser swaps it into the gap. Under the HTML, the server also streams the React Server Component payload — the serialised component tree — and fills in the suspended slots as they resolve. You can see a minimal version of that payload without Next. In an empty folder, run npm init -y and npm install [email protected] [email protected] (npm adds the react-dom and webpack peer packages), save the script below as flight.mjs, and run it with React's server build: NODE_ENV=production node --conditions react-server flight.mjs. The react-server condition selects the server-only entry points, and production mode leaves out the debug rows that development adds.
// Render a tiny Server Component tree to the RSC payload and print it.
import { createElement as h } from 'react';
import { renderToPipeableStream } from 'react-server-dom-webpack/server';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function Greeting() {
await sleep(50); // a fast query
return h('p', null, 'Signed in as Amara (pro)');
}
async function Holdings() {
await sleep(300); // a slower query
return h('p', null, 'AAPL 42% · NVDA 33%');
}
const tree = h('div', null, h('h1', null, 'Portfolio'), h(Greeting), h(Holdings));
renderToPipeableStream(tree).pipe(process.stdout);0:["$","div",null,{"children":[["$","h1",null,{"children":"Portfolio"}],"$L1","$L2"]}]
1:["$","p",null,{"children":"Signed in as Amara (pro)"}]
2:["$","p",null,{"children":"AAPL 42% · NVDA 33%"}]Row 0 is the page tree, sent as soon as the synchronous part is rendered; the $L1 and $L2 slots say "an async component is still working". Row 1 (the greeting, after its 50 ms wait) and row 2 (the holdings, after 300 ms) are written when their data resolves, so with these delays row 1 arrives before row 2. This is the format Next.js streams alongside the HTML and uses to hydrate the page without re-fetching what the server already knows.
04. Step 3: Cache on purpose
Caching has two different layers, and they solve different problems.
Within one request, several components may ask for the same data: the layout reads the session and the page reads it again. React's cache() wraps a function so that repeated calls with the same arguments in one request share one execution and one result. It costs nothing across requests and cannot leak between users, because its scope ends with the request.
Across requests, rendering the same public data per visitor is waste. The current Next.js model is the use cache directive: mark a data function or a component, give the entry a lifetime with cacheLife, and tag it with cacheTag so it can be invalidated precisely. In projects that have not adopted Cache Components, the older tools do the same job: fetch(url, { next: { revalidate: 3600 } }) for time-based revalidation, or export const revalidate = 3600 for a whole route. Either way, time-based revalidation is stale-while-revalidate: after the window passes, the next request is served the cached copy and refreshes it in the background.
import { cache } from 'react';
import { cacheLife, cacheTag } from 'next/cache';
// Per request: one database hit however many components ask.
export const getSessionUser = cache(async () => {
/* read the session cookie, load the user */
});
// Across requests: public catalogue data with a tag for invalidation.
export async function getProductList() {
'use cache';
cacheLife('minutes');
cacheTag('products');
return db.query('SELECT id, name, price FROM products');
}When the underlying data changes, refresh on demand instead of waiting out the window. From a Route Handler (which a background job or a CMS webhook can call), call revalidateTag('products', 'max') to mark tagged entries stale (stale-while-revalidate), or call updateTag('products') inside a Server Action when the user must see their own write immediately (read-your-writes). revalidatePath('/catalogue') invalidates everything a route used, which is blunter but useful when you cannot name the tags.
05. Check your understanding
06. Apply it
Return to the route list from the first lesson's apply section. For each request-time route, write down its data calls, mark which are independent and which depend on earlier results, and group the independent ones with Promise.all, keeping sequential awaits only for calls that need an earlier result. Identify the slowest call in each route and say whether it belongs inside a Suspense boundary. Finally, pick one piece of public data and decide its caching: a use cache (or revalidate) window, a tag name, and the action that would call revalidateTag when the data changes.
07. Review prompt
Without looking back, explain the difference between React's cache() and a use cache lifetime, and say which one could ever leak data between users. Then describe what a visitor sees, byte by byte, in the first 100 milliseconds of a streamed page with one fast and one slow panel, and state exactly where the slow fetch must live for that to work.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.