trpc
БесплатноБез исполняемых скриптовНе проверенtRPC builds end-to-end type-safe TypeScript APIs without schemas or code generation: the server defines procedures, the client calls them with full type…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
tRPC — End-to-End Type-Safe APIs
Overview
tRPC lets a TypeScript server export a router type and a TypeScript client import only that type, so every call is checked at compile time with no REST routes, OpenAPI spec or code generation. Inputs are validated at runtime with a schema library (Zod, Valibot, ArkType, or anything with a Standard Schema). This skill targets tRPC v11 (@trpc/* 11.x). Both client and server must be on the same major version.
Instructions
1. Install
npm install @trpc/server @trpc/client zod
# React apps: the TanStack Query integration (recommended in v11)
npm install @trpc/tanstack-react-query @tanstack/react-query
TypeScript needs "strict": true. The legacy @trpc/react-query (createTRPCReact, trpc.x.useQuery()) and @trpc/next packages still ship in 11.x, but the docs steer new React code to @trpc/tanstack-react-query.
2. Define the server
// server/trpc.ts
import { initTRPC, TRPCError } from "@trpc/server";
import { z } from "zod";
export type Context = { user?: { id: string }; db: Db }; // Db: your Prisma/Drizzle client type
const t = initTRPC.context<Context>().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.user) throw new TRPCError({ code: "UNAUTHORIZED" });
return next({ ctx: { user: ctx.user } }); // narrows ctx.user to non-optional downstream
});
// server/routers/users.ts
export const usersRouter = router({
getById: publicProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
const user = await ctx.db.user.findUnique({ where: { id: input.id } });
if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
return user;
}),
list: publicProcedure
.input(z.object({ cursor: z.string().nullish(), limit: z.number().min(1).max(100).default(20) }))
.query(async ({ input, ctx }) => {
const rows = await ctx.db.user.findMany({
take: input.limit + 1,
cursor: input.cursor ? { id: input.cursor } : undefined,
orderBy: { createdAt: "desc" },
});
const nextCursor = rows.length > input.limit ? rows.pop()!.id : undefined;
return { items: rows, nextCursor };
}),
rename: protectedProcedure
.input(z.object({ name: z.string().min(1) }))
.mutation(({ input, ctx }) => ctx.db.user.update({ where: { id: ctx.user.id }, data: input })),
});
// server/routers/_app.ts
export const appRouter = router({ users: usersRouter });
export type AppRouter = typeof appRouter; // the only thing the client imports
Name the cursor field cursor in the input and return nextCursor; the infinite-query helpers rely on that.
3. Serve it
Pick an adapter from @trpc/server/adapters/*. Each one takes router and createContext:
- Standalone Node:
createHTTPServer({ router: appRouter, createContext })from@trpc/server/adapters/standalone, then.listen(3000). - Express, Fastify, AWS Lambda:
.../adapters/express,.../fastify,.../aws-lambda. - Next.js App Router and other fetch runtimes:
fetchRequestHandler({ endpoint: "/api/trpc", req, router: appRouter, createContext })from@trpc/server/adapters/fetch, exported as bothGETandPOSTinapp/api/trpc/[trpc]/route.ts.
4. Call it from any TypeScript client
import { createTRPCClient, httpBatchLink } from "@trpc/client";
import type { AppRouter } from "../server/routers/_app";
const client = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: "http://localhost:3000", headers: () => ({ authorization: `Bearer ${process.env.API_TOKEN}` }) })],
});
const user = await client.users.getById.query({ id: "usr_42" });
Calls made in the same tick are batched into one HTTP request by httpBatchLink. A transformer (superjson, for Date/Map) is set with initTRPC.create({ transformer }) on the server and transformer on the link in v11, not on the client constructor.
5. React with TanStack Query
// utils/trpc.ts
import { createTRPCContext } from "@trpc/tanstack-react-query";
import type { AppRouter } from "../server/routers/_app";
export const { TRPCProvider, useTRPC } = createTRPCContext<AppRouter>();
Wrap the app in <QueryClientProvider client={queryClient}><TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>, where trpcClient is the createTRPCClient above, created once (for example with useState). In Next.js, create a fresh QueryClient per request on the server and reuse one in the browser.
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/utils/trpc";
function Profile({ userId }: { userId: string }) {
const trpc = useTRPC();
const queryClient = useQueryClient();
const user = useQuery(trpc.users.getById.queryOptions({ id: userId }));
const rename =
Установить trpc в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл trpc?
tRPC builds end-to-end type-safe TypeScript APIs without schemas or code generation: the server defines procedures, the client calls them with full type inference. Use when someone asks to "add tRPC", "set up a tRPC router", "call my API with type safety", "use tRPC with React Query or Next.js", or to migrate a tRPC v10 app to v11.
Как установить скилл trpc?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл trpc запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic