validators
Configure input and output validation with .input() and .output() using Zod, Yup, Superstruct, ArkType, Valibot, Effect, or custom validator functions. Chain multiple .input() calls to merge object schemas. Standard Schema protocol support. Output validation returns INTERNAL_SERVER_ERROR on failure.
- 0
- Installs
- —
- Rating
- —
- Success rate
- 1
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 3253915ea9edd9dc… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
tRPC -- Validators
Setup
// server/trpc.ts
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const router = t.router;
export const publicProcedure = t.procedure;
// server/appRouter.ts
import { z } from 'zod';
import { publicProcedure, router } from './trpc';
export const appRouter = router({
hello: publicProcedure
.input(z.object({ name: z.string() }))
.output(z.object({ greeting: z.string() }))
.query(({ input }) => {
return { greeting: `hello ${input.name}` };
}),
});
export type AppRouter = typeof appRouter;
Core Patterns
Input validation with Zod
import { z } from 'zod';
import { publicProcedure, router } from './trpc';
export const appRouter = router({
userById: publicProcedure.input(z.string()).query(({ input }) => {
return { id: input, name: 'Katt' };
}),
userCreate: publicProcedure
.input(z.object({ name: z.string(), email: z.string().email() }))
.mutation(({ input }) => {
return { id: '1', ...input };
}),
});
Input chaining to merge object schemas
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
const baseProcedure = t.procedure
.input(z.object({ townName: z.string() }))
.use((opts) => {
console.log(`Request from: ${opts.input.townName}`);
return opts.next();
});
export const appRouter = t.router({
hello: baseProcedure
.input(z.object({ name: z.string() }))
.query(({ input }) => {
return { greeting: `Hello ${input.name}, from ${input.townName}` };
}),
});
Multiple .input() calls merge object properties; the final input type is { townName: string; name: string }.
Output validation
import { z } from 'zod';
import { publicProcedure, router } from './trpc';
export const appRouter = router({
hello: publicProcedure
.output(z.object({ greeting: z.string() }))
.query(() => {
return { greeting: 'hello world' };
}),
});
Output validation catches mismatches between your return type and the expected shape, useful for untrusted data sources.
Custom validator function (no library)
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const appRouter = t.router({
hello: t.procedure
.input((value): string => {
if (typeof value === 'string') return value;
throw new Error('Input is not a string');
})
.output((value): string => {
if (typeof value === 'string') return value;
throw new Error('Output is not a string');
})
.query(({ input }) => {
return `hello ${input}`;
}),
});
Common Mistakes
[MEDIUM] Chaining non-object inputs
Wrong:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure.input(z.string()).input(z.number());
Correct:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure
.input(z.object({ name: z.string() }))
.input(z.object({ age: z.number() }));
Multiple .input() calls merge object properties; non-object schemas (string, number, array) cannot be merged and produce type errors.
Source: www/docs/server/validators.md
[MEDIUM] Output validation failure returns 500
Wrong:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure
.output(z.object({ id: z.string() }))
.query(() => ({ id: 123 }));
Correct:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure
.output(z.object({ id: z.string() }))
.query(() => ({ id: '123' }));
If .output() validation fails, tRPC returns INTERNAL_SERVER_ERROR (500), not BAD_REQUEST, because the server produced invalid data.
Source: www/docs/server/validators.md
[HIGH] Using cursor: z.optional() without nullable for infinite queries
Wrong:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure
.input(z.object({ cursor: z.string().optional() }))
.query(({ input }) => {
return { items: [], nextCursor: input.cursor };
});
Correct:
import { z } from 'zod';
import { publicProcedure } from './trpc';
const proc = publicProcedure
.input(z.object({ cursor: z.string().nullish() }))
.query(({ input }) => {
return { items: [], nextCursor: input.cursor };
});
React Query internally passes cursor: undefined during invalidation refetch; using .optional() without .nullable() can fail validation. Use .nullish() instead.
Source: https://github.com/trpc/trpc/issues/6862
See Also
server-setup-- initTRPC, routers, procedureserror-handling-- how validation errors surface as BAD_REQUESTerror-handling-- errorFormatter to expose Zod field errorsmiddlewares-- use input chaining with middleware base procedures
Files
1- SKILL.md
c214b1472c5.4 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from trpc/trpc8
Deploy tRPC on AWS Lambda with awsLambdaRequestHandler() from @trpc/server/adapters/aws-lambda for API Gateway v1 (REST, APIGatewayProxyEvent) and v2 (HTTP, APIGatewayProxyEventV2), and Lambda Function URLs. Enable response streaming with awsLambdaStreamingRequestHandler() wrapped in awslambda.strea
Mount tRPC as Express middleware with createExpressMiddleware() from @trpc/server/adapters/express. Access Express req/res in createContext via CreateExpressContextOptions. Mount at a path prefix like app.use('/trpc', ...). Avoid global express.json() conflicting with tRPC body parsing for FormData.
Mount tRPC as a Fastify plugin with fastifyTRPCPlugin from @trpc/server/adapters/fastify. Configure prefix, trpcOptions (router, createContext, onError). Enable WebSocket subscriptions with useWSS and @fastify/websocket. Set routerOptions.maxParamLength for batch requests. Requires Fastify v5+. Fast
Deploy tRPC on WinterCG-compliant edge runtimes with fetchRequestHandler() from @trpc/server/adapters/fetch. Supports Cloudflare Workers, Deno Deploy, Vercel Edge Runtime, Astro, Remix, SolidStart. FetchCreateContextFnOptions provides req (Request) and resHeaders (Headers) for context creation. The
Mount tRPC on Node.js built-in HTTP server with createHTTPServer() from @trpc/server/adapters/standalone, createHTTPHandler() for custom http.createServer, createHTTP2Handler() for HTTP/2 with TLS. Configure basePath to slice URL prefix, CORS via the cors npm package passed as middleware option. Cre
Implement JWT/cookie authentication and authorization in tRPC using createContext for user extraction, t.middleware with opts.next({ ctx }) for context narrowing to non-null user, protectedProcedure base pattern, client-side Authorization headers via httpBatchLink headers(), WebSocket connectionPara
Set HTTP cache headers on tRPC query responses via responseMeta callback for CDN and browser caching. Configure Cache-Control, s-maxage, stale-while-revalidate. Handle caching with batching and authenticated requests. Avoid caching mutations, errors, and authenticated responses.
Create a vanilla tRPC client with createTRPCClient<AppRouter>(), configure link chain with httpBatchLink/httpLink, dynamic headers for auth, transformer on links (not client constructor). Infer types with inferRouterInputs and inferRouterOutputs. AbortController signal support. TRPCClientError typin
Related backend skillsscan passed
PostHog integration for Django applications
Coordinate frontend/backend or service-to-service work through one authoritative machine-checkable contract (OpenAPI, AsyncAPI, Protocol Buffers, or JSON Schema), with generated consumer types and contract-verified integration. Use when parallel consumer and provider work must evolve an API or event
Report browser/API/CLI/job/worker/webhook bugs. (gstack)
This skill should be used when the user asks to "build an MCP server", "create an MCP", "make an MCP integration", "wrap an API for Claude", "expose tools to Claude", "make an MCP app", or discusses building something with the Model Context Protocol. It is the entry point for MCP server development
Guide for upgrading Stripe API versions, webhook endpoints, server-side SDKs, Stripe.js, and mobile SDKs
Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.