Data fetching, caching & revalidation
Fetch data in server components and choose static, dynamic or revalidated rendering.
By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.
In short
Server components can fetch data directly with async/await. Next.js then renders routes statically at build time, dynamically per request, or statically with periodic or on-demand revalidation.
Explained simply
In the App Router, a server component can simply be an async function. You await your data, from a database or an API, and return the UI. No useEffect, no loading flags for the first render.
Next.js then decides when to build that page. Some pages can be built once and served to everyone, like a pricing page. Some must be built for each visitor, like a dashboard that reads the user's cookie. Some sit in between: built once and refreshed every few minutes.
Revalidation is how cached pages get fresh again. You can say refresh at most every 60 seconds, or you can tell Next.js to refresh right now, for example after an editor publishes a new blog post.
Streaming makes slow data less painful. Wrap a slow part of the page in a Suspense boundary, and Next.js sends the rest of the page immediately, then fills in the slow part when its data arrives.
Press Play on a diagram to walk through it one step at a time.
- Rendered at build time
- Served from cache or CDN
- Fastest response
- Best for marketing and docs
- Static, refreshed on a timer
- Or via revalidatePath or revalidateTag
- Fresh enough, still fast
- Best for blogs and catalogs
- Rendered on every request
- Uses cookies, headers or live data
- Always fresh, more server work
- Best for dashboards
- 1Per-user data?
Yes: dynamic, uses cookies or a session
- 2Changes on a known event?
Yes: cache and revalidate by tag
- 3Can be a few minutes stale?
Yes: cache with revalidate seconds
- 4Never changes until deploy?
Fully static
- 5Slow parts?
Wrap them in Suspense to stream
In depth
Static or dynamic: how Next.js decides
By default, Next.js tries to render each route at build time. A route becomes dynamic, rendered per request, as soon as it uses request-time information: cookies(), headers(), searchParams, or the connection() function. Since Next.js 15, fetch requests are not cached by default either, so a route that fetches without any cache option renders fresh on every request.
You can see the result in the next build output, which marks each route as static or dynamic. You can also force a choice with route segment config: export const dynamic = "force-dynamic" or export const revalidate = 3600 in a page or layout. A dynamic route is not bad: dashboards and pages with user data should be dynamic. Just make it a deliberate choice.
- cookies(), headers(), searchParams: dynamic
- fetch with no cache option: not cached (Next.js 15+)
- fetch(url, { cache: "force-cache" }): cached
- export const revalidate = 60: refresh the route at most each minute
The caching layers
Next.js has several caches, and confusion usually comes from mixing them up. Request memoization: during one render, identical GET fetch calls run only once, so two components can fetch the same URL without a double request; for database calls, wrap the function in React's cache() to get the same effect. Data cache: stores fetch results across requests and deployments when you opt in with force-cache or revalidate. Full route cache: the rendered HTML and payload of static routes, built at build time. Router cache: in the browser, it keeps payloads of visited and prefetched routes for fast back and forward navigation.
Revalidation clears the data cache and the affected routes. After a mutation, call router.refresh() or revalidate on the server so the browser cache picks up new data too.
- 1Router cache (browser)
Visited and prefetched route payloads
- 2Full route cache (server)
Pre-rendered HTML and payload for static routes
- 3Data cache (server)
Opt-in fetch results across requests
- 4Request memoization
Dedupes identical calls in one render
- 5Data source
Your database or API
Revalidating by time or on demand
Time-based revalidation uses stale-while-revalidate. With revalidate: 60, the first visitor after 60 seconds still gets the cached page instantly, and Next.js rebuilds it in the background; the next visitor sees the fresh version. It is simple and fits content that may be a little stale.
On-demand revalidation refreshes exactly when data changes. revalidatePath("/blog") clears one route. revalidateTag("posts") clears every fetch tagged with next: { tags: ["posts"] }, across all pages that use it. Call these from server actions or route handlers, for example from a CMS webhook. In Next.js 16, revalidateTag takes a second argument for the cache profile, such as "max", and the new updateTag("posts") is meant for server actions where users must see their own change immediately.
Streaming with Suspense
Without streaming, the whole page waits for its slowest query. With a Suspense boundary around a slow component, Next.js sends the page shell and the fallback first, keeps the HTTP response open, and streams the finished component when its data arrives. React inserts it in place. loading.tsx is simply a Suspense boundary around the whole page.
Place boundaries by how users read the page: the header and main content should not wait for a recommendations widget. Start independent fetches in parallel, either in separate components inside separate Suspense boundaries, or with Promise.all, so you do not build a waterfall where each request waits for the previous one.
- Browser to Next.js server: GET /products/421GET /products/42
- Next.js server to Browser: HTML: header, product, reviews fallback2HTML: header, product, reviews fallback
- Next.js server to Reviews API: fetch reviews (slow)3fetch reviews (slow)
- Reviews API to Next.js server: reviews data4reviews data
- Next.js server to Browser: stream the reviews HTML chunk5stream the reviews HTML chunk
- 6React swaps fallback for contentBrowser to Browser: React swaps fallback for content
The newer model: Cache Components and "use cache"
Next.js 16 adds an opt-in model called Cache Components, enabled with cacheComponents: true in next.config.ts. Everything is dynamic by default, and you mark what can be cached with the "use cache" directive at the top of a function, component or file. cacheLife("hours") sets how long it lives, and cacheTag("posts") lets you revalidate it by tag. Uncached data that is slow must sit inside a Suspense boundary.
This pairs with partial prerendering: the static shell of a page is served instantly from the edge, and dynamic holes stream in. It works for database calls, not only fetch. Route segment options like dynamic and revalidate do not apply in this mode. Because caching rules changed across Next.js 13, 14, 15 and 16, always check the docs for the version in your package.json.
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Fetch data in server components~1h
- 2Choose static or dynamic rendering~1h
- 3Revalidate by time or on demand~1h
- 4Stream with Suspense boundaries~1h
- 5Understand the Next.js caching layers~1h
Key points
- Fetch in server components close to where data is used; requests are deduplicated.
- Reading cookies, headers or searchParams makes a route dynamic.
- Set next: { revalidate: 60 } on fetch to refresh cached data every minute.
- Wrap slow parts in Suspense so the rest of the page streams immediately.
- Caching defaults have changed across Next.js versions, so check the docs for yours.
Key terms
Tap a card to flip it. 0/5 known
Examples
import { Suspense } from 'react';
async function Products() {
const res = await fetch('https://api.example.com/products', { next: { revalidate: 60 } });
const products: { id: string; name: string }[] = await res.json();
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
export default function Page() {
return <Suspense fallback={<p>Loading...</p>}><Products /></Suspense>;
}Time-based revalidation with a streamed Suspense boundary.
A blog that refreshes when an editor publishes
Step 1: tag the posts fetch with "posts" and cache it. Step 2: the blog pages are now served from cache. Step 3: the CMS calls a webhook route when a post is published. Step 4: the route checks a shared secret and revalidates the tag, so every page that lists posts refreshes on the next visit. In Next.js 15, call revalidateTag("posts") with one argument instead.
// lib/posts.ts
export async function getPosts() {
const res = await fetch("https://cms.example.com/posts", {
cache: "force-cache",
next: { tags: ["posts"] },
});
return res.json();
}
// app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";
export async function POST(req: Request) {
if (req.headers.get("x-secret") !== process.env.REVALIDATE_SECRET) return new Response(null, { status: 401 });
revalidateTag("posts", "max");
return Response.json({ revalidated: true });
}Removing a waterfall
A user page awaited the profile, then the orders, then the recommendations, taking 200 + 300 + 800 ms. Step 1: start profile and orders together with Promise.all, cutting that part to 300 ms. Step 2: move recommendations into their own async component inside a Suspense boundary, so the page appears after about 300 ms and recommendations stream in later.
import { Suspense } from "react";
import { getProfile, getOrders, getRecommendations } from "@/lib/data";
async function Recommendations({ userId }: { userId: string }) {
const items = await getRecommendations(userId);
return <ul>{items.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}
export default async function Account() {
const [profile, orders] = await Promise.all([getProfile(), getOrders()]);
return (<main>
<h1>{profile.name}</h1><p>{orders.length} orders</p>
<Suspense fallback={<p>Loading picks...</p>}><Recommendations userId={profile.id} /></Suspense>
</main>);
}Quick reference
- Async server components fetch data directly; no useEffect needed
- Next.js 15+: fetch is not cached unless you pass cache: "force-cache" or next.revalidate
- cookies(), headers() and searchParams make a route dynamic
- fetch(url, { next: { tags: ["posts"] } }) then revalidateTag to refresh by tag
- revalidatePath("/blog") refreshes one route after a change
- Wrap slow components in Suspense; loading.tsx does it for a whole page
- Use Promise.all for independent requests to avoid waterfalls
- Next.js 16 opt-in: cacheComponents: true, then "use cache" with cacheLife and cacheTag
Common mistakes
- Fetching from your own route handler inside a server component instead of calling the logic directly.
- Assuming data is cached when your Next.js version does not cache fetch by default.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make a server component that fetches https://api.example.com/rates and caches the result for 10 minutes.
- Exercise 2medium
Two components on one page both need the current user from the database. Make sure only one query runs per request.
- Exercise 3hard
A product page shows details (fast), stock levels (must be live) and reviews (slow, can be an hour old). Design the data loading so the page appears quickly and each part has the right freshness.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why does my Next.js page show old data after I update the database?
- The page or its data is cached. Call revalidatePath or revalidateTag after the change, or make that data uncached if it must always be live.
- Should I fetch my own API route from a server component?
- No. It adds an extra network hop and breaks at build time. Call the same function the route handler uses directly.
- What is the difference between loading.tsx and Suspense?
- loading.tsx is a Suspense boundary around a whole route segment. A Suspense boundary you write yourself can wrap just one slow part of a page.
- Is static rendering always better?
- It is fastest, but only for data that is the same for everyone. Personalized or live data should be dynamic, with slow parts streamed.