본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)48k · #6024

trpc-fullstack

하는 일

tRPC Full-Stack은 타입이 안전한 API(앱의 서버와 클라이언트를 잇는 연결)를 만들도록 돕습니다. 서버에서 작성한 코드를 클라이언트가 자동으로 이해하므로 오류를 막을 수 있습니다.

사용하는 경우

  • ✓TypeScript로 풀스택 애플리케이션(프런트엔드와 백엔드)을 만들 때.
  • ✓클라이언트와 서버가 타입 오류 없이 통신하기를 원할 때.
  • ✓즉시 업데이트 같은 실시간 기능을 추가할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/trpc-fullstack/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/trpc-fullstack/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Next.js 앱에서 게시글을 만들고 목록을 볼 수 있는 타입 안전 API를 만들어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

서버에서 '라우터'(함수 묶음)와 '프로시저'(실제 함수)를 정의합니다. tRPC는 서버에서 사용하는 데이터 타입이 클라이언트에서도 같도록 보장하며, 모든 것을 자동으로 검증합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

tRPC Full-Stack

Overview

tRPC 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.

When to Use This Skill

  • Use when building a TypeScript full-stack app (Next.js, Remix, Express + React) where the client and server share a single repo
  • Use when you want end-to-end type safety on API calls without REST/GraphQL schema overhead
  • Use when adding real-time features (subscriptions) to an existing tRPC setup
  • Use when designing multi-step middleware (auth, rate limiting, tenant scoping) on tRPC procedures
  • Use when migrating an existing REST/GraphQL API to tRPC incrementally

Core Concepts

Routers and Procedures

A router groups related procedures (think: endpoints). Procedures are typed functions — query for reads, mutation for writes, subscription for real-time streams.

Input Validation with Zod

All procedure inputs are validated with Zod schemas. The validated, typed input is available in the procedure handler — no manual parsing.

Context

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.

Middleware

Middleware chains run before a procedure. Use them for authentication, logging, and request enrichment. They can extend the context for downstream procedures.


How It Works

Step 1: Install and Initialize

npm install @trpc/server @trpc/client @trpc/react-query @tanstack/react-query zod

Create the tRPC instance and reusable builders:

// src/server/trpc.ts
import { initTRPC, TRPCError } from '@trpc/server';
import { type Context } from './context';
import { ZodError } from 'zod';

const t = initTRPC.context<Context>().create({
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

export const router = t.router;
export const publicProcedure = t.procedure;
export const middleware = t.middleware;

Step 2: Define Two Context Factories

Next.js App Router handlers receive a fetch Request (not a Node.js NextApiRequest), so the context must be built differently depending on the call site. Define one factory per surface:

// src/server/context.ts
import { type FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';
import { auth } from '@/server/auth'; // Next-Auth v5 / your auth helper
import { db } from './db';

/**
 * Context for the HTTP handler (App Router Route Handler).
 * `opts.req` is the fetch Request — auth is resolved server-side via `auth()`.
 */
export async function createTRPCContext(opts: FetchCreateContextFnOptions) {
  const session = await auth(); // server-side auth — no req/res needed
  return { session, db, headers: opts.req.headers };
}

/**
 * Context for direct server-side callers (Server Components, RSC, cron jobs).
 * No HTTP request is involved, so we call auth() directly from the server.
 */
export async function createServerContext() {
  const session = await auth();
  return { session, db };
}

export type Context = Awaited<ReturnType<typeof createTRPCContext>>;

Step 3: Build an Auth Middleware and Protected Procedure

// src/server/trpc.ts (continued)
const enforceAuth = middleware(({ ctx, next }) => {
  if (!ctx.session?.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({
    ctx: {
      // Narrows type: session is non-null from here
      session: { ...ctx.session, user: ctx.session.user },
    },
  });
});

export const protectedProcedure = t.procedure.use(enforceAuth);

Step 4: Create Routers

// src/server/routers/post.ts
import { z } from 'zod';
import { router, publicProcedure, protectedProcedure } from '../trpc';
import { TRPCError } from '@trpc/server';

export const postRouter = router({
  list: publicProcedure
    .input(
      z.object({

…
자주 묻는 질문

'라우터'와 '프로시저'는 무엇인가요?

라우터는 함수를 정리하는 폴더와 비슷합니다. 프로시저는 데이터를 읽는(query), 데이터를 쓰는(mutation), 실시간 업데이트를 보내는(subscription) 등 실제 작업을 수행하는 함수입니다.

'미들웨어'는 무엇인가요?

함수가 실행되기 전에 하는 검사입니다. 예를 들어 사용자가 게시글을 만들기 전에 로그인했는지 확인하는 데 유용합니다.

데이터 검증은 어떻게 작동하나요?

Zod라는 도구로 데이터의 모양을 정의합니다. tRPC는 이 정의를 사용해 주고받는 데이터가 올바른지 확인하고 오류를 막습니다.

상세 정보

작성자의 원본 설명

Build end-to-end type-safe APIs with tRPC — routers, procedures, middleware, subscriptions, and Next.js/React integration patterns.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#6024
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