nestjs-trpc
하는 일
AI가 tRPC 라우터를 NestJS 클래스로 정의하고, Zod 스키마를 추가하며, 클라이언트 타입을 생성하도록 안내합니다. NestJS에서 처음부터 끝까지 타입 안전성을 원하는 개발자를 위한 스킬입니다.
사용하는 경우
- ✓NestJS 앱에 tRPC 프로시저를 추가하고 싶을 때.
- ✓NestJS 프로젝트에서 @Router, @Query 또는 @Mutation 데코레이터를 사용할 때.
- ✓클라이언트에 타입이 없거나 AppRouter 타입이 오래된 경우.
스킬 링크
https://github.com/trycompai/crm/blob/release/.agents/skills/nestjs-trpc/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“NestJS 앱에 id로 사용자를 찾아 반환하는 tRPC 쿼리를 추가해 주실 수 있나요? 입력값은 Zod 스키마로 검증해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI가 데코레이터가 붙은 라우터 클래스를 설정하고, NestJS 모듈에 등록한 뒤, CLI를 실행해 클라이언트가 맞는 AppRouter 타입을 받도록 합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 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?,
자주 묻는 질문
클라이언트에 타입이 없는 이유는 무엇인가요?
CLI가 데코레이터를 읽어 AppRouter 타입을 만듭니다. 타입이 없거나 오래되었다면 대개 CLI가 라우터를 인식하지 못한 것입니다.
어떤 검증 라이브러리를 사용하나요?
입력과 출력 스키마에 Zod를 사용합니다.
무엇을 설치해야 하나요?
nestjs-trpc 패키지, tRPC v11, Zod가 필요하며, NestJS 모듈 등록도 필요합니다.
상세 정보
작성자의 원본 설명
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
인기도
- GitHub 스타
- 12k
- 순위
- #11521
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
ai-elements
12k에이전트가 대화, 메시지, 도구 표시, 프롬프트 입력을 위한 기성 컴포넌트로 AI 채팅 화면을 만들도록 돕습니다.
ai-sdk
12k에이전트가 Vercel AI SDK로 텍스트 생성, 스트리밍, 도구 호출, 에이전트를 포함한 AI 기능을 만들도록 돕습니다.
better-accessibility
12k에이전트가 키보드와 스크린 리더로도 사용할 수 있도록 인터페이스를 만들며, 포커스, 레이블, ARIA, 양식을 다루도록 돕습니다.
better-auth-best-practices
12k에이전트가 TypeScript 앱에서 문서에 나온 단계에 따라 Better Auth로 로그인, 세션, OAuth, 플러그인을 설정하도록 돕습니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.