Skip to content
cccskills
FreePublished on GitHubEnglish overview

trpc-router

Use this guide when adding server-side tRPC routers, queries, mutations, or API endpoints. It explains input validation, model access through middleware, response shapes, parallel detail queries, and consistent error handling for code in the server router area.

OriginalShow the original description

Use for server TRPC routers, procedures and API endpoints in apps/server/src/routers.

lobehub/lobehub83,504 stars(GitHub 83,504 + cccskills 0)

Run score Not tested

See how to install

Good for

  • Adding a query or mutation to a server router
  • Validating procedure inputs with Zod schemas
  • Combining related records in a detail endpoint
  • Following shared error and response conventions

Overview

What it does

This guide explains how to add server-side tRPC routers and procedures, including queries and mutations. It describes where router files belong and how to structure them. Inputs are validated with Zod schemas, while models are passed into procedure context through middleware for use within each procedure. The guide also shows response formats for queries and mutations, how to handle TRPCError, how to log errors, and how to order procedure names in a router. For a detail query that needs several related records, it includes an example that fetches them in parallel.

When it helps

Use it when adding an API procedure and you need to follow the existing project conventions. It can help when you want procedures to use models provided through shared middleware, keep unexpected errors in a consistent format, or return related information in one request for a screen or CLI.

Example requests

  • “Add a list query for this domain using the existing router conventions.”
  • “Create a detail procedure that returns the related data together.”
  • “Bring this mutation’s input validation and error handling in line with the guide.”

Notes

The guide covers server-side tRPC routers under apps/server/src/routers.

This overview was written by AI (OpenAI Codex) from the public SKILL.md. Check the original below for the exact behavior.

Document check

AI checked the SKILL.md for operations that need care and for setup requirements. The score comes only from actually running the skill (hands-on test).

SafetyAre sending data, deleting files, and running commands disclosed?
AGoodIt describes logging and error wrapping; no external sends or destructive actions are specified.
Easy setupDoes it need few tools or API keys, and are they documented?
AGoodIt assumes server routers and Zod but specifies no extra keys or setup steps.

Not counted in the score. Rated by AI (OpenAI Codex) as of Oct 26, 2026. Treat it as a guide and read the original before installing.

Disagree? Request a re-evaluation

Tell us which point is wrong and why. No login needed. We will check it against the SKILL.md, redo the evaluation, and show the result here.

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

Files included (1)

  • SKILL.md3.5 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

TRPC Router Guide

File Location

  • Routers: apps/server/src/routers/lambda/<domain>.ts
  • Helpers: apps/server/src/routers/lambda/_helpers/
  • Schemas: apps/server/src/routers/lambda/_schema/

Router Structure

Imports

import { TRPCError } from '@trpc/server';
import { z } from 'zod';

import { SomeModel } from '@/database/models/some';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';

Middleware: Inject Models into ctx

Always use middleware to inject models into ctx instead of creating new Model(ctx.serverDB, ctx.userId) inside every procedure.

const domainProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
  const { ctx } = opts;
  return opts.next({
    ctx: {
      fooModel: new FooModel(ctx.serverDB, ctx.userId),
      barModel: new BarModel(ctx.serverDB, ctx.userId),
    },
  });
});

Then use ctx.fooModel in procedures:

// Good
const model = ctx.fooModel;

// Bad - don't create models inside procedures
const model = new FooModel(ctx.serverDB, ctx.userId);

Exception: When a model needs a different userId (e.g., watchdog iterating over multiple users' tasks), create it inline.

Procedure Pattern

export const fooRouter = router({
  // Query
  find: domainProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {
    try {
      const item = await ctx.fooModel.findById(input.id);
      if (!item) throw new TRPCError({ code: 'NOT_FOUND', message: 'Not found' });
      return { data: item, success: true };
    } catch (error) {
      if (error instanceof TRPCError) throw error;
      console.error('[foo:find]', error);
      throw new TRPCError({
        cause: error,
        code: 'INTERNAL_SERVER_ERROR',
        message: 'Failed to find item',
      });
    }
  }),

  // Mutation
  create: domainProcedure.input(createSchema).mutation(async ({ input, ctx }) => {
    try {
      const item = await ctx.fooModel.create(input);
      return { data: item, message: 'Created', success: true };
    } catch (error) {
      if (error instanceof TRPCError) throw error;
      console.error('[foo:create]', error);
      throw new TRPCError({
        cause: error,
        code: 'INTERNAL_SERVER_ERROR',
        message: 'Failed to create',
      });
    }
  }),
});

