Integración de Zod en procedimientos de tRPC
Aplique esquemas de Zod directamente a las entradas de sus consultas y mutaciones de tRPC para obtener una validación automática.
Integración de Zod en procedimientos de tRPC es una lección gratuita de tRPC End-to-End Type Safe APIs en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de tRPC End-to-End Type Safe APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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_REQUESTerror response to the client, including details about why the validation failed. - This means you don't need to write manual
try/catchblocks 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!
Aprende tRPC End-to-End Type Safe APIs con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 10
- Lecciones
- 40
Preguntas frecuentes
¿La lección «Integración de Zod en procedimientos de tRPC» es gratis?
Sí — el texto completo de «Integración de Zod en procedimientos de tRPC» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de tRPC End-to-End Type Safe APIs, actualiza a CoddyKit PRO. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Integración de Zod en procedimientos de tRPC»?
Aplique esquemas de Zod directamente a las entradas de sus consultas y mutaciones de tRPC para obtener una validación automática. Practicas tRPC End-to-End Type Safe APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar tRPC End-to-End Type Safe APIs?
No se requiere experiencia previa. tRPC End-to-End Type Safe APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Integración de Zod en procedimientos de tRPC»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de tRPC End-to-End Type Safe APIs?
Sí. Cada lección de tRPC End-to-End Type Safe APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a los esquemas de Zod
- Definición de esquemas complejos de Zod
- Integración de Zod en procedimientos de tRPC
- Transformación y refinamiento de datos con Zod