Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 72 ยท Data Fetching and Caching

Fetching Data in Server Components

Fetch data in Next.js Server Components with async/await, fetch and direct database calls, avoid request waterfalls with Promise.all, and learn request memoization.

In a classic React app, fetching data means an effect, a state variable, a loading flag and an error flag, all inside a component that runs in the browser. Server Components remove most of that. A Server Component can be an async function, so it can simply wait for its data and return the finished UI. The browser never sees the fetch, the query or the keys that were used.

This lesson covers the everyday patterns: async/await in a component, where the data can come from, how to read params, why sequential awaits slow a page down, how to run requests in parallel, and what request memoization does when several components ask for the same thing. Caching across requests is a bigger topic, and it has its own lessons that start with Caching in Next.js: the Big Picture.

Real Next.js cannot run on this site, so Next.js code is shown read-only. The two runnable examples are plain Node.js stand-ins: one measures sequential versus parallel waiting, the other models request memoization.

The simplest case: an async component

A page in the App Router is a function exported from page.tsx. If it is a Server Component (the default), it may be async:

TSX
// app/posts/page.tsx  (real Next.js, read-only)
type Post = { id: number; title: string };

export default async function PostsPage() {
  const response = await fetch('https://api.example.com/posts');
  if (!response.ok) {
    throw new Error('Could not load posts');
  }
  const posts: Post[] = await response.json();

  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

There is no useEffect, no useState and no loading flag inside the component. The server waits for fetch, renders the list and sends the result. If you need a reminder of how the same task looks in the browser, compare it with Data Fetching in React.

Two details are worth knowing from the start. A thrown error is caught by the nearest error.tsx boundary, and while the data is loading, the nearest loading.tsx or <Suspense> fallback is shown. Both are covered in loading.tsx, error.tsx and not-found.tsx.

Where the data can come from

Because the code runs on the server, you are not limited to HTTP APIs. A Server Component can read from any source your server can reach:

TSX
// app/dashboard/page.tsx  (real Next.js, read-only)
import { db } from '@/lib/db'; // an ORM client such as Prisma or Drizzle
import { readFile } from 'node:fs/promises';

export default async function Dashboard() {
  const orders = await db.order.findMany({ take: 10, orderBy: { createdAt: 'desc' } });
  const notice = await readFile('content/notice.txt', 'utf8');

  return (
    <section>
      <p>{notice}</p>
      <p>{orders.length} recent orders</p>
    </section>
  );
}

Database queries, the file system, a CMS SDK, a private internal service and environment secrets are all fair game. None of that code is sent to the browser. Only the rendered result is, which you saw in Inside the RSC Payload.

In a larger app, wrap queries in functions inside a data layer instead of scattering db calls through pages. Data Access Layers and ORMs shows how.

A Server Component can reach your database, so anything you render from it is visible to the user. Never pass a whole database row to a Client Component or print it into the page without choosing the fields first. Password hashes and internal flags travel in the payload like any other prop.

Reading params

Dynamic routes give the page its params, and search forms give it searchParams. In Next.js 15 and 16 both are Promises, so you read them with await:

TSX
// app/posts/[id]/page.tsx  (real Next.js, read-only)
export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const response = await fetch(`https://api.example.com/posts/${id}`);
  const post = await response.json();

  return <h1>{post.title}</h1>;
}

Earlier versions passed plain objects. The change lets Next.js start work before it knows which parts of the request you will read. You will meet it again in Dynamic Routes.

Sequential versus parallel fetching

await pauses the function. If you write several awaits in a row, each request waits for the one before it to finish, even when they have nothing to do with each other. This is called a request waterfall, and it is the most common reason a server-rendered page is slow.

Waterfall

One after another Each await waits for the previous one.
Time adds up Total is the sum of all requests.

Fine only when a request needs the previous result.

1 / 3

A request depends on another only when it needs its result. Fetching a user's posts needs the user's id, so that pair is a chain. Weather and badges need nothing, so they should start right away. Here is the shape of the fix:

