0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Урок

Получение данных в RSC

Научитесь эффективно получать данные непосредственно в серверных компонентах, чтобы уменьшить размер пакетов JavaScript на стороне клиента

«Получение данных в RSC» — бесплатный урок Next.js 15 Fullstack (App Router + Server Actions) на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack (App Router + Server Actions), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack (App Router + Server Actions) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Fetch Data on the Server?

Welcome to data fetching in Next.js Server Components! Traditionally, data fetching often happened on the client-side, leading to heavier JavaScript bundles.

Server Components (RSCs) change this by allowing you to fetch data directly on the server, before any JavaScript is sent to the browser.

How Server Components Fetch Data

In a Server Component, you can use standard JavaScript async/await syntax with the native fetch API to get data.

  • No need for client-side hooks like useEffect.
  • Data fetching runs entirely on the server.
  • The fetched data is rendered into HTML.

A Basic Data Fetch Scenario

Imagine fetching a list of products or user profiles. In a Next.js Server Component, your component function can be marked as async, allowing you to await the result of a fetch call.

This means your component receives the data before it's even sent to the browser for rendering.

Runnable Fetch Example

Here's a simplified Node.js example demonstrating how fetch works with async/await, similar to how it would operate within a Next.js Server Component.

Run it to see how data is retrieved from an external API.

async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log("Fetched data:", data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

// In a Next.js Server Component, this would be called
// directly inside your async component function.
fetchData();

The Role of `await` in RSCs

When you await a fetch call in an RSC, the server pauses rendering that part of the component until the data arrives. Once the data is ready, the component continues rendering.

This ensures the initial HTML sent to the client already contains all the necessary data, improving perceived load times.

Keeping Server-Side Secrets

One major advantage of fetching data in Server Components is that server-only logic, like database queries or API keys, never leaves the server.

This significantly enhances security, as sensitive information is not exposed to the client's browser.

Leaner Client Bundles

By fetching data on the server, the client doesn't need to download extra JavaScript bundles for data fetching libraries or complex data hydration logic.

This results in:

  • Faster initial page loads.
  • Less JavaScript for the browser to parse and execute.
  • Improved performance, especially on slower networks.

Common Data Sources for RSCs

Server Components can fetch data from various sources:

  • External APIs: Using fetch for REST or GraphQL endpoints.
  • Databases: Directly querying a database (e.g., with Prisma client).
  • File System: Reading local files (e.g., Markdown content).

The key is that these operations happen on the server.

Check Your Understanding

Which of the following is a primary benefit of fetching data directly within Next.js Server Components?

Data Fetching in RSCs Recap

In this lesson, we explored how to fetch data efficiently using Next.js Server Components.

  • RSCs use async/await and fetch to get data on the server.
  • This keeps sensitive logic server-side and reduces client-side JavaScript.
  • The result is faster initial page loads and improved security.

Next, we'll look at interactivity with Client Components!

Часто задаваемые вопросы

Урок «Получение данных в RSC» бесплатный?

Да — полный текст урока «Получение данных в RSC» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack (App Router + Server Actions), подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack (App Router + Server Actions) содержит 4 уроков всего.

Чему я научусь в уроке «Получение данных в RSC»?

Научитесь эффективно получать данные непосредственно в серверных компонентах, чтобы уменьшить размер пакетов JavaScript на стороне клиента Ты практикуешь Next.js 15 Fullstack (App Router + Server Actions) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack (App Router + Server Actions)?

Предыдущий опыт не требуется. Next.js 15 Fullstack (App Router + Server Actions) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Получение данных в RSC»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack (App Router + Server Actions)?

Да. Каждый урок Next.js 15 Fullstack (App Router + Server Actions) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Понимание RSC и RCC
  2. Получение данных в RSC
  3. Интерактивность с RCC
  4. Шаблоны композиции серверных и клиентских компонентов
← Назад к Next.js 15 Fullstack (App Router + Server Actions)