0Pricing
tRPC End-to-End Type Safe APIs · Урок

tRPC с маршрутизатором приложений Next.js

Без лишних сложностей интегрируйте tRPC в маршрутизатор приложений Next.js, используя серверные компоненты для эффективного получения данных.

«tRPC с маршрутизатором приложений Next.js» — бесплатный урок tRPC End-to-End Type Safe APIs на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения tRPC End-to-End Type Safe APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс tRPC End-to-End Type Safe APIs содержит 4 уроков всего.

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

tRPC & Next.js App Router

Welcome to a new era of web development with the Next.js App Router! This lesson will guide you through integrating tRPC into this powerful architecture.

The App Router introduces new paradigms like Server Components and Client Components. tRPC helps you maintain end-to-end type safety across these different rendering environments.

Understanding App Router Basics

Before diving into tRPC, let's quickly recap the App Router's core concepts:

  • Server Components: Rendered on the server, ideal for data fetching and static content. They don't have state or interactivity.
  • Client Components: Rendered on the client, enabling interactivity, state, and browser APIs. They are marked with 'use client';.

tRPC plays a key role in making data fetching type-safe, regardless of whether you're in a Server or Client Component.

The tRPC App Router Adapter

To integrate tRPC with the Next.js App Router, you'll use the @trpc/next/app-router adapter. This package provides utilities specifically designed for this environment.

It handles the nuances of calling tRPC procedures from both Server Components (direct calls) and Client Components (via React Query hooks).

Server-side tRPC Setup

First, you need to expose your tRPC API routes within the app directory. This typically involves creating a route.ts file (e.g., app/api/trpc/[trpc]/route.ts).

The adapter helps configure your tRPC server to work seamlessly with Next.js API routes, handling incoming requests and routing them to your tRPC procedures.

Data Fetching in Server Components

One of the biggest advantages of the App Router is fetching data directly in Server Components. With tRPC, this means you can call your backend procedures without any client-side JavaScript.

You'll create a special server-side tRPC client that allows you to call procedures directly, similar to calling a function, all while maintaining type safety.

Server Component Fetching Demo

Here's how you can fetch data using tRPC directly inside a Next.js Server Component (e.g., app/page.tsx). Notice there are no hooks used here.

// app/page.tsx (Server Component)
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '@/server/routers/_app'; // Your backend router type

// Create a server-side tRPC client for direct usage
const serverClient = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: 'http://localhost:3000/api/trpc', // Your tRPC API endpoint
    }),
  ],
});

export default async function HomePage() {
  // Fetch data directly in a Server Component
  const greeting = await serverClient.example.hello.query({
    text: 'from Server Component!'
  });

  return (
    <div>
      <h1>{greeting}</h1>
      <p>This content is rendered on the server.</p>
    </div>
  );
}

Client-side tRPC Setup

For Client Components, you'll still need to set up a client-side tRPC provider. This is typically done in your root layout (e.g., app/layout.tsx) by wrapping your app with a 'use client'; component that provides the tRPC client.

This provider makes tRPC's React Query hooks available to all Client Components.

Data Fetching in Client Components

Inside a Client Component, you'll use tRPC's React Query hooks (like useQuery for fetching or useMutation for modifying data) just as you would in a traditional React app.

Remember to mark your component with 'use client'; at the top of the file to ensure it runs on the client.

Client Component Fetching Demo

This example shows a Client Component (e.g., app/client-page/page.tsx) fetching data using tRPC's useQuery hook. This component would be rendered client-side.

// app/client-page/page.tsx (Client Component)
'use client'; // Mark as a Client Component

import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '@/server/routers/_app'; // Your backend router type

// Initialize tRPC client for React hooks
const trpc = createTRPCReact<AppRouter>();

export default function ClientPage() {
  // Use tRPC hooks to fetch data on the client
  const { data, isLoading, error } = trpc.example.hello.useQuery({
    text: 'from Client Component!'
  });

  if (isLoading) return <p>Loading client data...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>{data}</h1>
      <p>This data was fetched client-side with React Query.</p>
    </div>
  );
}

Choosing Server vs. Client Fetching

When should you fetch data in a Server Component versus a Client Component?

  • Server Components: Ideal for initial data loads, static content, and data that doesn't need client-side re-fetching or interactivity. Reduces client bundle size.
  • Client Components: Necessary for interactive features, real-time updates, and data that changes based on user input. Utilizes React Query's caching and re-fetching benefits.

Often, a hybrid approach yields the best performance and user experience.

Quick Check: App Router Fetching

You want to fetch initial, non-interactive data for a blog post directly on the server to improve page load performance. Which component type and tRPC usage pattern would be most appropriate?

Recap: tRPC in App Router

Great job! You've learned how to integrate tRPC with the Next.js App Router.

  • tRPC provides end-to-end type safety for both Server Components and Client Components.
  • Use a server-side tRPC client for direct data fetching in Server Components.
  • Use React Query hooks (via a client-side provider) for interactive data fetching in Client Components.
  • Choosing between server and client fetching depends on your performance and interactivity needs.

This hybrid approach allows you to build robust, type-safe Next.js applications!

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

Урок «tRPC с маршрутизатором приложений Next.js» бесплатный?

Да — полный текст урока «tRPC с маршрутизатором приложений Next.js» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс tRPC End-to-End Type Safe APIs, подпишись на CoddyKit PRO. Курс tRPC End-to-End Type Safe APIs содержит 4 уроков всего.

Чему я научусь в уроке «tRPC с маршрутизатором приложений Next.js»?

Без лишних сложностей интегрируйте tRPC в маршрутизатор приложений Next.js, используя серверные компоненты для эффективного получения данных. Ты практикуешь tRPC End-to-End Type Safe APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать tRPC End-to-End Type Safe APIs?

Предыдущий опыт не требуется. tRPC End-to-End Type Safe APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «tRPC с маршрутизатором приложений Next.js»?

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

Можно ли писать и запускать код в этом уроке tRPC End-to-End Type Safe APIs?

Да. Каждый урок tRPC End-to-End Type Safe APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

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

  1. tRPC с маршрутизатором приложений Next.js
  2. Расширенная интеграция React Query
  3. Серверные компоненты и получение данных tRPC
  4. Оптимистичные обновления с мутациями tRPC
← Назад к tRPC End-to-End Type Safe APIs