Aggregated Detail Endpoint

For views that need multiple related data, create a single detail procedure that fetches everything in parallel:

detail: domainProcedure.input(idInput).query(async ({ input, ctx }) => {
  const item = await resolveOrThrow(ctx.fooModel, input.id);

  const [children, related] = await Promise.all([
    ctx.fooModel.findChildren(item.id),
    ctx.barModel.findByFooId(item.id),
  ]);

  return {
    data: { ...item, children, related },
    success: true,
  };
}),

This avoids the CLI or frontend making N sequential requests.

Conventions

  • Return shape: { data, success: true } for queries, { data?, message, success: true } for mutations
  • Error handling: re-throw TRPCError, wrap others with console.error + new TRPCError
  • Input validation: use zod schemas, define at file top
  • Router name: export const fooRouter = router({ ... })
  • Procedure names: alphabetical order within the router object
  • Log prefix: [domain:procedure] format, e.g. [task:create]

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

acceptance

FreeSummary

Use this skill to verify a delivery by exercising the real product through a suitable surface such as a CLI, web app, desktop app, or iOS Simulator. It helps create or find a verification plan, capture evidence, and publish an acceptance report.

  • Verifying a completed product change
  • Collecting screenshots or other evidence
  • Creating a verification plan and report
lobehub/lobehub83.5KUpdated Oct 26, 2026

Use this skill to add an AI model provider to LobeHub across runtime integration, model cards, settings, branding, documentation, and acceptance checks. It also covers provider documentation updates and distinguishes new providers from models added to an existing provider.

  • Integrating a new AI model provider into LobeHub
  • Updating setup or usage documentation for a provider
  • Checking whether a model needs a new provider integration
lobehub/lobehub83.5KUpdated Oct 26, 2026

add-setting-env

FreeSummary

Use this skill to add a server-side environment variable that sets a default for a user setting. It walks through validation, server configuration and store merging, plus updating the example environment file and self-hosting documentation.

  • Adding an environment variable for a setting default
  • Wiring a new setting domain into server config
  • Documenting a new variable for self-hosting
lobehub/lobehub83.5KUpdated Oct 26, 2026

Provides guidance for registering hooks around an agent’s execution steps, tool calls, human approvals, context compression, and sub-agent calls. Hooks can observe events, supply local mock tool results, or use webhooks to allow or deny tool results under configured policies.

  • Observing agent steps and tool errors
  • Mocking tool results during local execution
  • Requiring webhook decisions before or after a tool call
lobehub/lobehub83.5KUpdated Oct 26, 2026

agent-signal

FreeSummary

Build event-driven background workflows for agents by defining sources, interpreting them as signals, and running actions through policies. It also guides asynchronous handoffs, deduplication, scoped execution, completion receipts, and observability.

  • Adding a new event source to an agent workflow
  • Routing interpreted signals to concrete background actions
  • Enqueuing work for asynchronous processing
lobehub/lobehub83.5KUpdated Oct 26, 2026

Use this skill to run end-to-end acceptance checks for bot channels in real desktop chat apps. It drives apps such as Discord, Slack, Telegram, WeChat, Lark, and QQ to send a message, wait for a response, and capture the result.

  • Checking a bot response in a real Discord channel
  • Testing chat behavior through Slack or Telegram
  • Capturing a bot interaction in a native macOS app
lobehub/lobehub83.5KUpdated Oct 26, 2026

See all skills by lobehub

Report a problem with this skill