Codegen
Codegen is a plugin system for generating code based on your API. It traverses your router and serializes each procedure's input and output into a parseable format. Right now, the only plugin available is Zod output middleware.
Zod output middleware
This plugin generates Zod output schemas to validate the values you return at runtime match the procedure's inferred return type. This makes sure you cannot return any other data than expected and prevent leaking sensistive information or breaking your API.
To start, add the plugin to your config:
// trpc.config.ts
import { defineConfig } from "trpc-tools";
import { zodOutputMiddlewarePlugin } from "trpc-tools/codegen";
import type { AppRouter } from "~/server/routers/_app"; // <--- you may have to change this path
export default defineConfig({
router: {} as AppRouter,
codegen: {
plugins: [zodOutputMiddlewarePlugin()],
},
});// trpc.config.ts
import { defineConfig } from "trpc-tools";
import { zodOutputMiddlewarePlugin } from "trpc-tools/codegen";
import type { AppRouter } from "~/server/routers/_app"; // <--- you may have to change this path
export default defineConfig({
router: {} as AppRouter,
codegen: {
plugins: [zodOutputMiddlewarePlugin()],
},
});Then, use the command:
trpc codegentrpc codegenThis will generate a file called middleware.ts in the trpc directory. You can then import the middleware and use it in your base procedure:
import { initTRPC, TRPCError } from "@trpc/server";
import { AppRouter } from "server/routers/app";
import { snapshotMiddleware } from "./trpc/middleware";
const publicProcedure = t.procedure.use(snapshotMiddleware);import { initTRPC, TRPCError } from "@trpc/server";
import { AppRouter } from "server/routers/app";
import { snapshotMiddleware } from "./trpc/middleware";
const publicProcedure = t.procedure.use(snapshotMiddleware);