[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72AKVQC4VHNP0JB0Z4F4BV8":3,"skill-same:01M72AKVQC4VHNP0JB0Z4F4BV8":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":13,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":45,"install":46,"resources":59},"01M72AKVQC4VHNP0JB0Z4F4BV8","trpc-fullstack",null,"Build end-to-end type-safe APIs with tRPC — routers, procedures, middleware, subscriptions, and Next.js\u002FReact integration patterns.","Sansar35\u002Fclaude-agent","Sansar35","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F145020281?v=4","01M724CQ2SCC86MGNSD87D0D4K","01M724CQ3965G9WJ3QXE3AJ5YY",1,"MIT","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fantigravity\u002Ftrpc-fullstack\u002FSKILL.md",[],[],"2026-11-10 18:39:20",false,"---\nname: trpc-fullstack\ndescription: \"Build end-to-end type-safe APIs with tRPC — routers, procedures, middleware, subscriptions, and Next.js\u002FReact integration patterns.\"\ncategory: framework\nrisk: none\nsource: community\ndate_added: \"2026-03-17\"\nauthor: suhaibjanjua\ntags: [typescript, trpc, api, fullstack, nextjs, react, type-safety]\ntools: [claude, cursor, gemini]\n---\n\n# tRPC Full-Stack\n\n## Overview\n\ntRPC lets you build fully type-safe APIs without writing a schema or code-generation step. Your TypeScript types flow from the server router directly to the client — so every API call is autocompleted, validated at compile time, and refactoring-safe. Use this skill when building TypeScript monorepos, Next.js apps, or any project where the server and client share a codebase.\n\n## When to Use This Skill\n\n- Use when building a TypeScript full-stack app (Next.js, Remix, Express + React) where the client and server share a single repo\n- Use when you want end-to-end type safety on API calls without REST\u002FGraphQL schema overhead\n- Use when adding real-time features (subscriptions) to an existing tRPC setup\n- Use when designing multi-step middleware (auth, rate limiting, tenant scoping) on tRPC procedures\n- Use when migrating an existing REST\u002FGraphQL API to tRPC incrementally\n\n## Core Concepts\n\n### Routers and Procedures\n\nA **router** groups related **procedures** (think: endpoints). Procedures are typed functions — `query` for reads, `mutation` for writes, `subscription` for real-time streams.\n\n### Input Validation with Zod\n\nAll procedure inputs are validated with Zod schemas. The validated, typed input is available in the procedure handler — no manual parsing.\n\n### Context\n\n`context` is shared state passed to every procedure — auth session, database client, request headers, etc. It is built once per request in a context factory. **Important:** Next.js App Router and Pages Router require separate context factories because App Router handlers receive a fetch `Request`, not a Node.js `NextApiRequest`.\n\n### Middleware\n\nMiddleware chains run before a procedure. Use them for authentication, logging, and request enrichment. They can extend the context for downstream procedures.\n\n---\n\n## How It Works\n\n### Step 1: Install and Initialize\n\n```bash\nnpm install @trpc\u002Fserver @trpc\u002Fclient @trpc\u002Freact-query @tanstack\u002Freact-query zod\n```\n\nCreate the tRPC instance and reusable builders:\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Ftrpc.ts\nimport { initTRPC, TRPCError } from '@trpc\u002Fserver';\nimport { type Context } from '.\u002Fcontext';\nimport { ZodError } from 'zod';\n\nconst t = initTRPC.context\u003CContext>().create({\n  errorFormatter({ shape, error }) {\n    return {\n      ...shape,\n      data: {\n        ...shape.data,\n        zodError:\n          error.cause instanceof ZodError ? error.cause.flatten() : null,\n      },\n    };\n  },\n});\n\nexport const router = t.router;\nexport const publicProcedure = t.procedure;\nexport const middleware = t.middleware;\n```\n\n### Step 2: Define Two Context Factories\n\nNext.js App Router handlers receive a fetch `Request` (not a Node.js `NextApiRequest`), so the context\nmust be built differently depending on the call site. Define one factory per surface:\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Fcontext.ts\nimport { type FetchCreateContextFnOptions } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { auth } from '@\u002Fserver\u002Fauth'; \u002F\u002F Next-Auth v5 \u002F your auth helper\nimport { db } from '.\u002Fdb';\n\n\u002F**\n * Context for the HTTP handler (App Router Route Handler).\n * `opts.req` is the fetch Request — auth is resolved server-side via `auth()`.\n *\u002F\nexport async function createTRPCContext(opts: FetchCreateContextFnOptions) {\n  const session = await auth(); \u002F\u002F server-side auth — no req\u002Fres needed\n  return { session, db, headers: opts.req.headers };\n}\n\n\u002F**\n * Context for direct server-side callers (Server Components, RSC, cron jobs).\n * No HTTP request is involved, so we call auth() directly from the server.\n *\u002F\nexport async function createServerContext() {\n  const session = await auth();\n  return { session, db };\n}\n\nexport type Context = Awaited\u003CReturnType\u003Ctypeof createTRPCContext>>;\n```\n\n### Step 3: Build an Auth Middleware and Protected Procedure\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Ftrpc.ts (continued)\nconst enforceAuth = middleware(({ ctx, next }) => {\n  if (!ctx.session?.user) {\n    throw new TRPCError({ code: 'UNAUTHORIZED' });\n  }\n  return next({\n    ctx: {\n      \u002F\u002F Narrows type: session is non-null from here\n      session: { ...ctx.session, user: ctx.session.user },\n    },\n  });\n});\n\nexport const protectedProcedure = t.procedure.use(enforceAuth);\n```\n\n### Step 4: Create Routers\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Frouters\u002Fpost.ts\nimport { z } from 'zod';\nimport { router, publicProcedure, protectedProcedure } from '..\u002Ftrpc';\nimport { TRPCError } from '@trpc\u002Fserver';\n\nexport const postRouter = router({\n  list: publicProcedure\n    .input(\n      z.object({\n        limit: z.number().min(1).max(100).default(20),\n        cursor: z.string().optional(),\n      })\n    )\n    .query(async ({ ctx, input }) => {\n      const posts = await ctx.db.post.findMany({\n        take: input.limit + 1,\n        cursor: input.cursor ? { id: input.cursor } : undefined,\n        orderBy: { createdAt: 'desc' },\n      });\n      const nextCursor =\n        posts.length > input.limit ? posts.pop()!.id : undefined;\n      return { posts, nextCursor };\n    }),\n\n  byId: publicProcedure\n    .input(z.object({ id: z.string() }))\n    .query(async ({ ctx, input }) => {\n      const post = await ctx.db.post.findUnique({ where: { id: input.id } });\n      if (!post) throw new TRPCError({ code: 'NOT_FOUND' });\n      return post;\n    }),\n\n  create: protectedProcedure\n    .input(\n      z.object({\n        title: z.string().min(1).max(200),\n        body: z.string().min(1),\n      })\n    )\n    .mutation(async ({ ctx, input }) => {\n      return ctx.db.post.create({\n        data: { ...input, authorId: ctx.session.user.id },\n      });\n    }),\n\n  delete: protectedProcedure\n    .input(z.object({ id: z.string() }))\n    .mutation(async ({ ctx, input }) => {\n      const post = await ctx.db.post.findUnique({ where: { id: input.id } });\n      if (!post) throw new TRPCError({ code: 'NOT_FOUND' });\n      if (post.authorId !== ctx.session.user.id)\n        throw new TRPCError({ code: 'FORBIDDEN' });\n      return ctx.db.post.delete({ where: { id: input.id } });\n    }),\n});\n```\n\n### Step 5: Compose the Root Router and Export Types\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Froot.ts\nimport { router } from '.\u002Ftrpc';\nimport { postRouter } from '.\u002Frouters\u002Fpost';\nimport { userRouter } from '.\u002Frouters\u002Fuser';\n\nexport const appRouter = router({\n  post: postRouter,\n  user: userRouter,\n});\n\n\u002F\u002F Export the type for the client — never import the appRouter itself on the client\nexport type AppRouter = typeof appRouter;\n```\n\n### Step 6: Mount the API Handler (Next.js App Router)\n\nThe App Router handler must use `fetchRequestHandler` and the **fetch-based** context factory.\n`createTRPCContext` receives `FetchCreateContextFnOptions` (with a fetch `Request`), not\na Pages Router `req\u002Fres` pair.\n\n```typescript\n\u002F\u002F src\u002Fapp\u002Fapi\u002Ftrpc\u002F[trpc]\u002Froute.ts\nimport { fetchRequestHandler } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { type FetchCreateContextFnOptions } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { appRouter } from '@\u002Fserver\u002Froot';\nimport { createTRPCContext } from '@\u002Fserver\u002Fcontext';\n\nconst handler = (req: Request) =>\n  fetchRequestHandler({\n    endpoint: '\u002Fapi\u002Ftrpc',\n    req,\n    router: appRouter,\n    \u002F\u002F opts is FetchCreateContextFnOptions — req is the fetch Request\n    createContext: (opts: FetchCreateContextFnOptions) => createTRPCContext(opts),\n  });\n\nexport { handler as GET, handler as POST };\n```\n\n### Step 7: Set Up the Client (React Query)\n\n```typescript\n\u002F\u002F src\u002Futils\u002Ftrpc.ts\nimport { createTRPCReact } from '@trpc\u002Freact-query';\nimport type { AppRouter } from '@\u002Fserver\u002Froot';\n\nexport const trpc = createTRPCReact\u003CAppRouter>();\n```\n\n```typescript\n\u002F\u002F src\u002Fapp\u002Fproviders.tsx\n'use client';\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query';\nimport { httpBatchLink } from '@trpc\u002Fclient';\nimport { useState } from 'react';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function TRPCProvider({ children }: { children: React.ReactNode }) {\n  const [queryClient] = useState(() => new QueryClient());\n  const [trpcClient] = useState(() =>\n    trpc.createClient({\n      links: [\n        httpBatchLink({\n          url: '\u002Fapi\u002Ftrpc',\n          headers: () => ({ 'x-trpc-source': 'react' }),\n        }),\n      ],\n    })\n  );\n\n  return (\n    \u003Ctrpc.Provider client={trpcClient} queryClient={queryClient}>\n      \u003CQueryClientProvider client={queryClient}>{children}\u003C\u002FQueryClientProvider>\n    \u003C\u002Ftrpc.Provider>\n  );\n}\n```\n\n---\n\n## Examples\n\n### Example 1: Fetching Data in a Component\n\n```typescript\n\u002F\u002F components\u002FPostList.tsx\n'use client';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function PostList() {\n  const { data, isLoading, error } = trpc.post.list.useQuery({ limit: 10 });\n\n  if (isLoading) return \u003Cp>Loading…\u003C\u002Fp>;\n  if (error) return \u003Cp>Error: {error.message}\u003C\u002Fp>;\n\n  return (\n    \u003Cul>\n      {data?.posts.map((post) => (\n        \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n```\n\n### Example 2: Mutation with Cache Invalidation\n\n```typescript\n'use client';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function CreatePost() {\n  const utils = trpc.useUtils();\n\n  const createPost = trpc.post.create.useMutation({\n    onSuccess: () => {\n      \u002F\u002F Invalidate and refetch the post list\n      utils.post.list.invalidate();\n    },\n  });\n\n  const handleSubmit = (e: React.FormEvent\u003CHTMLFormElement>) => {\n    e.preventDefault();\n    const form = e.currentTarget;\n    const data = new FormData(form);\n    createPost.mutate({\n      title: data.get('title') as string,\n      body: data.get('body') as string,\n    });\n    form.reset();\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput name=\"title\" placeholder=\"Title\" required \u002F>\n      \u003Ctextarea name=\"body\" placeholder=\"Body\" required \u002F>\n      \u003Cbutton type=\"submit\" disabled={createPost.isPending}>\n        {createPost.isPending ? 'Creating…' : 'Create Post'}\n      \u003C\u002Fbutton>\n      {createPost.error && \u003Cp>{createPost.error.message}\u003C\u002Fp>}\n    \u003C\u002Fform>\n  );\n}\n```\n\n### Example 3: Server-Side Caller (Server Components \u002F SSR)\n\nUse `createServerContext` — the dedicated server-side factory — so that `auth()` is called\ncorrectly without needing a synthetic or empty request object:\n\n```typescript\n\u002F\u002F app\u002Fposts\u002Fpage.tsx (Next.js Server Component)\nimport { appRouter } from '@\u002Fserver\u002Froot';\nimport { createCallerFactory } from '@trpc\u002Fserver';\nimport { createServerContext } from '@\u002Fserver\u002Fcontext';\n\nconst createCaller = createCallerFactory(appRouter);\n\nexport default async function PostsPage() {\n  \u002F\u002F Uses createServerContext — calls auth() server-side, no req\u002Fres cast needed\n  const caller = createCaller(await createServerContext());\n  const { posts } = await caller.post.list({ limit: 20 });\n\n  return (\n    \u003Cul>\n      {posts.map((post) => (\n        \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n```\n\n### Example 4: Real-Time Subscriptions (WebSocket)\n\n```typescript\n\u002F\u002F server\u002Frouters\u002Fnotifications.ts\nimport { observable } from '@trpc\u002Fserver\u002Fobservable';\nimport { EventEmitter } from 'events';\n\nconst ee = new EventEmitter();\n\nexport const notificationRouter = router({\n  onNew: protectedProcedure.subscription(({ ctx }) => {\n    return observable\u003C{ message: string; at: Date }>((emit) => {\n      const onNotification = (data: { message: string }) => {\n        emit.next({ message: data.message, at: new Date() });\n      };\n\n      const channel = `user:${ctx.session.user.id}`;\n      ee.on(channel, onNotification);\n      return () => ee.off(channel, onNotification);\n    });\n  }),\n});\n```\n\n```typescript\n\u002F\u002F Client usage — requires wsLink in the client config\ntrpc.notification.onNew.useSubscription(undefined, {\n  onData(data) {\n    toast(data.message);\n  },\n});\n```\n\n---\n\n## Best Practices\n\n- ✅ **Export only `AppRouter` type** from server code — never import `appRouter` on the client\n- ✅ **Use separate context factories** — `createTRPCContext` for the HTTP handler, `createServerContext` for Server Components and callers\n- ✅ **Validate all inputs with Zod** — never trust raw `input` without a schema\n- ✅ **Split routers by domain** (posts, users, billing) and merge in `root.ts`\n- ✅ **Extend context in middleware** rather than querying the DB multiple times per request\n- ✅ **Use `utils.invalidate()`** after mutations to keep the cache fresh\n- ❌ **Don't cast context with `as any`** to silence type errors — the mismatch will surface as a runtime failure when auth or session lookups return undefined\n- ❌ **Don't use `createContext({} as any)`** in Server Components — use `createServerContext()` which calls `auth()` directly\n- ❌ **Don't put business logic in the route handler** — keep it in the procedure or a service layer\n- ❌ **Don't share the tRPC client instance globally** — create it per-provider to avoid stale closures\n\n---\n\n## Security & Safety Notes\n\n- Always enforce authorization in `protectedProcedure` — never rely on client-side checks alone\n- Validate all input shapes with Zod, including pagination cursors and IDs, to prevent injection via malformed inputs\n- Avoid exposing internal error details to clients — use `TRPCError` with a public-safe `message` and keep stack traces server-side only\n- Rate-limit public procedures using middleware to prevent abuse\n\n---\n\n## Common Pitfalls\n\n- **Problem:** Auth session is `null` in protected procedures even when the user is logged in\n  **Solution:** Ensure `createTRPCContext` uses the correct server-side auth call (e.g. `auth()` from Next-Auth v5) and is not receiving a Pages Router `req\u002Fres` cast via `as any` in an App Router handler\n\n- **Problem:** Server Component caller fails for auth-dependent queries\n  **Solution:** Use `createServerContext()` (the dedicated server-side factory) instead of passing an empty or synthetic object to `createContext`\n\n- **Problem:** \"Type error: AppRouter is not assignable to AnyRouter\"\n  **Solution:** Import `AppRouter` as a `type` import (`import type { AppRouter }`) on the client, not the full module\n\n- **Problem:** Mutations not reflecting in the UI after success\n  **Solution:** Call `utils.\u003Crouter>.\u003Cprocedure>.invalidate()` in `onSuccess` to trigger a refetch via React Query\n\n- **Problem:** \"Cannot find module '@trpc\u002Fserver\u002Fadapters\u002Fnext'\" with App Router\n  **Solution:** Use `@trpc\u002Fserver\u002Fadapters\u002Ffetch` and `fetchRequestHandler` for the App Router; the `nextjs` adapter is for Pages Router only\n\n- **Problem:** Subscriptions not connecting\n  **Solution:** Subscriptions require `splitLink` — route subscriptions to `wsLink` and queries\u002Fmutations to `httpBatchLink`\n\n---\n\n## Related Skills\n\n- `@typescript-expert` — Deep TypeScript patterns used inside tRPC routers and generic utilities\n- `@react-patterns` — React hooks patterns that pair with `trpc.*.useQuery` and `useMutation`\n- `@test-driven-development` — Write procedure unit tests using `createCallerFactory` without an HTTP server\n- `@security-auditor` — Review tRPC middleware chains for auth bypass and input validation gaps\n\n## Additional Resources\n\n- [tRPC Official Docs](https:\u002F\u002Ftrpc.io\u002Fdocs)\n- [create-t3-app](https:\u002F\u002Fcreate.t3.gg) — Production Next.js starter with tRPC wired in\n- [tRPC GitHub](https:\u002F\u002Fgithub.com\u002Ftrpc\u002Ftrpc)\n- [TanStack Query Docs](https:\u002F\u002Ftanstack.com\u002Fquery\u002Flatest)\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","# tRPC Full-Stack\n\n## Overview\n\ntRPC lets you build fully type-safe APIs without writing a schema or code-generation step. Your TypeScript types flow from the server router directly to the client — so every API call is autocompleted, validated at compile time, and refactoring-safe. Use this skill when building TypeScript monorepos, Next.js apps, or any project where the server and client share a codebase.\n\n## When to Use This Skill\n\n- Use when building a TypeScript full-stack app (Next.js, Remix, Express + React) where the client and server share a single repo\n- Use when you want end-to-end type safety on API calls without REST\u002FGraphQL schema overhead\n- Use when adding real-time features (subscriptions) to an existing tRPC setup\n- Use when designing multi-step middleware (auth, rate limiting, tenant scoping) on tRPC procedures\n- Use when migrating an existing REST\u002FGraphQL API to tRPC incrementally\n\n## Core Concepts\n\n### Routers and Procedures\n\nA **router** groups related **procedures** (think: endpoints). Procedures are typed functions — `query` for reads, `mutation` for writes, `subscription` for real-time streams.\n\n### Input Validation with Zod\n\nAll procedure inputs are validated with Zod schemas. The validated, typed input is available in the procedure handler — no manual parsing.\n\n### Context\n\n`context` is shared state passed to every procedure — auth session, database client, request headers, etc. It is built once per request in a context factory. **Important:** Next.js App Router and Pages Router require separate context factories because App Router handlers receive a fetch `Request`, not a Node.js `NextApiRequest`.\n\n### Middleware\n\nMiddleware chains run before a procedure. Use them for authentication, logging, and request enrichment. They can extend the context for downstream procedures.\n\n---\n\n## How It Works\n\n### Step 1: Install and Initialize\n\n```bash\nnpm install @trpc\u002Fserver @trpc\u002Fclient @trpc\u002Freact-query @tanstack\u002Freact-query zod\n```\n\nCreate the tRPC instance and reusable builders:\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Ftrpc.ts\nimport { initTRPC, TRPCError } from '@trpc\u002Fserver';\nimport { type Context } from '.\u002Fcontext';\nimport { ZodError } from 'zod';\n\nconst t = initTRPC.context\u003CContext>().create({\n  errorFormatter({ shape, error }) {\n    return {\n      ...shape,\n      data: {\n        ...shape.data,\n        zodError:\n          error.cause instanceof ZodError ? error.cause.flatten() : null,\n      },\n    };\n  },\n});\n\nexport const router = t.router;\nexport const publicProcedure = t.procedure;\nexport const middleware = t.middleware;\n```\n\n### Step 2: Define Two Context Factories\n\nNext.js App Router handlers receive a fetch `Request` (not a Node.js `NextApiRequest`), so the context\nmust be built differently depending on the call site. Define one factory per surface:\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Fcontext.ts\nimport { type FetchCreateContextFnOptions } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { auth } from '@\u002Fserver\u002Fauth'; \u002F\u002F Next-Auth v5 \u002F your auth helper\nimport { db } from '.\u002Fdb';\n\n\u002F**\n * Context for the HTTP handler (App Router Route Handler).\n * `opts.req` is the fetch Request — auth is resolved server-side via `auth()`.\n *\u002F\nexport async function createTRPCContext(opts: FetchCreateContextFnOptions) {\n  const session = await auth(); \u002F\u002F server-side auth — no req\u002Fres needed\n  return { session, db, headers: opts.req.headers };\n}\n\n\u002F**\n * Context for direct server-side callers (Server Components, RSC, cron jobs).\n * No HTTP request is involved, so we call auth() directly from the server.\n *\u002F\nexport async function createServerContext() {\n  const session = await auth();\n  return { session, db };\n}\n\nexport type Context = Awaited\u003CReturnType\u003Ctypeof createTRPCContext>>;\n```\n\n### Step 3: Build an Auth Middleware and Protected Procedure\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Ftrpc.ts (continued)\nconst enforceAuth = middleware(({ ctx, next }) => {\n  if (!ctx.session?.user) {\n    throw new TRPCError({ code: 'UNAUTHORIZED' });\n  }\n  return next({\n    ctx: {\n      \u002F\u002F Narrows type: session is non-null from here\n      session: { ...ctx.session, user: ctx.session.user },\n    },\n  });\n});\n\nexport const protectedProcedure = t.procedure.use(enforceAuth);\n```\n\n### Step 4: Create Routers\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Frouters\u002Fpost.ts\nimport { z } from 'zod';\nimport { router, publicProcedure, protectedProcedure } from '..\u002Ftrpc';\nimport { TRPCError } from '@trpc\u002Fserver';\n\nexport const postRouter = router({\n  list: publicProcedure\n    .input(\n      z.object({\n        limit: z.number().min(1).max(100).default(20),\n        cursor: z.string().optional(),\n      })\n    )\n    .query(async ({ ctx, input }) => {\n      const posts = await ctx.db.post.findMany({\n        take: input.limit + 1,\n        cursor: input.cursor ? { id: input.cursor } : undefined,\n        orderBy: { createdAt: 'desc' },\n      });\n      const nextCursor =\n        posts.length > input.limit ? posts.pop()!.id : undefined;\n      return { posts, nextCursor };\n    }),\n\n  byId: publicProcedure\n    .input(z.object({ id: z.string() }))\n    .query(async ({ ctx, input }) => {\n      const post = await ctx.db.post.findUnique({ where: { id: input.id } });\n      if (!post) throw new TRPCError({ code: 'NOT_FOUND' });\n      return post;\n    }),\n\n  create: protectedProcedure\n    .input(\n      z.object({\n        title: z.string().min(1).max(200),\n        body: z.string().min(1),\n      })\n    )\n    .mutation(async ({ ctx, input }) => {\n      return ctx.db.post.create({\n        data: { ...input, authorId: ctx.session.user.id },\n      });\n    }),\n\n  delete: protectedProcedure\n    .input(z.object({ id: z.string() }))\n    .mutation(async ({ ctx, input }) => {\n      const post = await ctx.db.post.findUnique({ where: { id: input.id } });\n      if (!post) throw new TRPCError({ code: 'NOT_FOUND' });\n      if (post.authorId !== ctx.session.user.id)\n        throw new TRPCError({ code: 'FORBIDDEN' });\n      return ctx.db.post.delete({ where: { id: input.id } });\n    }),\n});\n```\n\n### Step 5: Compose the Root Router and Export Types\n\n```typescript\n\u002F\u002F src\u002Fserver\u002Froot.ts\nimport { router } from '.\u002Ftrpc';\nimport { postRouter } from '.\u002Frouters\u002Fpost';\nimport { userRouter } from '.\u002Frouters\u002Fuser';\n\nexport const appRouter = router({\n  post: postRouter,\n  user: userRouter,\n});\n\n\u002F\u002F Export the type for the client — never import the appRouter itself on the client\nexport type AppRouter = typeof appRouter;\n```\n\n### Step 6: Mount the API Handler (Next.js App Router)\n\nThe App Router handler must use `fetchRequestHandler` and the **fetch-based** context factory.\n`createTRPCContext` receives `FetchCreateContextFnOptions` (with a fetch `Request`), not\na Pages Router `req\u002Fres` pair.\n\n```typescript\n\u002F\u002F src\u002Fapp\u002Fapi\u002Ftrpc\u002F[trpc]\u002Froute.ts\nimport { fetchRequestHandler } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { type FetchCreateContextFnOptions } from '@trpc\u002Fserver\u002Fadapters\u002Ffetch';\nimport { appRouter } from '@\u002Fserver\u002Froot';\nimport { createTRPCContext } from '@\u002Fserver\u002Fcontext';\n\nconst handler = (req: Request) =>\n  fetchRequestHandler({\n    endpoint: '\u002Fapi\u002Ftrpc',\n    req,\n    router: appRouter,\n    \u002F\u002F opts is FetchCreateContextFnOptions — req is the fetch Request\n    createContext: (opts: FetchCreateContextFnOptions) => createTRPCContext(opts),\n  });\n\nexport { handler as GET, handler as POST };\n```\n\n### Step 7: Set Up the Client (React Query)\n\n```typescript\n\u002F\u002F src\u002Futils\u002Ftrpc.ts\nimport { createTRPCReact } from '@trpc\u002Freact-query';\nimport type { AppRouter } from '@\u002Fserver\u002Froot';\n\nexport const trpc = createTRPCReact\u003CAppRouter>();\n```\n\n```typescript\n\u002F\u002F src\u002Fapp\u002Fproviders.tsx\n'use client';\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query';\nimport { httpBatchLink } from '@trpc\u002Fclient';\nimport { useState } from 'react';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function TRPCProvider({ children }: { children: React.ReactNode }) {\n  const [queryClient] = useState(() => new QueryClient());\n  const [trpcClient] = useState(() =>\n    trpc.createClient({\n      links: [\n        httpBatchLink({\n          url: '\u002Fapi\u002Ftrpc',\n          headers: () => ({ 'x-trpc-source': 'react' }),\n        }),\n      ],\n    })\n  );\n\n  return (\n    \u003Ctrpc.Provider client={trpcClient} queryClient={queryClient}>\n      \u003CQueryClientProvider client={queryClient}>{children}\u003C\u002FQueryClientProvider>\n    \u003C\u002Ftrpc.Provider>\n  );\n}\n```\n\n---\n\n## Examples\n\n### Example 1: Fetching Data in a Component\n\n```typescript\n\u002F\u002F components\u002FPostList.tsx\n'use client';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function PostList() {\n  const { data, isLoading, error } = trpc.post.list.useQuery({ limit: 10 });\n\n  if (isLoading) return \u003Cp>Loading…\u003C\u002Fp>;\n  if (error) return \u003Cp>Error: {error.message}\u003C\u002Fp>;\n\n  return (\n    \u003Cul>\n      {data?.posts.map((post) => (\n        \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n```\n\n### Example 2: Mutation with Cache Invalidation\n\n```typescript\n'use client';\nimport { trpc } from '@\u002Futils\u002Ftrpc';\n\nexport function CreatePost() {\n  const utils = trpc.useUtils();\n\n  const createPost = trpc.post.create.useMutation({\n    onSuccess: () => {\n      \u002F\u002F Invalidate and refetch the post list\n      utils.post.list.invalidate();\n    },\n  });\n\n  const handleSubmit = (e: React.FormEvent\u003CHTMLFormElement>) => {\n    e.preventDefault();\n    const form = e.currentTarget;\n    const data = new FormData(form);\n    createPost.mutate({\n      title: data.get('title') as string,\n      body: data.get('body') as string,\n    });\n    form.reset();\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput name=\"title\" placeholder=\"Title\" required \u002F>\n      \u003Ctextarea name=\"body\" placeholder=\"Body\" required \u002F>\n      \u003Cbutton type=\"submit\" disabled={createPost.isPending}>\n        {createPost.isPending ? 'Creating…' : 'Create Post'}\n      \u003C\u002Fbutton>\n      {createPost.error && \u003Cp>{createPost.error.message}\u003C\u002Fp>}\n    \u003C\u002Fform>\n  );\n}\n```\n\n### Example 3: Server-Side Caller (Server Components \u002F SSR)\n\nUse `createServerContext` — the dedicated server-side factory — so that `auth()` is called\ncorrectly without needing a synthetic or empty request object:\n\n```typescript\n\u002F\u002F app\u002Fposts\u002Fpage.tsx (Next.js Server Component)\nimport { appRouter } from '@\u002Fserver\u002Froot';\nimport { createCallerFactory } from '@trpc\u002Fserver';\nimport { createServerContext } from '@\u002Fserver\u002Fcontext';\n\nconst createCaller = createCallerFactory(appRouter);\n\nexport default async function PostsPage() {\n  \u002F\u002F Uses createServerContext — calls auth() server-side, no req\u002Fres cast needed\n  const caller = createCaller(await createServerContext());\n  const { posts } = await caller.post.list({ limit: 20 });\n\n  return (\n    \u003Cul>\n      {posts.map((post) => (\n        \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n```\n\n### Example 4: Real-Time Subscriptions (WebSocket)\n\n```typescript\n\u002F\u002F server\u002Frouters\u002Fnotifications.ts\nimport { observable } from '@trpc\u002Fserver\u002Fobservable';\nimport { EventEmitter } from 'events';\n\nconst ee = new EventEmitter();\n\nexport const notificationRouter = router({\n  onNew: protectedProcedure.subscription(({ ctx }) => {\n    return observable\u003C{ message: string; at: Date }>((emit) => {\n      const onNotification = (data: { message: string }) => {\n        emit.next({ message: data.message, at: new Date() });\n      };\n\n      const channel = `user:${ctx.session.user.id}`;\n      ee.on(channel, onNotification);\n      return () => ee.off(channel, onNotification);\n    });\n  }),\n});\n```\n\n```typescript\n\u002F\u002F Client usage — requires wsLink in the client config\ntrpc.notification.onNew.useSubscription(undefined, {\n  onData(data) {\n    toast(data.message);\n  },\n});\n```\n\n---\n\n## Best Practices\n\n- ✅ **Export only `AppRouter` type** from server code — never import `appRouter` on the client\n- ✅ **Use separate context factories** — `createTRPCContext` for the HTTP handler, `createServerContext` for Server Components and callers\n- ✅ **Validate all inputs with Zod** — never trust raw `input` without a schema\n- ✅ **Split routers by domain** (posts, users, billing) and merge in `root.ts`\n- ✅ **Extend context in middleware** rather than querying the DB multiple times per request\n- ✅ **Use `utils.invalidate()`** after mutations to keep the cache fresh\n- ❌ **Don't cast context with `as any`** to silence type errors — the mismatch will surface as a runtime failure when auth or session lookups return undefined\n- ❌ **Don't use `createContext({} as any)`** in Server Components — use `createServerContext()` which calls `auth()` directly\n- ❌ **Don't put business logic in the route handler** — keep it in the procedure or a service layer\n- ❌ **Don't share the tRPC client instance globally** — create it per-provider to avoid stale closures\n\n---\n\n## Security & Safety Notes\n\n- Always enforce authorization in `protectedProcedure` — never rely on client-side checks alone\n- Validate all input shapes with Zod, including pagination cursors and IDs, to prevent injection via malformed inputs\n- Avoid exposing internal error details to clients — use `TRPCError` with a public-safe `message` and keep stack traces server-side only\n- Rate-limit public procedures using middleware to prevent abuse\n\n---\n\n## Common Pitfalls\n\n- **Problem:** Auth session is `null` in protected procedures even when the user is logged in\n  **Solution:** Ensure `createTRPCContext` uses the correct server-side auth call (e.g. `auth()` from Next-Auth v5) and is not receiving a Pages Router `req\u002Fres` cast via `as any` in an App Router handler\n\n- **Problem:** Server Component caller fails for auth-dependent queries\n  **Solution:** Use `createServerContext()` (the dedicated server-side factory) instead of passing an empty or synthetic object to `createContext`\n\n- **Problem:** \"Type error: AppRouter is not assignable to AnyRouter\"\n  **Solution:** Import `AppRouter` as a `type` import (`import type { AppRouter }`) on the client, not the full module\n\n- **Problem:** Mutations not reflecting in the UI after success\n  **Solution:** Call `utils.\u003Crouter>.\u003Cprocedure>.invalidate()` in `onSuccess` to trigger a refetch via React Query\n\n- **Problem:** \"Cannot find module '@trpc\u002Fserver\u002Fadapters\u002Fnext'\" with App Router\n  **Solution:** Use `@trpc\u002Fserver\u002Fadapters\u002Ffetch` and `fetchRequestHandler` for the App Router; the `nextjs` adapter is for Pages Router only\n\n- **Problem:** Subscriptions not connecting\n  **Solution:** Subscriptions require `splitLink` — route subscriptions to `wsLink` and queries\u002Fmutations to `httpBatchLink`\n\n---\n\n## Related Skills\n\n- `@typescript-expert` — Deep TypeScript patterns used inside tRPC routers and generic utilities\n- `@react-patterns` — React hooks patterns that pair with `trpc.*.useQuery` and `useMutation`\n- `@test-driven-development` — Write procedure unit tests using `createCallerFactory` without an HTTP server\n- `@security-auditor` — Review tRPC middleware chains for auth bypass and input validation gaps\n\n## Additional Resources\n\n- [tRPC Official Docs](https:\u002F\u002Ftrpc.io\u002Fdocs)\n- [create-t3-app](https:\u002F\u002Fcreate.t3.gg) — Production Next.js starter with tRPC wired in\n- [tRPC GitHub](https:\u002F\u002Fgithub.com\u002Ftrpc\u002Ftrpc)\n- [TanStack Query Docs](https:\u002F\u002Ftanstack.com\u002Fquery\u002Flatest)\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n",{"name":5,"risk":23,"tags":24,"tools":32,"author":36,"source":37,"category":38,"date_added":39,"description":7},"none",[25,26,27,28,29,30,31],"typescript","trpc","api","fullstack","nextjs","react","type-safety",[33,34,35],"claude","cursor","gemini","suhaibjanjua","community","framework","2026-03-17","main","d046d088ce5a79a083f0abc0fe1b7ded73bc5b1f","claude-config\u002Fskills\u002Fantigravity\u002Ftrpc-fullstack","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent","https:\u002F\u002Fgithub.com\u002FSansar35","2026-05-10 16:04:53",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add Sansar35\u002Fclaude-agent --skill trpc-fullstack",{"tool":52,"command":53},"bunx","bunx skills add Sansar35\u002Fclaude-agent --skill trpc-fullstack",{"tool":55,"command":56},"pnpm","pnpm dlx skills add Sansar35\u002Fclaude-agent --skill trpc-fullstack","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fantigravity\u002Ftrpc-fullstack\u002FSKILL.md",true,[],[61,68,75,82,89,97],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M72DVAN1JYEA302MT0C5MGD6","zustand-store-ts","Create Zustand stores following established patterns with proper TypeScript types and middleware.","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M72DV8J5NBRRM4RPDFRV95N7","zod-validation-expert","Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzod-validation-expert\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M72DV5EMHW0BHP9BZ167MDCB","zinc-database","Access ZINC (230M+ purchasable compounds). Search by ZINC ID\u002FSMILES, similarity searches, 3D-ready structures for docking, analog discovery, for virtual screening and drug discovery.","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzinc-database\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M72DV216QY0E693ZPEVQ0DBS","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":18},"01M72DTXQREMCRKA8NHCVKHN4W","zapier-workflows","Manage and trigger pre-built Zapier workflows and MCP tool orchestration. Use when user mentions workflows, Zaps, automations, daily digest, research, search, lead tracking, expenses, or asks to \"run\" any process. Also handles Perplexity-based research and Google Sheets data tracking.","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzapier-workflows\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzapier-workflows\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":18},"01M72DTT17TBSJ0Y8J2XZ4C9TZ","zapier-make-patterns","No-code automation democratizes workflow building. Zapier and Make (formerly Integromat) let non-developers automate business processes without writing code. But no-code doesn't mean no-complexity - these platforms have their own patterns, pitfalls, and breaking points.  This skill covers when to use which platform, how to build reliable automations, and when to graduate to code-based solutions. Key insight: Zapier optimizes for simplicity and integrations (7000+ apps), Make optimizes for power","https:\u002F\u002Fgithub.com\u002FSansar35\u002Fclaude-agent\u002Fblob\u002Fmain\u002Fclaude-config\u002Fskills\u002Fzapier-make-patterns\u002FSKILL.md",[],[]]