0Pricing
tRPC End-to-End Type Safe APIs · Pelajaran

Mengintegrasikan Zod dalam Prosedur tRPC

Terapkan skema Zod langsung pada masukan kueri dan mutasi tRPC Anda untuk validasi otomatis.

Mengintegrasikan Zod dalam Prosedur tRPC adalah pelajaran tRPC End-to-End Type Safe APIs gratis di CoddyKit. Ini adalah pelajaran 3 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar tRPC End-to-End Type Safe APIs, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus tRPC End-to-End Type Safe APIs mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

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!

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Mengintegrasikan Zod dalam Prosedur tRPC” gratis?

Ya — teks lengkap “Mengintegrasikan Zod dalam Prosedur tRPC” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus tRPC End-to-End Type Safe APIs, upgrade ke CoddyKit PRO. Kursus tRPC End-to-End Type Safe APIs mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Mengintegrasikan Zod dalam Prosedur tRPC”?

Terapkan skema Zod langsung pada masukan kueri dan mutasi tRPC Anda untuk validasi otomatis. Kamu berlatih tRPC End-to-End Type Safe APIs dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai tRPC End-to-End Type Safe APIs?

Tidak diperlukan pengalaman sebelumnya. tRPC End-to-End Type Safe APIs di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 3 dari 4.

Berapa lama pelajaran “Mengintegrasikan Zod dalam Prosedur tRPC” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran tRPC End-to-End Type Safe APIs ini?

Ya. Setiap pelajaran tRPC End-to-End Type Safe APIs menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Pengantar Skema Zod
  2. Menentukan Skema Zod yang Kompleks
  3. Mengintegrasikan Zod dalam Prosedur tRPC
  4. Mentransformasi dan Menyempurnakan Data Zod
← Kembali ke tRPC End-to-End Type Safe APIs