Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Fetching and Rendering Data in Next.js | Section
Building Web Apps with Next.js

bookFetching and Rendering Data in Next.js

Sveip for å vise menyen

In real applications, pages rarely display static content. Most of the time, you need to load data from an API and show it to the user.

In Next.js, this is done directly inside Server Components. You can fetch data and render it in the same place, without using additional hooks or complex logic.

This makes data handling simpler and more efficient.

Fetching Data

Server Components can be asynchronous, which allows you to use fetch with await:

export default async function Page() {
  const res = await fetch("https://api.example.com/products");
  const products = await res.json();

  return <div>Data loaded</div>;
}

The data is fetched on the server before the page is rendered.

Rendering Data

Once the data is loaded, you can render it directly in your component:

export default async function Page() {
  const res = await fetch("https://api.example.com/products");
  const products = await res.json();

  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

The user receives a fully rendered page with data already included.

How This Works

The server runs the component first, fetches the data, and generates the HTML. The browser then receives the final result.

This means there is no need to:

  • Wait for data after page load;
  • Manage loading state in simple cases;
  • Write additional client-side logic for fetching.

Why This Approach Is Better

Fetching and rendering data on the server improves performance and simplifies your code.

The user sees content faster, and search engines can easily read the page because it is already fully rendered.

At the same time, your components stay clean because data fetching and rendering are handled in one place.

question mark

Where is data typically fetched in modern Next.js using the App Router?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 23

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 23
some-alt