Langsung ke konten
Skillpedia
API & server (backend)48k Β· #6024

trpc-fullstack

Fungsinya

tRPC Full-Stack membantu Anda membangun API (penghubung antara server dan client aplikasi) yang type-safe. Artinya, kode yang Anda tulis di server otomatis dipahami oleh client, sehingga mencegah terjadinya error.

Kapan dipakai

  • βœ“Saat membangun aplikasi full-stack (front-end dan back-end) dengan TypeScript.
  • βœ“Saat Anda ingin client dan server berkomunikasi tanpa error tipe data.
  • βœ“Saat menambahkan fitur real-time, seperti pembaruan instan.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/trpc-fullstack/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œBuat API yang type-safe untuk aplikasi Next.js saya yang memungkinkan pembuatan dan penampilan daftar postingan.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Anda mendefinisikan 'routers' (kelompok fungsi) dan 'procedures' (fungsi-fungsi aslinya) di server. tRPC memastikan tipe data di server sama dengan yang ada di client, dan memvalidasi semuanya secara otomatis.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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({

…
Pertanyaan umum

Apa itu 'routers' dan 'procedures'?

Routers seperti folder yang mengatur fungsi-fungsi Anda. Procedures adalah fungsi spesifik yang menjalankan tugas, seperti membaca data (query), menulis data (mutation), atau mengirim pembaruan real-time (subscription).

Apa itu 'middleware'?

Middleware adalah pemeriksaan yang dilakukan sebelum sebuah fungsi dijalankan. Ini berguna, misalnya, untuk memeriksa apakah pengguna sudah login sebelum mengizinkan mereka membuat postingan.

Bagaimana validasi data bekerja?

Anda menggunakan library bernama Zod untuk mendefinisikan bentuk data yang diharapkan. tRPC memakai definisi ini untuk memastikan data yang dikirim dan diterima sudah benar, sehingga mencegah error.

Detail

Deskripsi asli dari pembuat

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

repo: sickn33/agentic-awesome-skills

Popularitas

Bintang GitHub
48k
Peringkat
#6024
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa