🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Fetch Data in a Server Component

A Server Component can fetch its own data. It waits for the data, then sends the finished page.

The book page reads its book

The page awaits the route params, then reads the book. A missing book shows the not-found page.

import { getBook, getBooks } from "@/lib/books";
import { notFound } from "next/navigation";

export default async function BookPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const book = getBook(id);
  if (!book) notFound();
  return (
    <main>
      <h1>{book.title}</h1>
      <p>by {book.author} ({book.year})</p>
      <p>{book.read ? "Finished" : "Still reading"}</p>
    </main>
  );
}

The store the page reads

The store reads the books file. Five books live in it.

export function getBooks(): Book[] {
  const raw = readFileSync(join(process.cwd(), "data", "books.json"), "utf8");
  return JSON.parse(raw) as Book[];
}

export function getBook(id: string): Book | undefined {
  return getBooks().find((book) => book.id === id);
}

Example

curl -s http://localhost:3111/books/dune | grep -o '<h1>Dune</h1>'

Key points

  • Fetch: asking a source for data, and waiting for the answer
  • A Server Component fetches with await. The page waits, then renders.
  • No useEffect is needed. The fetch runs on the server, before the page is sent.
  • No loading state is needed in the page. The server holds the page until the data is ready.
  • The book page reads one book from the store. The store is a file on the server.

In this example, the check asks the server for the Dune page. The page is a Server Component, so it reads the book on the server and sends the finished page. The heading Dune is in the answer, with Frank Herbert and Finished beside it. No JavaScript fetch ran in the browser. The server did the reading, and the browser only showed the result.

Note

Fetch on the server when the page needs the data to render. Fetch in the browser only when the data changes after the page loads.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

Where does a Server Component fetch its data?