本文へスキップ
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がスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/trpc-fullstack/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“投稿の作成と一覧表示ができる、型安全なAPIを私のNext.jsアプリ用に作成してください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

サーバー側で「router」(関数をまとめるグループ)と「procedure」(実際の関数)を定義します。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({

…
よくある質問

「router」と「procedure」とは何ですか?

routerは関数を整理するフォルダのようなものです。procedureは、データを読み取る(query)、データを書き込む(mutation)、リアルタイムの更新を送信する(subscription)など、個々の処理を行う関数です。

「middleware」とは何ですか?

関数が実行される前に行われるチェックのことです。たとえば、投稿を作成させる前にユーザーがログインしているかを確認する、といった用途に便利です。

データの検証はどのように行われますか?

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

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル