tRPC

repository·main·Indexed 58 days ago

https://github.com/trpc/trpc

tRPC enables developers to build end-to-end typesafe APIs without schemas or code generation, providing full static typesafety and autocompletion from server to client.

Tokens
184.4K
Snippets
536
Records
668
Agent score
99%

What's inside tRPC

  1. Overview of tRPC backend development

    main

    To build a tRPC backend, you follow a structured workflow of defining your API surface and then hosting it via an adapter.

    Key steps include:

    1. Defining Routers and Procedures: Organize your API into routers and define individual procedures (queries or mutations).
    2. Setting up Context: Create a context object to provide shared data (like database connections or user sessions) to your procedures.
    3. Adding Input Validation: Use validators to ensure the data sent to your procedures is correct.
    4. Using Middlewares: Implement middlewares to add cross-cutting concerns like authentication or logging to your procedures.
    5. Hosting with Adapters: Once the API is defined, use an adapter to integrate it with a web server or platform (e.g., Express, Fastify, Next.js, or AWS Lambda).
  2. Overview of Open Graph Image Generation

    main
    Open Graph Image Generation is a tool designed to compute and generate dynamic social card images using React components. It is optimized for use with Next.js and Edge Functions, utilizing Tailwind CSS for styling. This allows developers to create highly customizable, data-driven images (like social media preview cards) that can respond to URL queries or dynamic data.
  3. Explore tRPC Extensions and Community Add-ons

    main

    The tRPC ecosystem includes various community-driven extensions to enhance development, testing, and documentation. Key categories include:

    • Documentation & UI: Tools like tRPC Docs Generator for interactive docs, tRPC-ui or tRPC Studio for manual backend testing, and trpc-to-openapi for OpenAPI/REST support.
    • Developer Tools: Browser extensions like tRPC Client Devtools and sandboxes like tRPC Playground.
    • Testing & QA: msw-trpc for Mock Service Worker support and Step CI for automated API testing.
    • CLI & Automation: trpc-cli to turn routers into type-safe CLIs, and Prisma tRPC Generator to automate router creation from Prisma schemas.
    • Security & Protocols: tRPC Shield for permission systems and trpc-to-mcp for Model Context Protocol support.
  4. Use tRPC Library Adapters and Runtime Support

    main

    tRPC can be adapted to work with different runtimes, transport layers, and state management libraries:

    • State Management: jotai-trpc (Jotai) and trpc-zustand (Zustand).
    • Runtimes & Servers: trpc-bun-adapter (Bun), trpc-koa-adapter (Koa), NestJS-tRPC (NestJS), and tRPC-uWebSockets (uWebSockets.js).
    • Transport Layers: trpc-rabbitmq (RabbitMQ), trpc-mqtt (MQTT), and trpc-redis (Redis).
    • Cloud & Serverless: @h4ad/serverless-adapter (AWS SQS/API Gateway) and cloudflare-pages-plugin-trpc (Cloudflare Pages).
    • Other Clients: tRPC-SWR (Vercel SWR) and trpc-rtk-query (Redux Toolkit Query).
  5. Find tRPC Frontend Framework Integrations

    main

    tRPC can be integrated into various frontend frameworks using community adapters:

    • Svelte: tRPC-SvelteKit for SvelteKit projects.
    • Remix: tRPC-Remix and tRPC-Remix-Call for Remix-specific client/server calls.
    • SolidJS: tRPC Client For SolidJS (with Solid Query) and tRPC API Handler For SolidStart.
    • Vue/Nuxt: tRPC-nuxt for Nuxt 3 modules.
  6. Use TanStack React Query with tRPC

    main

    The @trpc/tanstack-react-query package is the recommended integration for using tRPC with React and TanStack Query. It provides a more native TanStack Query experience by offering factories for common interfaces, including:

    • QueryKeys: For managing and generating cache keys.
    • QueryOptions: For defining query configurations.
    • MutationOptions: For defining mutation configurations.

    If you are starting a new project, use this integration instead of the classic React Query integration.

  7. Project structure of the Prisma + tRPC + WebSockets starter

    main

    When working with this starter, the following files and directories are central to the application logic:

    • ./prisma/schema.prisma: Defines the Prisma database schema.
    • ./src/api/trpc/[trpc].tsx: The tRPC response handler (API entry point).
    • ./src/server/routers: Contains the different tRPC routers that define your application's API surface.
  8. Key features of tRPC

    main

    tRPC provides several features designed for high-performance developer experience (DX):

    • Static Typesafety: Full autocompletion on the client for inputs, outputs, and errors.
    • Zero Runtime Bloat: No code generation or heavy build pipelines; the client-side footprint is tiny.
    • Extensive Ecosystem: A wide range of adapters for popular backend frameworks.
    • Real-time Support: Built-in support for Subscriptions for real-time updates.
    • Performance Optimizations: Includes Request Batching to combine multiple simultaneous requests into a single network call.
  9. What is a terminating link and which ones should I use?

    main

    A terminating link is the final link in your links array. Unlike other links, it does not call the next function. Instead, it is responsible for sending the composed tRPC operation to the server and returning an OperationResultEnvelope.

    Crucial: Your links array must contain at least one terminating link. If no terminating link is present, the tRPC operation will never be sent to the server.

    Common terminating links:

    • httpBatchLink: The recommended terminating link for most use cases.
    • httpLink
    • httpBatchStreamLink
    • httpSubscriptionLink
    • wsLink
    • localLink
  10. What is tRPC?

    main

    tRPC (TypeScript Remote Procedure Call) is a framework for building and consuming fully typesafe APIs without the need for schemas or code generation. It leverages TypeScript's type inference to keep API contracts in sync between the client and server, catching errors at build time.

    Key characteristics:

    • No Code Generation: Unlike GraphQL or OpenAPI, tRPC uses direct type inference, meaning no extra build steps are required to sync types.
    • Framework Agnostic: It can run standalone or be mounted as an endpoint on existing REST APIs via adapters.
    • Full Stack Typesafety: Provides autocompletion for inputs, outputs, and errors on the client side.
  11. What is procedure metadata and how to use it

    main

    Procedure metadata allows you to attach an optional, type-safe meta property to specific procedures. This metadata is accessible within all middleware function parameters via the opts.meta object. This is particularly useful for defining cross-cutting concerns like authentication requirements or role-based access control that middleware can then act upon.

    import { initTRPC } from '@trpc/server';
    
    type Context = { user: { name: string } | null };
    
    interface Meta {
      authRequired: boolean;
    }
    
    // Initialize tRPC with the Meta type
    export const t = initTRPC.context<Context>().meta<Meta>().create();
    
    export const appRouter = t.router({
      // Procedures here can access meta via middleware
    });
  12. Avoid bundling server code into the client

    main

    When importing your AppRouter type into a client-side file, always use the import type syntax.

    Using a standard import { AppRouter } ... will cause your bundler to pull the entire server-side code into your client bundle, which is a critical mistake that increases bundle size and can cause runtime errors.

    // ❌ WRONG: Pulls server code into client
    import { AppRouter } from '../server/router';
    
    // ✅ CORRECT: Only imports the type definition
    import type { AppRouter } from '../server/router';