TSX
// real Next.js, read-only
export default async function Page() {
  // Start independent work immediately: promises, not results.
  const weatherPromise = getWeather();
  const badgesPromise = getBadges();

  const user = await getUser();
  const posts = await getPosts(user.id); // a real dependency

  const [weather, badges] = await Promise.all([weatherPromise, badgesPromise]);
  // render with user, posts, weather, badges
}

The stand-in below measures both versions with simulated requests that take 200, 300, 400 and 300 ms. Because setTimeout is only roughly exact, the timings are rounded down to a 100 ms step. Run it, then try changing which function starts first.

Node.js Waterfall versus parallel fetching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both functions return the same data. The first takes about 1,200 ms because it adds all four delays, and the second about 500 ms, because the longest chain (user, then posts) takes 200 + 300 ms and everything else fits inside that window.

If a page has parts that are naturally independent, you can go further and split them into separate components, each wrapped in <Suspense>, so each one streams in when its own data is ready. That is the subject of Streaming with Suspense.

Request memoization

Real components often need the same data in several places. A layout wants the current user for the header, the page wants the user's name in a greeting, and generateMetadata wants it for the title. Passing the user down through props would be awkward, so each component just calls the function it needs.

Next.js (through React) makes this cheap. During one request, identical fetch calls with the GET method, the same URL and the same options are memoized: the network call happens once, and every caller receives the same result. This is called request memoization. It lasts for that render pass only. The next request starts with an empty memo, and it is not a persistent cache across users.

For things that are not fetch, such as a database query, React provides cache(), which wraps any function with the same per-request memo. Data Access Layers and ORMs uses it.

The stand-in builds a memo scope per request, the way React does. Three components ask for the same user and only one "network" call is made. A POST is never shared, and a second request starts fresh.

Node.js Request memoization in miniature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In each request, Header, Greeting and Sidebar all report the same call number, because they shared one promise. The two POST calls were sent separately. The second request has its own list of calls, so nothing leaked from the first.

Because components can fetch for themselves, prefer fetching where the data is used over passing data down many levels. Memoization makes the duplicate calls free, and each component stays self-contained.

A few rules of thumb

  • Do not fetch your own Route Handlers from a Server Component. Calling fetch('/api/posts') from the server goes out over HTTP to your own app. Import and call the function that the handler uses instead. Route Handlers explains when handlers are the right tool.
  • Fetch in the component that needs the data. Do not hoist everything to the page just to pass it down.
  • Await only what you need now. If a part of the page can show a fallback, move its data into a child component under <Suspense>.
  • Check response.ok. fetch does not throw for a 404 or 500 response. Throw yourself, or call notFound() for a missing resource.
  • Keep secrets in the server code. Reading process.env.SECRET_KEY is safe here. Keeping Server Code on the Server explains the guards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Server Component be declared async while a Client Component cannot?

    A Server Component's output is produced on the server, which can wait for any async work before sending the result. Client Components re-render in the browser and cannot suspend that way.
  2. 2. A page awaits getUser(), then getWeather(), then getBadges(), none depending on each other. What is the best fix?

    Independent requests should be started together. The total time is then the slowest request instead of the sum of all of them.
  3. 3. What does request memoization do?

    Memoization is per request and per render pass. Identical GET fetches share one promise, and the next request starts with an empty memo.
  4. 4. A Server Component needs data that your own app also exposes at /api/posts. What should it do?

    On the server there is no need to go through HTTP to reach your own code. Import the data function and call it, which is faster and avoids a relative URL that does not work on the server anyway.

Summary

  • Server Components can be async and simply await their data. There are no effects or loading flags inside the component.
  • Data can come from fetch, a database or ORM, the file system or any server-side SDK, and it never reaches the browser unless you render it.
  • In Next.js 15 and 16, params and searchParams are Promises that you await.
  • Sequential awaits create waterfalls. Start independent requests together and use Promise.all; await dependent ones in order.
  • Identical GET fetch calls within one request are memoized, and cache() does the same for non-fetch functions.
  • Do not fetch your own Route Handlers from the server; call the shared function.

Next, see the other side of the boundary in Fetching Data on the Client.