跳到正文
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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/trpc-fullstack/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 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({

…
常见问题

什么是“路由器”(routers)和“过程”(procedures)?

路由器就像文件夹,用来组织你的函数。过程则是执行具体任务的函数,比如读取数据(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

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能