{"data":{"slug":"github-lobehub-lobehub-agents-skills-trpc-router-d50eb876025f","title":"Build TRPC Routers for API Endpoints","summary":"Create TRPC routers for server-side API endpoints with proper middleware and procedure patterns, including query and mutation endpoints, aggregated data views, and model injection via middleware.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-trpc-router-d50eb876025f","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-trpc-router-d50eb876025f","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-trpc-router-d50eb876025f.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-trpc-router-d50eb876025f\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Always use middleware to inject models into `ctx` instead of creating `new Model(ctx.serverDB, ctx.userId)` inside every procedure. Ensure that the router files are located in `apps\/server\/src\/routers\/lambda\/<domain>.ts` and that the required imports are included.","instructions":"---\nname: trpc-router\ndescription: 'Use for server TRPC routers, procedures and API endpoints in apps\/server\/src\/routers.'\nuser-invocable: false\n---\n\n# TRPC Router Guide\n\n## File Location\n\n- Routers: `apps\/server\/src\/routers\/lambda\/<domain>.ts`\n- Helpers: `apps\/server\/src\/routers\/lambda\/_helpers\/`\n- Schemas: `apps\/server\/src\/routers\/lambda\/_schema\/`\n\n## Router Structure\n\n### Imports\n\n```typescript\nimport { TRPCError } from '@trpc\/server';\nimport { z } from 'zod';\n\nimport { SomeModel } from '@\/database\/models\/some';\nimport { authedProcedure, router } from '@\/libs\/trpc\/lambda';\nimport { serverDatabase } from '@\/libs\/trpc\/lambda\/middleware';\n```\n\n### Middleware: Inject Models into ctx\n\n**Always use middleware to inject models into `ctx`** instead of creating `new Model(ctx.serverDB, ctx.userId)` inside every procedure.\n\n```typescript\nconst domainProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {\n  const { ctx } = opts;\n  return opts.next({\n    ctx: {\n      fooModel: new FooModel(ctx.serverDB, ctx.userId),\n      barModel: new BarModel(ctx.serverDB, ctx.userId),\n    },\n  });\n});\n```\n\nThen use `ctx.fooModel` in procedures:\n\n```typescript\n\/\/ Good\nconst model = ctx.fooModel;\n\n\/\/ Bad - don't create models inside procedures\nconst model = new FooModel(ctx.serverDB, ctx.userId);\n```\n\n**Exception**: When a model needs a different `userId` (e.g., watchdog iterating over multiple users' tasks), create it inline.\n\n### Procedure Pattern\n\n```typescript\nexport const fooRouter = router({\n  \/\/ Query\n  find: domainProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {\n    try {\n      const item = await ctx.fooModel.findById(input.id);\n      if (!item) throw new TRPCError({ code: 'NOT_FOUND', message: 'Not found' });\n      return { data: item, success: true };\n    } catch (error) {\n      if (error instanceof TRPCError) throw error;\n      console.error('[foo:find]', error);\n      throw new TRPCError({\n        cause: error,\n        code: 'INTERNAL_SERVER_ERROR',\n        message: 'Failed to find item',\n      });\n    }\n  }),\n\n  \/\/ Mutation\n  create: domainProcedure.input(createSchema).mutation(async ({ input, ctx }) => {\n    try {\n      const item = await ctx.fooModel.create(input);\n      return { data: item, message: 'Created', success: true };\n    } catch (error) {\n      if (error instanceof TRPCError) throw error;\n      console.error('[foo:create]', error);\n      throw new TRPCError({\n        cause: error,\n        code: 'INTERNAL_SERVER_ERROR',\n        message: 'Failed to create',\n      });\n    }\n  }),\n});\n```\n\n### Aggregated Detail Endpoint\n\nFor views that need multiple related data, create a single `detail` procedure that fetches everything in parallel:\n\n```typescript\ndetail: domainProcedure.input(idInput).query(async ({ input, ctx }) => {\n  const item = await resolveOrThrow(ctx.fooModel, input.id);\n\n  const [children, related] = await Promise.all([\n    ctx.fooModel.findChildren(item.id),\n    ctx.barModel.findByFooId(item.id),\n  ]);\n\n  return {\n    data: { ...item, children, related },\n    success: true,\n  };\n}),\n```\n\nThis avoids the CLI or frontend making N sequential requests.\n\n## Conventions\n\n- Return shape: `{ data, success: true }` for queries, `{ data?, message, success: true }` for mutations\n- Error handling: re-throw `TRPCError`, wrap others with `console.error` + new `TRPCError`\n- Input validation: use `zod` schemas, define at file top\n- Router name: `export const fooRouter = router({ ... })`\n- Procedure names: alphabetical order within the router object\n- Log prefix: `[domain:procedure]` format, e.g. `[task:create]`\n","use_cases":["Implement query and mutation endpoints for a database model","Create aggregated detail endpoints for complex data views","Set up middleware for injecting models into the context"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/trpc-router\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T11:38:34.000000Z","updated_at":"2026-11-22T11:17:19.000000Z","seo_title":"Build TRPC Routers for API Endpoints","seo_description":"Learn how to create TRPC routers for server-side API endpoints with proper middleware and procedure patterns.","seo_keywords":["TRPC router creation","API endpoint implementation","TRPC middleware setup","Database model procedures","Aggregated data endpoints"]}}