Intégrer Zod aux procédures tRPC
Appliquez directement des schémas Zod aux entrées de vos requêtes et mutations tRPC pour automatiser la validation.
Intégrer Zod aux procédures tRPC est une leçon tRPC End-to-End Type Safe APIs gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage tRPC End-to-End Type Safe APIs, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours tRPC End-to-End Type Safe APIs comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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!
Questions Fréquemment Posées
La leçon « Intégrer Zod aux procédures tRPC » est-elle gratuite ?
Oui — le texte complet de « Intégrer Zod aux procédures tRPC » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours tRPC End-to-End Type Safe APIs, passe à CoddyKit PRO. Le cours tRPC End-to-End Type Safe APIs comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Intégrer Zod aux procédures tRPC » ?
Appliquez directement des schémas Zod aux entrées de vos requêtes et mutations tRPC pour automatiser la validation. Tu pratiques tRPC End-to-End Type Safe APIs avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer tRPC End-to-End Type Safe APIs ?
Aucune expérience préalable n'est requise. tRPC End-to-End Type Safe APIs sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Intégrer Zod aux procédures tRPC » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon tRPC End-to-End Type Safe APIs ?
Oui. Chaque leçon tRPC End-to-End Type Safe APIs inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Introduction aux schémas Zod
- Définition de schémas Zod complexes
- Intégrer Zod aux procédures tRPC
- Transformer et affiner les données Zod