0Pricing
tRPC End-to-End Type Safe APIs · 강의

tRPC 절차에 Zod 연동

tRPC 쿼리와 변형의 입력에 Zod 스키마를 직접 적용하여 자동 검증을 구현합니다.

tRPC 절차에 Zod 연동은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Zod for tRPC Inputs

Welcome! In this lesson, we'll learn how to integrate Zod schemas directly into your tRPC procedures. This powerful combination ensures your API inputs are always valid and type-safe from end-to-end.

You'll see how to apply Zod for both query and mutation procedures, making your backend more robust and developer-friendly.

Why Validate Inputs?

Input validation is a critical part of building secure and reliable APIs. It's like a quality check at the entrance of your backend.

  • Security: Prevents malicious or malformed data from reaching your server logic.
  • Data Integrity: Ensures your database only stores valid and expected data formats.
  • Predictability: Your backend logic can trust the shape of incoming data, reducing runtime errors.
  • Better DX: Developers get immediate feedback on incorrect inputs.

The `.input()` Method

tRPC makes integrating Zod incredibly simple. Each tRPC procedure (query, mutation, or subscription) has an .input() method.

This method accepts a Zod schema, which tRPC then uses to automatically validate any incoming data for that procedure. If the input doesn't match the schema, tRPC handles the error for you!

Query Input Validation

For queries, you often expect parameters like an ID or a search term. Zod helps ensure these inputs are of the correct type and format.

Let's look at an example where we want to fetch a user by their unique ID. We'll use Zod to ensure the userId is a valid UUID string.

Query Procedure Example

Here's how you define a tRPC query procedure that uses a Zod schema to validate its input:

import { initTRPC } from '@trpc/server';
import { z } from 'zod';

// Minimal tRPC context setup
const t = initTRPC.create();

// Define a query procedure with Zod input validation
const getUserById = t.procedure
  .input(z.object({
    userId: z.string().uuid("Invalid user ID format"),
  }))
  .query(({ input }) => {
    // In a real app, this would fetch from a database
    console.log(`Fetching user: ${input.userId}`);
    return { id: input.userId, name: "Alice" }; // Mock data
  });

// To use this, you'd add it to a tRPC router, e.g.:
// export const appRouter = t.router({ getUserById });

Mutation Input Validation

Mutations often involve creating or updating data, which means they typically accept more complex input objects. Zod is perfect for validating these structures.

Consider a scenario where you want to create a new blog post. We'll validate its title and optional content to ensure they meet certain criteria.

Mutation Procedure Example

Here's a mutation procedure that validates input for creating a new post using a Zod object schema:

import { initTRPC } from '@trpc/server';
import { z } from 'zod';

// Minimal tRPC context setup
const t = initTRPC.create();

// Define a mutation procedure with Zod input validation
const createPost = t.procedure
  .input(z.object({
    title: z.string().min(5, "Title must be at least 5 characters"),
    content: z.string().optional(),
    authorId: z.string().uuid("Invalid author ID"),
  }))
  .mutation(({ input }) => {
    // This would typically save data to a database
    console.log(`Creating post: "${input.title}" by ${input.authorId}`);
    return { id: "new-post-uuid", ...input, createdAt: new Date() }; // Mock
  });

// To use this, you'd add it to a tRPC router, e.g.:
// export const appRouter = t.router({ createPost });

Automatic Validation Errors

One of the biggest advantages of integrating Zod directly with tRPC is automatic error handling.

  • If a client sends input that doesn't match your Zod schema, tRPC will automatically catch the validation error.
  • It then sends a standardized BAD_REQUEST error response to the client, including details about why the validation failed.
  • This means you don't need to write manual try/catch blocks for basic input validation!

Benefits of Direct Integration

Combining Zod with tRPC's .input() method provides several powerful benefits:

  • End-to-End Type Safety: Your Zod schema defines the exact input type, which tRPC automatically infers and shares with your client.
  • Single Source of Truth: Define validation rules once, and they apply on both the server (runtime) and client (compile-time).
  • Reduced Boilerplate: No need for manual validation checks or separate DTOs (Data Transfer Objects).
  • Clear API Contracts: Your procedures clearly state their input requirements through their Zod schemas.

Quick Check: Zod in tRPC

You've learned how Zod schemas are integrated into tRPC procedures. Let's test your understanding!

Recap: Zod & tRPC Synergy

Great job! You've successfully learned how to integrate Zod schemas into your tRPC procedures.

  • We saw that the .input() method is key for applying Zod schemas to both queries and mutations.
  • This integration provides automatic validation, end-to-end type safety, and clear API contracts.
  • By leveraging Zod within tRPC, you build more robust, secure, and developer-friendly APIs with less effort.

Next up, we'll explore more advanced Zod schemas!

자주 묻는 질문

“tRPC 절차에 Zod 연동” 강의는 무료인가요?

네 — “tRPC 절차에 Zod 연동” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“tRPC 절차에 Zod 연동”에서 뭘 배우나요?

tRPC 쿼리와 변형의 입력에 Zod 스키마를 직접 적용하여 자동 검증을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“tRPC 절차에 Zod 연동” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Zod 스키마 소개
  2. 복잡한 Zod 스키마 정의
  3. tRPC 절차에 Zod 연동
  4. Zod 데이터 변환과 세부 검증
← tRPC End-to-End Type Safe APIs(으)로 돌아가기