tRPC is a TypeScript RPC framework that infers API types end-to-end — the server’s procedure types become the client’s call types without code generation. UUID v7 fits tRPC’s model well: Zod schemas validate UUID inputs, server procedures generate IDs without client exposure, and branded types enforce UUID version correctness across the type boundary. See TypeScript UUID Types for the branded type pattern.
Setup
npm install @trpc/server @trpc/client @trpc/react-query zod uuid
npm install --save-dev @types/uuid
Zod UUID schema validation
// server/trpc.ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
// Reusable UUID v7 Zod schema
const uuidV7Schema = z.string()
.uuid('Must be a valid UUID')
.refine(s => s.charAt(14) === '7', { message: 'Must be UUID v7' });
export { t, uuidV7Schema };
tRPC router with UUID v7 procedures
// server/routers/orders.ts
import { t, uuidV7Schema } from '../trpc';
import { z } from 'zod';
import { v7 as uuidv7 } from 'uuid';
import { db } from '../db';
export const ordersRouter = t.router({
// Mutation: create order — UUID v7 generated server-side
create: t.procedure
.input(z.object({
customerId: z.string().uuid(),
total: z.number().positive(),
}))
.mutation(async ({ input }) => {
const order = await db.order.create({
data: {
id: uuidv7(), // server-side UUID v7 — never reaches client bundle
customerId: input.customerId,
total: input.total,
},
});
return order; // id is UUID v7 in the response
}),
// Query: get order by UUID v7 ID
getById: t.procedure
.input(z.object({ id: uuidV7Schema }))
.query(async ({ input }) => {
return db.order.findUniqueOrThrow({ where: { id: input.id } });
}),
// Query: paginated list with UUID v7 cursor
list: t.procedure
.input(z.object({
cursor: z.string().uuid().optional(),
limit: z.number().int().min(1).max(100).default(20),
}))
.query(async ({ input }) => {
const orders = await db.order.findMany({
where: input.cursor ? { id: { gt: input.cursor } } : undefined,
orderBy: { id: 'asc' },
take: input.limit,
});
const nextCursor = orders.length === input.limit
? orders[orders.length - 1].id
: null;
return { orders, nextCursor };
}),
});
Branded UUID types for compile-time safety
// types/ids.ts
export type OrderId = string & { readonly _brand: 'OrderId' };
export type CustomerId = string & { readonly _brand: 'CustomerId' };
export function orderId(s: string): OrderId {
return s as OrderId;
}
export function customerId(s: string): CustomerId {
return s as CustomerId;
}
// server/routers/orders.ts — branded output
import { orderId, OrderId } from '../types/ids';
import { v7 as uuidv7 } from 'uuid';
create: t.procedure
.mutation(async (): Promise<{ id: OrderId }> => {
const id = orderId(uuidv7());
await db.order.create({ data: { id, ...rest } });
return { id };
}),
The branded type OrderId cannot be accidentally passed where CustomerId is expected — TypeScript catches the mismatch at compile time. See TypeScript UUID Types.
React client usage
// app/orders/page.tsx
'use client';
import { trpc } from '../trpc-client';
export default function OrdersPage() {
const { data } = trpc.orders.list.useQuery({ limit: 20 });
const createOrder = trpc.orders.create.useMutation();
return (
<div>
{data?.orders.map(order => (
<div key={order.id}>{order.id}</div>
))}
<button onClick={() => createOrder.mutate({ customerId: 'user-123', total: 99.99 })}>
Create Order
</button>
</div>
);
}
The UUID v7 id on each order sorts chronologically — data.orders arrives in creation order without a separate createdAt sort. See UUID v7 for Cursor Pagination.
Further reading
- TypeScript UUID Types — branded types and validation
- UUID in Prisma — v7 Setup and Migration
- UUID v7 for Cursor Pagination
- UUID in JavaScript — full guide
External references
Frequently asked questions
How do I validate UUID inputs in tRPC procedures?
Use Zod's z.string().uuid() in your input schema. tRPC validates inputs against the Zod schema before the procedure handler runs — invalid UUID strings return a 400-equivalent error automatically. For stricter validation (UUID v7 version check), use z.string().refine(s => s.charAt(14) === '7', 'Must be UUID v7').
How do I generate UUID v7 in a tRPC mutation?
Import v7 as uuidv7 from the uuid package and call it inside the mutation handler. tRPC procedures run on the server — the uuid package is never bundled into the client. Return the generated ID in the response so the client can use it for optimistic updates or navigation.
How do I use branded UUID types in tRPC with TypeScript?
Define a branded type: type OrderId = string & \{ readonly _brand: 'OrderId' \}. Use it in your tRPC router's output type and Prisma models. This prevents accidentally passing an OrderId where a UserId is expected at compile time. See TypeScript UUID Types.