PortfolioHire me for one like this

Sample website by Chayangkoon

CodeSprout

Lesson 5 / 6

Lesson 5

Getting data

8 min read

So far our pages have used text typed straight into the code. Real sites show data that lives somewhere else: a list of courses from a database, prices from a shop system, or posts from a content tool. Next.js gives you three places to fetch that data, and choosing the right one is one of the most important decisions you make.

On the server, in the component

A Server Component can be an async function. That means it can wait for data before returning its HTML. You simply await the data and use it.

app/courses/page.tsx
export default async function CoursesPage() {
  const res = await fetch("https://api.example.com/courses");
  const courses: { id: string; title: string }[] = await res.json();

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

Because this code runs on the server, the visitor's browser never sees the API address or any secret keys you use, and it receives a page that already contains the list. courses.map(...) turns each item in the array into a list item, and key helps React keep track of them.

When does it run?

Here is the surprise for most beginners: the page above runs its fetch once during npm run build. Nothing in it depends on who is visiting, so Next.js renders it ahead of time and saves the finished HTML. That is fast and cheap, but the list only changes when you build again.

  • At build time (the default): good for data that is the same for everyone and changes rarely, like a course list or a menu.
  • On each request: when the data must be fresh (stock levels, a logged-in user's dashboard), tell fetch not to store the result. The Node.js server then fetches it every time someone opens the page.
  • In the browser: a Client Component can fetch after the page loads, for example when a visitor types in a search box. The page appears first, then the results fill in.
// Fetch fresh data on every request instead of once at build time
const res = await fetch("https://api.example.com/stock", { cache: "no-store" });

Showing a loading state

Slow data should not leave visitors staring at a blank screen. Add a file called loading.tsx next to your page.tsx, and Next.js shows it immediately while the page waits for its data.

app/courses/loading.tsx
export default function Loading() {
  return <p>Loading courses…</p>;
}

You now know how pages are built from routes, components and data. The last step is getting your site off your computer and onto the internet, which is what the final lesson covers.