nestjs-trpc
Qué hace
Guía a la IA para definir enrutadores de tRPC como clases de NestJS, añadir esquemas de Zod y generar el tipo del cliente. Está pensada para desarrolladores que quieren seguridad de tipos de extremo a extremo en NestJS.
Cuándo usarla
- ✓Cuando quieres procedimientos de tRPC dentro de una aplicación de NestJS.
- ✓Cuando usas los decoradores @Router, @Query o @Mutation en un proyecto de NestJS.
- ✓Cuando tu cliente no tiene tipos o el tipo AppRouter está desactualizado.
Link de la skill
https://github.com/trycompai/crm/blob/release/.agents/skills/nestjs-trpc/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“¿Puedes añadir en mi aplicación de NestJS una consulta de tRPC que devuelva un usuario por id, con un esquema de entrada de Zod?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La IA prepara la clase de enrutador decorada, la registra en el módulo de NestJS y ejecuta la CLI para que el cliente reciba el tipo AppRouter correspondiente.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
NestJS-tRPC
nestjs-trpc lets you define tRPC procedures as decorated NestJS classes instead of
chaining t.procedure builders. Routers are DI-aware classes that look like controllers;
a separate CLI reads those decorators and emits an AppRouter type for the client.
Verified against v2.13.0. The published docs at nestjs-trpc.io still contain v1-era
examples in several places. Where this skill and the docs disagree, this skill matches the
shipped .d.ts files and the official examples/ in the repo — see
Docs errata for the specific traps.
The one thing to internalize
There are two separate systems that both need to be correct, and they fail independently:
| Runtime | Type generation | |
|---|---|---|
| Driven by | Nest DI container at boot | Rust CLI doing static analysis of your source |
| Needs | classes listed in providers |
decorators it can read literally |
| Fails as | 404 / "no procedures" / undefined injection | stale or missing AppRouter |
A router that works at runtime but was never picked up by the CLI produces a client with no types, and vice versa. When something is wrong, first ask which of the two is broken.
Setup workflow
1. Install
npm install nestjs-trpc zod @trpc/server
Peer deps (v2.13.0): @nestjs/common & @nestjs/core ^9.3.8 || ^10 || ^11,
@trpc/server ^11, zod ^3.14 || ^4, rxjs 7.8.1, reflect-metadata ^0.1.13 || ^0.2.
tRPC v11 is required — v10 will not work.
Standard NestJS tsconfig.json requirements apply: experimentalDecorators: true,
emitDecoratorMetadata: true. tsc must be resolvable, because the CLI shells out to it
to typecheck what it generates.
2. Register the module
// app.module.ts
import { Module } from '@nestjs/common';
import { TRPCModule } from 'nestjs-trpc';
import { UserRouter } from './user.router';
import { UserService } from './user.service';
import { ProtectedMiddleware } from './protected.middleware';
import { AppContext } from './app.context';
@Module({
imports: [
TRPCModule.forRoot({
context: AppContext,
}),
],
providers: [UserRouter, AppContext, UserService, ProtectedMiddleware],
})
export class AppModule {}
Routers, middlewares, and the context class are all ordinary providers. Listing them in
providers is what makes DI work — forgetting a router here is the single most common
reason procedures silently don't exist at runtime.
Default mount point is /trpc; override with basePath. Full option table in
references/module-config.md.
3. Write a router
// user.router.ts
import { Inject } from '@nestjs/common';
import { Router, Query, Mutation, UseMiddlewares, Input, Ctx } from 'nestjs-trpc';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { UserService } from './user.service';
import { ProtectedMiddleware } from './protected.middleware';
import { userSchema, type User } from './user.schema';
@Router({ alias: 'users' })
export class UserRouter {
constructor(@Inject(UserService) private readonly userService: UserService) {}
@Query({
input: z.object({ userId: z.string() }),
output: userSchema,
})
@UseMiddlewares(ProtectedMiddleware)
async getUserById(@Input('userId') userId: string): Promise<User> {
const user = await this.userService.getUser(userId);
if (user == null) {
throw new TRPCError({ message: 'Could not find user.', code: 'NOT_FOUND' });
}
return user;
}
}
Client call site: trpc.users.getUserById.query({ userId }). The alias sets that first
segment — without it the class name is used.
4. Generate the client type
npx nestjs-trpc generate # one-shot
npx nestjs-trpc watch # regenerate on change during development
Writes server.ts (containing export type AppRouter = typeof appRouter) to
./src/@generated by default; --output <dir> moves it. This is a build step, not a
runtime import — the generated file is types only, and your procedures still execute
through the Nest-managed router at runtime.
Add it to your scripts so it can't drift:
{
"scripts": {
"dev": "nestjs-trpc watch & nest start --watch",
"build": "nestjs-trpc generate && nest build"
}
}
Run nestjs-trpc generate --dry-run in CI to fail the build when the committed types are
stale.
Writing procedures
Three procedure decorators, all taking `{ input?, output?,
Preguntas frecuentes
¿Por qué el cliente podría no tener tipos?
La CLI lee los decoradores para construir el tipo AppRouter, así que un tipo que falta o está desactualizado suele significar que la CLI no detectó el enrutador.
¿Qué biblioteca de validación usa?
Usa Zod para los esquemas de entrada y de salida.
¿Qué necesita instalado?
Necesita el paquete nestjs-trpc, tRPC v11 y Zod, además del registro del módulo en NestJS.
Detalles
Descripción original del autor
Build end-to-end type-safe tRPC APIs inside NestJS using the nestjs-trpc adapter — @Router/@Query/@Mutation/@Subscription decorators, TRPCModule.forRoot, injectable middlewares and context, Zod input/output schemas, and the Rust CLI that generates the AppRouter type for clients. Use this skill whenever the user mentions nestjs-trpc, tRPC in a NestJS app, @Router or @Query decorators, TRPCModule, AppRouterHost, "typed API between my Nest backend and frontend", generating AppRouter types, or is migrating a NestJS GraphQL/REST API to tRPC — even if they don't name the library explicitly.
repo: trycompai/crm
Popularidad
- Estrellas en GitHub
- 12 mil
- Posición en el ranking
- #11521
- Licencia
- MIT
- Actualizada
- 1/11/2026
Comentarios
- …
Más skills de este repositorio
ai-elements
12 milAyuda a tu agente a crear interfaces de chat con IA usando componentes listos para conversaciones, mensajes y campos de instrucciones.
ai-sdk
12 milAyuda a tu agente a crear funciones de IA con el AI SDK de Vercel: texto, transmisión en tiempo real, herramientas y agentes.
better-accessibility
12 milAyuda a tu agente a hacer las interfaces utilizables con teclado y lectores de pantalla, cubriendo foco, etiquetas, ARIA y formularios.
better-auth-best-practices
12 milAyuda a tu agente a configurar Better Auth para inicio de sesión, sesiones, OAuth y plugins en una app de TypeScript, siguiendo sus pasos oficiales.
Skills parecidas
api-connector-builder
280 milHace que tu agente cree nuevas conexiones de API siguiendo el patrón existente. Úsalo para añadir una integración más sin inventar otra forma de hacer las cosas.
api-design
280 milAyuda a tu agente a diseñar APIs REST según las buenas prácticas. Es útil para definir cómo se comunican las APIs, cómo se muestran los errores y cómo organizar los datos.
backend-patterns
280 milAyuda a tu agente con patrones de arquitectura del lado del servidor y optimización de bases de datos. Es útil para crear o revisar código que se ejecuta en el servidor.