# tRPC v11 > End-to-end typesafe APIs for TypeScript. Write procedures on the server, call them from the client with their types, and serve them on any runtime. --- Source: https://trpc.io/docs # tRPC >

End-to-end typesafe APIs made easy

weekly downloads GitHub License GitHub Stars

## Introduction tRPC lets you build & consume fully typesafe APIs without schemas or code generation. It combines concepts from [REST](https://www.sitepoint.com/rest-api/) and [GraphQL](https://graphql.org/) - if you are unfamiliar with either, take a look at the key [Concepts](https://trpc.io/docs/concepts.md). In full-stack TypeScript projects, keeping API contracts in sync between the client and server is a common pain point. tRPC does this by leveraging TypeScript's type inference directly, with no code generation step, and catches problems at build time. tRPC can run standalone or mounted as an endpoint on your existing REST API using our extensive ecosystem of adapters. ## Features - βœ…  Well-tested and production ready. - πŸ§™β€β™‚οΈ  Full static typesafety & autocompletion on the client, for inputs, outputs, and errors. - 🐎  Snappy DX - No code generation, run-time bloat, or build pipeline. - πŸƒ  Light - tRPC has zero runtime dependencies and a tiny client-side footprint. - 🐻  For new and old projects - Easy to start with or add to your existing brownfield project. - πŸ”‹  Framework agnostic - The tRPC community has built [adapters](https://trpc.io/docs/community/awesome-trpc.md#-extensions--community-add-ons) for all of the most popular frameworks. - πŸ₯ƒ  Subscriptions support - Add typesafe real-time updates to your application. - ⚑️  Request batching - Requests made at the same time can be automatically combined into one. - πŸ‘€  Examples - Check out an [example](https://trpc.io/docs/example-apps.md) to learn with or use as a starting point. ## Quick Look - [tRPC in 100 Seconds](https://www.youtube.com/watch?v=0DyAyLdVW0I) - [Matt Pocock: Learn tRPC in 5 minutes](https://www.youtube.com/watch?v=S6rcrkbsDI0) - [Chris Bautista: Making typesafe APIs easy with tRPC](https://www.youtube.com/watch?v=2LYM8gf184U) See more on the [Videos & Community Resources](https://trpc.io/docs/videos-and-community-resources.md) page. ## Try tRPC - [Minimal Example](https://stackblitz.com/github/trpc/trpc/tree/main/examples/minimal?file=server%2Findex.ts&file=client%2Findex.ts&view=editor) β€” Node.js http server + client. - [Minimal Next.js Example](https://stackblitz.com/github/trpc/examples-next-minimal-starter?file=src%2Ftrpc%2Frouters%2F_app.ts&file=src%2Fapp%2Fpage.tsx) β€” App Router: one router + page. Or use an [example app](https://trpc.io/docs/example-apps.md) to get started locally. ## Adopt tRPC ### Creating a new project Since tRPC can live inside of many different frameworks, you will first need to decide where you want to use it. On the backend, there are [adapters](https://trpc.io/docs/server/adapters.md) for a range of frameworks as well as vanilla Node.js. On the frontend, you can use our [TanStack React Query](https://trpc.io/docs/client/tanstack-react-query/setup.md) or [Next.js](https://trpc.io/docs/client/nextjs.md) integrations, a [third-party integration](https://trpc.io/docs/community/awesome-trpc.md#frontend-frameworks) for a variety of other frameworks, or the [Vanilla Client](https://trpc.io/docs/client/vanilla/setup.md), which works anywhere JavaScript runs. After choosing your stack, you can either scaffold your app using a [template](https://trpc.io/docs/example-apps.md), or start from scratch using the documentation for your chosen backend and frontend integration. ### Adding tRPC to an existing project Adding tRPC to an existing project is not significantly different from starting a new project, so the same resources apply. The main challenge is that it can feel difficult to know how to integrate tRPC with your existing application. Here are some tips: - You don't need to port all of your existing backend logic to tRPC. A common migration strategy is to initially only use tRPC for new endpoints, and only later migrate existing endpoints to tRPC. - If you're not sure where to start, check the documentation for your backend [adapter](https://trpc.io/docs/server/adapters.md) and frontend implementation, as well as the [example apps](https://trpc.io/docs/example-apps.md). - If you are looking for some inspiration of how tRPC might look as part of a larger codebase, there are some examples in [Open-source projects using tRPC](https://trpc.io/docs/community/awesome-trpc.md#-open-source-projects-using-trpc). ## Community Join us on [Discord](https://trpc.io/discord) to ask questions and share your experiences! --- Source: https://trpc.io/docs/quickstart # Quickstart > Learn how to quickly get started and setup tRPC ## Installation tRPC is split between several packages, so you can install only what you need. Make sure to install the packages you want in the proper sections of your codebase. For this quickstart guide we'll keep it simple and use the vanilla client only. For framework guides, check out [usage with React](https://trpc.io/docs/client/tanstack-react-query/setup.md) and [usage with Next.js](https://trpc.io/docs/client/nextjs.md). > [!NOTE] Requirements > - tRPC requires TypeScript >=5.7.2 > - We strongly recommend using `"strict": true` in your `tsconfig.json` as we don't officially support non-strict mode. Start off by installing the `@trpc/server` and `@trpc/client` packages: ```package-install @trpc/server @trpc/client ``` ## Your first tRPC API Let's walk through the steps of building a typesafe API with tRPC. To start, this API will contain three endpoints with these TypeScript signatures: ```ts type User = { id: string; name: string; }; userList: () => User[]; userById: (id: string) => User; userCreate: (data: { name: string }) => User; ``` Here's the file structure we'll be building. We recommend separating tRPC initialization, router definition, and server setup into distinct files to prevent cyclic dependencies: ``` . β”œβ”€β”€ server/ β”‚ β”œβ”€β”€ trpc.ts # tRPC instantiation & setup β”‚ β”œβ”€β”€ appRouter.ts # Your API logic and type export β”‚ └── index.ts # HTTP server └── client/ └── index.ts # tRPC client ``` ### 1. Create a router instance First, let's initialize the tRPC backend. It's good convention to do this in a separate file and export reusable helper functions instead of the entire tRPC object. ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; /** * Initialization of tRPC backend * Should be done only once per backend! */ const t = initTRPC.create(); /** * Export reusable router and procedure helpers * that can be used throughout the router */ export const router = t.router; export const publicProcedure = t.procedure; ``` Next, we'll initialize our main router instance, commonly referred to as `appRouter`, to which we'll later add procedures. Lastly, we need to export the type of the router which we'll later use on the client side. ```ts title="server/appRouter.ts" import { router } from './trpc'; export const appRouter = router({ // ... }); export type AppRouter = typeof appRouter; ``` ### 2. Add a query procedure Use `publicProcedure.query()` to add a query procedure to the router. The following creates a query procedure called `userList` that returns a list of users: ```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; export const appRouter = router({ userList: publicProcedure .query(async () => { const users: User[] = [{ id: '1', name: 'Katt' }]; return users; }), }); export type AppRouter = typeof appRouter; ``` ### 3. Using input parser to validate procedure inputs To implement the `userById` procedure, we need to accept input from the client. tRPC lets you define [input parsers](https://trpc.io/docs/server/validators.md) to validate and parse the input. You can define your own input parser or use a validation library of your choice, like [zod](https://zod.dev), [yup](https://github.com/jquense/yup), or [superstruct](https://docs.superstructjs.org/). You define your input parser on `publicProcedure.input()`, which can then be accessed on the resolver function as shown below:
The input parser should be a function that validates and casts the input of this procedure. It should return a strongly typed value when the input is valid or throw an error if the input is invalid.
> [!NOTE] Info > Throughout the remainder of this documentation, we will use `zod` as our validation library. ```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; export const appRouter = router({ // ... userById: publicProcedure // The input is unknown at this time. A client could have sent // us anything so we won't assume a certain data type. .input((val: unknown) => { // If the value is of type string, return it. // It will now be inferred as a string. if (typeof val === 'string') return val; // Uh oh, looks like that input wasn't a string. // We will throw an error instead of running the procedure. throw new Error(`Invalid input: ${typeof val}`); }) .query(async (opts) => { const { input } = opts; // const input: string const user: User = { id: input, name: 'Katt' }; return user; }), }); export type AppRouter = typeof appRouter; ```
The input parser can be any ZodType, e.g. z.string() or z.object({}).
```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; import { z } from 'zod'; export const appRouter = router({ // ... userById: publicProcedure .input(z.string()) .query(async (opts) => { const { input } = opts; // const input: string const user: User = { id: input, name: 'Katt' }; return user; }), }); export type AppRouter = typeof appRouter; ```
The input parser can be any YupSchema, e.g. yup.string() or yup.object({}).
> [!NOTE] Info > Throughout the remainder of this documentation, we will use `zod` as our validation library. ```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; import * as yup from 'yup'; export const appRouter = router({ // ... userById: publicProcedure .input(yup.string().required()) .query(async (opts) => { const { input } = opts; // const input: string const user: User = { id: input, name: 'Katt' }; return user; }), }); export type AppRouter = typeof appRouter; ```
The input parser can be any Valibot schema, e.g. v.string() or v.object({}).
> [!NOTE] Info > Throughout the remainder of this documentation, we will use `zod` as our validation library. ```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; import * as v from 'valibot'; export const appRouter = router({ // ... userById: publicProcedure .input(v.string()) .query(async (opts) => { const { input } = opts; // const input: string const user: User = { id: input, name: 'Katt' }; return user; }), }); export type AppRouter = typeof appRouter; ```
### 4. Adding a mutation procedure Similar to GraphQL, tRPC makes a distinction between Query and Mutation procedures. The distinction between a Query and a Mutation is primarily semantic. Queries use HTTP GET and are intended for read operations, while Mutations use HTTP POST and are intended for operations that cause side effects. Let's add a `userCreate` mutation by adding it as a new property on our router object: ```ts title="server/appRouter.ts" import { publicProcedure, router } from './trpc'; export const appRouter = router({ // ... userCreate: publicProcedure .input(z.object({ name: z.string() })) .mutation(async (opts) => { const { input } = opts; // const input: { // name: string; // } // Create the user in your DB const user: User = { id: '1', ...input }; return user; }), }); export type AppRouter = typeof appRouter; ``` ## Serving the API Now that we have defined our router, we can serve it. tRPC has first-class [adapters](https://trpc.io/docs/server/adapters.md) for many popular web servers. To keep it simple, we'll use the [`standalone`](https://trpc.io/docs/server/adapters/standalone.md) Node.js adapter here. ```ts title="server/index.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './appRouter'; const server = createHTTPServer({ router: appRouter, }); server.listen(3000); ```
See the full backend code ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; const t = initTRPC.create(); export const router = t.router; export const publicProcedure = t.procedure; ```
```ts title="server/appRouter.ts" import { z } from "zod"; import { publicProcedure, router } from "./trpc"; type User = { id: string; name: string }; export const appRouter = router({ userList: publicProcedure .query(async () => { const users: User[] = [{ id: '1', name: 'Katt' }]; return users; }), userById: publicProcedure .input(z.string()) .query(async (opts) => { const { input } = opts; const user: User = { id: input, name: 'Katt' }; return user; }), userCreate: publicProcedure .input(z.object({ name: z.string() })) .mutation(async (opts) => { const { input } = opts; const user: User = { id: '1', ...input }; return user; }), }); export type AppRouter = typeof appRouter; ```
```ts title="server/index.ts" import { createHTTPServer } from "@trpc/server/adapters/standalone"; import { appRouter } from "./appRouter"; const server = createHTTPServer({ router: appRouter, }); server.listen(3000); ```
## Using your new backend on the client Let's now move to the client-side code and embrace the power of end-to-end typesafety. When we import the `AppRouter` type for the client to use, we have achieved full typesafety for our system without leaking any implementation details to the client. ### 1. Setup the tRPC Client ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from '../server/appRouter'; // πŸ‘† **type-only** imports are stripped at build time // Pass AppRouter as a type parameter. πŸ‘‡ This lets `trpc` know // what procedures are available on the server and their input/output types. const trpc = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000', }), ], }); ``` Links in tRPC are similar to links in GraphQL, they let us control the data flow to the server. In the example above, we use the [httpBatchLink](https://trpc.io/docs/client/links/httpBatchLink.md), which automatically batches up multiple calls into a single HTTP request. For more in-depth usage of links, see the [links documentation](https://trpc.io/docs/client/links.md). ### 2. Type Inference & Autocomplete You now have access to your API procedures on the `trpc` object. Try it out! ```ts title="client/index.ts" // Inferred types const user = await trpc.userById.query('1'); // const user: User const createdUser = await trpc.userCreate.mutate({ name: 'Katt' }); // const createdUser: User ``` You can also use your autocomplete to explore the API on your client ```ts title="client/index.ts" trpc.u; ``` ## Next steps | What's next? | Description | |---|---| | [Example Apps](https://trpc.io/docs/example-apps.md) | Explore tRPC in your chosen framework | | [TanStack React Query](https://trpc.io/docs/client/tanstack-react-query/setup.md) | Recommended React integration via `@trpc/tanstack-react-query` | | [Next.js](https://trpc.io/docs/client/nextjs.md) | Usage with Next.js | | [Server Adapters](https://trpc.io/docs/server/adapters.md) | Express, Fastify, and more | | [Transformers](https://trpc.io/docs/server/data-transformers.md#using-superjson) | Use superjson to retain complex types like `Date` | --- Source: https://trpc.io/docs/skills # Agent Skills > Set up and use TanStack Intent to provide AI agent skills for tRPC tRPC ships [TanStack Intent](https://tanstack.com/intent/latest/docs/getting-started/quick-start-consumers) skills to help AI coding agents work with tRPC. When your agent works on a task that matches a skill, it loads the skill's `SKILL.md` into context. The skills ship inside `@trpc/server`, `@trpc/client`, `@trpc/tanstack-react-query`, `@trpc/next` and `@trpc/openapi`, so they're already in your `node_modules`. ## Setup ### 1. Run install The `install` command adds skill-loading guidance to your agent's config file (`AGENTS.md`, `CLAUDE.md`, etc.): ```bash npx @tanstack/intent@latest install ``` It covers the skills shipped in tRPC and your other installed packages. ### 2. Use skills in your workflow When your agent works on a task that matches a skill, it loads the corresponding `SKILL.md` into context to guide implementation. To see which skills are available: ```bash npx @tanstack/intent@latest list ``` To load one yourself, for example the server auth skill: ```bash npx @tanstack/intent@latest load @trpc/server#auth ``` ### 3. Keep skills up-to-date Skills version with library releases. When you update tRPC (e.g. `npm update @trpc/server`), you get the skills that match your installed version. ## Skills by task Each skill is generated from a page of these docs. Load one with `npx @tanstack/intent@latest load `, for example `npx @tanstack/intent@latest load @trpc/server#server-setup`. ### Build the API | Task | Skill | | --- | --- | | Initialize tRPC, define routers, procedures and context, export `AppRouter` | [`@trpc/server#server-setup`](https://trpc.io/docs/server/overview.md) | | Add middleware and reusable base procedures | [`@trpc/server#middlewares`](https://trpc.io/docs/server/middlewares.md) | | Validate inputs and outputs with Zod or another library | [`@trpc/server#validators`](https://trpc.io/docs/server/validators.md) | | Throw, format and handle errors | [`@trpc/server#error-handling`](https://trpc.io/docs/server/error-handling.md) | | Authenticate users and protect procedures | [`@trpc/server#auth`](https://trpc.io/docs/server/authorization.md) | | Call procedures from server code or tests | [`@trpc/server#server-side-calls`](https://trpc.io/docs/server/server-side-calls.md) | | Set HTTP cache headers on responses | [`@trpc/server#caching`](https://trpc.io/docs/server/caching.md) | | Accept `FormData`, files and binary inputs | [`@trpc/server#non-json-content-types`](https://trpc.io/docs/server/non-json-content-types.md) | | Stream real-time updates over SSE or WebSockets | [`@trpc/server#subscriptions`](https://trpc.io/docs/server/subscriptions.md) | | Send `Date`, `Map`, `Set` and other rich types with superjson | [`@trpc/client#superjson`](https://trpc.io/docs/server/data-transformers.md) | | Split the API across several services | [`@trpc/server#service-oriented-architecture`](https://trpc.io/docs/server/service-oriented-architecture.md) | ### Serve the API | Task | Skill | | --- | --- | | Node.js HTTP server, the simplest setup | [`@trpc/server#adapter-standalone`](https://trpc.io/docs/server/adapters/standalone.md) | | Express | [`@trpc/server#adapter-express`](https://trpc.io/docs/server/adapters/express.md) | | Fastify | [`@trpc/server#adapter-fastify`](https://trpc.io/docs/server/adapters/fastify.md) | | AWS Lambda behind API Gateway or a Function URL | [`@trpc/server#adapter-aws-lambda`](https://trpc.io/docs/server/adapters/aws-lambda.md) | | Fetch API and edge runtimes: Cloudflare Workers, Deno, Vercel Edge, Astro, Remix | [`@trpc/server#adapter-fetch`](https://trpc.io/docs/server/adapters/fetch.md) | ### Call the API | Task | Skill | | --- | --- | | Create a TypeScript client, infer types, handle errors | [`@trpc/client#client-setup`](https://trpc.io/docs/client/vanilla/setup.md) | | Configure links: batching, streaming, splitting, WebSockets, SSE, retries | [`@trpc/client#links`](https://trpc.io/docs/client/links.md) | | Use tRPC with TanStack React Query | [`@trpc/tanstack-react-query#react-query-setup`](https://trpc.io/docs/client/tanstack-react-query/setup.md) | | Migrate from the classic `@trpc/react-query` client | [`@trpc/tanstack-react-query#react-query-classic-migration`](https://trpc.io/docs/client/tanstack-react-query/migrating.md) | | Next.js App Router, including server components | [`@trpc/next#nextjs-app-router`](https://trpc.io/docs/client/nextjs/app-router-setup.md) | | Next.js Pages Router, SSR and SSG | [`@trpc/next#nextjs-pages-router`](https://trpc.io/docs/client/nextjs/pages-router/setup.md) | | Generate an OpenAPI spec and a REST client | [`@trpc/openapi#openapi`](https://trpc.io/docs/openapi.md) | ## Learn more For full documentation on TanStack Intent, see the [Quick Start for Consumers](https://tanstack.com/intent/latest/docs/getting-started/quick-start-consumers) guide. --- Source: https://trpc.io/docs/concepts # Concepts > ## What is RPC? What mindset should I adopt? ### It's just functions RPC is short for "Remote Procedure Call". It is a way of calling functions on one computer (the server) from another computer (the client). With traditional HTTP/REST APIs, you call a URL and get a response. With RPC, you call a function and get a response. ```ts // HTTP/REST const res = await fetch('/api/users/1'); const user = await res.json(); // RPC const user = await api.users.getById({ id: 1 }); ``` tRPC (TypeScript Remote Procedure Call) is one implementation of RPC, designed for TypeScript monorepos. It has its own flavor, but is RPC at its heart. ### Don't think about HTTP/REST implementation details If you inspect the network traffic of a tRPC app, you'll see that it's fairly standard HTTP requests and responses, but you don't need to think about the implementation details while writing your application code. You call functions, and tRPC takes care of everything else. You should ignore details like HTTP Verbs, since they carry meaning in REST APIs but, in RPC, form part of your function names instead, for instance: `getUser(id)` instead of `GET /users/:id`. ## Vocabulary Below are some terms that are used frequently in the tRPC ecosystem. We'll be using these throughout the documentation, so it's good to get familiar with them. Most of these concepts also have their own pages in the documentation.
Term Description
Procedure β†— API endpoint - can be a query, mutation , or subscription .
Query A procedure that gets some data.
Mutation A procedure that creates, updates, or deletes some data.
Subscription β†— A procedure that creates a persistent connection and listens to changes.
Router β†— A collection of procedures (and/or other routers) under a shared namespace.
Context β†— Stuff that every procedure can access. Commonly used for things like session state and database connections.
Middleware β†— A function that can run code before and after a procedure . Can modify context .
Validation β†— "Does this input data contain the right stuff?"
--- Source: https://trpc.io/docs/videos-and-community-resources # Videos and Community Resources > ### tRPC in 100 Seconds ### Matt Pocock: Learn tRPC in 5 minutes ### Chris Bautista: Making typesafe APIs easy with tRPC 15 minute video explaining the basics of tRPC and showing an example app. ### How tRPC really works 20 minute video showing how data flows in tRPC and explaining some core concepts. This video uses Next.js, but the concepts apply to any implementation. ### T3: tRPC, Prisma and NextAuth Done Right 45 minute tutorial by Jack Herrington that builds an app with Next.js, tRPC, Prisma, and NextAuth.js. ### DevTools.FM Episode 21 60 minute podcast episode with Alex, the creator of tRPC. --- Source: https://trpc.io/docs/example-apps # Example Apps > Example apps built with tRPC ## Official ### Node.js | Example | Description | Links | | --------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Minimal** | Hello world server and client | [Source](https://github.com/trpc/trpc/tree/main/examples/minimal) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/minimal) | | **Standalone Server** | Custom HTTP server with WebSocket support | [Source](https://github.com/trpc/trpc/tree/main/examples/standalone-server) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/standalone-server) | | **Content Types** | Binary, text, and JSON content type handling | [Source](https://github.com/trpc/trpc/tree/main/examples/minimal-content-types) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/minimal-content-types) | | **Lazy Loading** | Lazy-loading routes with dynamic imports | [Source](https://github.com/trpc/trpc/tree/main/examples/lazy-load) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/lazy-load) | | **SOA** | Service-oriented architecture with multiple tRPC services | [Source](https://github.com/trpc/trpc/tree/main/examples/soa) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/soa) | | **OpenAPI Codegen** | Generate a typed REST client from a tRPC router via OpenAPI | [Source](https://github.com/trpc/trpc/tree/main/examples/openapi-codegen) | | **Kitchen Sink** | Comprehensive examples covering many features | [Source](https://github.com/trpc/examples-kitchen-sink) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/examples-kitchen-sink) | ### React | Example | Description | Links | | ------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Minimal React** | Node.js server + Vite React client monorepo | [Source](https://github.com/trpc/trpc/tree/main/examples/minimal-react) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/minimal-react) | | **Express + React** | Express server with React client using React Query | [Source](https://github.com/trpc/trpc/tree/main/examples/express-server) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/express-server) | ### Next.js | Example | Description | Links | | --------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Prisma Starter** | Full-stack with Prisma, E2E testing, ESLint, and Tailwind CSS | [Source](https://github.com/trpc/examples-next-prisma-starter) Β· [Demo](https://nextjs.trpc.io) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/examples-next-prisma-starter) | | **Minimal Starter** | Bare-bones Next.js App Router + tRPC setup | [Source](https://github.com/trpc/examples-next-minimal-starter) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/examples-next-minimal-starter) | | **TodoMVC** | TodoMVC with SSG and Prisma | [Source](https://github.com/trpc/examples-next-prisma-todomvc) Β· [Demo](https://todomvc.trpc.io) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/examples-next-prisma-todomvc) | | **WebSockets** | Prisma, WebSockets, NextAuth, and subscriptions | [Source](https://github.com/trpc/examples-next-prisma-websockets-starter) Β· [Demo](https://websockets.trpc.io) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/examples-next-prisma-websockets-starter) | | **SSE Chat** | Streaming chat with Server-Sent Events and Drizzle ORM | [Source](https://github.com/trpc/trpc/tree/main/examples/tanstack-start-sse-chat) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/tanstack-start-sse-chat) | | **Big Router** | Large router with code generation | [Source](https://github.com/trpc/trpc/tree/main/examples/next-big-router) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/next-big-router) | | **Edge Runtime** | tRPC on Next.js Edge Runtime | [Source](https://github.com/trpc/trpc/tree/main/examples/next-edge-runtime) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/next-edge-runtime) | | **FormData** | Form handling with React Hook Form and Zod | [Source](https://github.com/trpc/trpc/tree/main/examples/next-formdata) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/next-formdata) | | **WebSocket Encoder** | WebSockets with MessagePack binary encoding | [Source](https://github.com/trpc/trpc/tree/main/examples/next-websockets-encoder) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/next-websockets-encoder) | ### Serverless | Example | Description | Links | | ------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Lambda + API Gateway** | AWS Lambda with API Gateway | [Source](https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/lambda-api-gateway) | | **Lambda Streaming** | AWS Lambda + API Gateway with streaming responses | [Source](https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway-streaming) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/lambda-api-gateway-streaming) | | **Lambda Function URLs** | AWS Lambda with Function URLs | [Source](https://github.com/trpc/trpc/tree/main/examples/lambda-url) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/lambda-url) | | **Cloudflare Workers** | tRPC on Cloudflare Workers | [Source](https://github.com/trpc/trpc/tree/main/examples/cloudflare-workers) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/cloudflare-workers) | | **Vercel Edge Runtime** | tRPC on Vercel Edge Runtime | [Source](https://github.com/trpc/trpc/tree/main/examples/vercel-edge-runtime) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/vercel-edge-runtime) | | **Deno Deploy** | tRPC client on Deno Deploy | [Source](https://github.com/trpc/trpc/tree/main/examples/deno-deploy) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/deno-deploy) | ### Other Ecosystems | Example | Description | Links | | ----------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Express** | Minimal Express + tRPC setup | [Source](https://github.com/trpc/trpc/tree/main/examples/express-minimal) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/express-minimal) | | **Fastify** | Fastify with WebSocket support | [Source](https://github.com/trpc/trpc/tree/main/examples/fastify-server) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/fastify-server) | | **Bun** | tRPC server and client on Bun | [Source](https://github.com/trpc/trpc/tree/main/examples/bun) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/bun) | | **Nuxt 3** | Nuxt 3 integration with trpc-nuxt | [Source](https://github.com/trpc/trpc/tree/main/examples/nuxt) Β· [CodeSandbox](https://codesandbox.io/s/github/trpc/trpc/tree/main/examples/nuxt) | ## Community > [!NOTE] > Community examples are maintained by their respective authors and may not be updated for the latest tRPC version. Check each project's README for version compatibility. ### Frameworks | Example | Description | Links | | ---------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | **create-t3-turbo** | T3 Stack with Expo and Turborepo | [Source](https://github.com/t3-oss/create-t3-turbo) Β· [CodeSandbox](https://codesandbox.io/s/github/t3-oss/create-t3-turbo) | | **SvelteKit + Prisma** | SvelteKit integration with Prisma | [Source](https://github.com/icflorescu/trpc-sveltekit-example) Β· [CodeSandbox](https://codesandbox.io/s/github/icflorescu/trpc-sveltekit-example) | ### Integrations | Example | Description | Links | | ------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Separate BE/FE** | Separate backend and frontend repositories | [Backend (Express)](https://github.com/mkosir/trpc-api-boilerplate) Β· [Frontend (Vite)](https://github.com/mkosir/trpc-fe-boilerplate-vite) | --- Source: https://trpc.io/docs/server/overview # Backend Usage > This section covers everything you need to set up and configure your tRPC backend. You'll learn how to define [routers](https://trpc.io/docs/server/routers.md) and [procedures](https://trpc.io/docs/server/procedures.md), set up [context](https://trpc.io/docs/server/context.md), add [input validation](https://trpc.io/docs/server/validators.md), and use [middlewares](https://trpc.io/docs/server/middlewares.md) to extend your API. Once your API is defined, you can host it using one of the available [adapters](https://trpc.io/docs/server/adapters.md) for platforms like Express, Fastify, Next.js, AWS Lambda, and more. --- Source: https://trpc.io/docs/server/routers # Define Routers > To begin building your tRPC-based API, you'll first need to define your router. Once you've mastered the fundamentals, you can [customize your routers](#advanced-usage) for more advanced use cases. ## Initialize tRPC You should initialize tRPC **exactly once** per application. Multiple instances of tRPC will cause issues: for example, `t.mergeRouters()` throws if the routers come from different instances that each set a [transformer](https://trpc.io/docs/server/data-transformers.md) or [error formatter](https://trpc.io/docs/server/error-formatting.md). Create `t` in one file and import your procedures and `router` from it everywhere. ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; // You can use any variable name you like. // We use t to keep things simple. const t = initTRPC.create(); export const router = t.router; export const publicProcedure = t.procedure; ``` You'll notice we are exporting certain methods of the `t` variable here rather than `t` itself. This is to establish a certain set of procedures that we will use idiomatically in our codebase. ## Defining a router Next, let's define a router with a procedure to use in our application. We have now created an API "endpoint". In order for these endpoints to be exposed to the frontend, your [Adapter](https://trpc.io/docs/server/adapters.md) should be configured with your `appRouter` instance. ```ts title="server/_app.ts" import { publicProcedure, router } from './trpc'; const appRouter = router({ greeting: publicProcedure.query(() => 'hello tRPC v11!'), }); // Export only the type of a router! // This prevents us from importing server code on the client. export type AppRouter = typeof appRouter; ``` On the client, import it with `import type { AppRouter } from '...'` and never import the `appRouter` value: a type-only import is always erased, so your server code can't end up in the client bundle. Procedures can't be named `then`, `call` or `apply`: `router()` throws if you use these names. ## Defining an inline sub-router {#inline-sub-router} When you define an inline sub-router, you can represent your router as a plain object. In the below example, `nested1` and `nested2` are equal: ```ts title="server/_app.ts" import * as trpc from '@trpc/server'; import { publicProcedure, router } from './trpc'; const appRouter = router({ // Using the router() method nested1: router({ proc: publicProcedure.query(() => '...'), }), // Using an inline sub-router nested2: { proc: publicProcedure.query(() => '...'), }, }); ``` ## Advanced usage When initializing your router, tRPC allows you to: - Setup [request contexts](https://trpc.io/docs/server/context.md) - Assign [metadata](https://trpc.io/docs/server/metadata.md) to procedures - [Format](https://trpc.io/docs/server/error-formatting.md) and [handle](https://trpc.io/docs/server/error-handling.md) errors - [Transform data](https://trpc.io/docs/server/data-transformers.md) as needed - Customize the [runtime configuration](#runtime-configuration) You can use method chaining to customize your `t`-object on initialization. For example: ```ts const t = initTRPC.context().meta().create({ /* [...] */ }); ``` ### Runtime Configuration ```ts interface RootConfig { /** * Use a data transformer * @see https://trpc.io/docs/v11/data-transformers */ transformer: DataTransformerOptions; /** * Use custom error formatting * @see https://trpc.io/docs/v11/error-formatting */ errorFormatter: ErrorFormatter; /** * Allow `@trpc/server` to run in non-server environments * @warning **Use with caution**, this should likely mainly be used within testing. * @default false */ allowOutsideOfServer: boolean; /** * Is this a server environment? * @warning **Use with caution**, this should likely mainly be used within testing. * @default typeof window === 'undefined' || 'Deno' in window || process.env.NODE_ENV === 'test' */ isServer: boolean; /** * Is this development? * Will be used to decide if the API should return stack traces * @default process.env.NODE_ENV !== 'production' */ isDev: boolean; } ``` --- Source: https://trpc.io/docs/server/procedures # Define Procedures > A procedure is a function which is exposed to the client, it can be one of: - a `Query` - used to fetch data, generally does not change any data - a `Mutation` - used to send data, often for create/update/delete purposes - a `Subscription` - you might not need this, and we have [dedicated documentation](https://trpc.io/docs/server/subscriptions.md) Procedures in tRPC are very flexible primitives to create backend functions. They use an immutable builder pattern, which means you can [create reusable base procedures](#reusable-base-procedures) that share functionality among multiple procedures. ## Writing procedures The `t` object you create during tRPC setup returns an initial `t.procedure` which all other procedures are built on: ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC.context<{ signGuestBook: () => Promise }>().create(); export const router = t.router; export const publicProcedure = t.procedure; const appRouter = router({ // Queries are the best place to fetch data hello: publicProcedure.query(() => { return { message: 'hello world', }; }), // Mutations are the best place to do things like updating a database goodbye: publicProcedure.mutation(async (opts) => { await opts.ctx.signGuestBook(); return { message: 'goodbye!', }; }), }); ``` ## Reusable "Base Procedures" {#reusable-base-procedures} As a general pattern we recommend you rename and export `t.procedure` as `publicProcedure`, which then makes room for you to create other named procedures for specific use cases and export those too. This pattern is called "base procedures" and is a key pattern for code and behaviour re-use in tRPC; every application is likely to need it. In the below code, we're using reusable base procedures to build common use-cases for our app - we're making a reusable base procedures for logged in users (`authedProcedure`) & another base procedure that takes an `organizationId` and validates that a user is part of that organization. > This is a simplified example; in practice you may want to use some combination of [Headers](https://trpc.io/docs/client/headers.md), [Context](https://trpc.io/docs/server/context.md), [Middleware](https://trpc.io/docs/server/middlewares.md), and [Metadata](https://trpc.io/docs/server/metadata.md), to [authenticate](https://en.wikipedia.org/wiki/Authentication) and [authorize](https://trpc.io/docs/server/authorization.md) your users. ```ts import { initTRPC, TRPCError } from '@trpc/server'; import { z } from 'zod'; type Organization = { id: string; name: string; }; type Membership = { role: 'ADMIN' | 'MEMBER'; Organization: Organization; }; type User = { id: string; memberships: Membership[]; }; type Context = { /** * User is nullable */ user: User | null; }; const t = initTRPC.context().create(); export const publicProcedure = t.procedure; // procedure that asserts that the user is logged in export const authedProcedure = t.procedure.use(async function isAuthed(opts) { const { ctx } = opts; // `ctx.user` is nullable if (!ctx.user) { // (property) user: User | null throw new TRPCError({ code: 'UNAUTHORIZED' }); } return opts.next({ ctx: { // βœ… user value is known to be non-null now user: ctx.user, }, }); }); // procedure that asserts a user is a member of a specific organization export const organizationProcedure = authedProcedure .input(z.object({ organizationId: z.string() })) .use(function isMemberOfOrganization(opts) { const membership = opts.ctx.user.memberships.find( (m) => m.Organization.id === opts.input.organizationId, ); if (!membership) { throw new TRPCError({ code: 'FORBIDDEN', }); } return opts.next({ ctx: { Organization: membership.Organization, }, }); }); export const appRouter = t.router({ whoami: authedProcedure.query(async (opts) => { // user is non-nullable here const { ctx } = opts; // const ctx: { // user: User; // } return ctx.user; }), addMember: organizationProcedure .input( z.object({ email: z.string().email(), }), ) .mutation((opts) => { // ctx contains the non-nullable user & the organization being queried const { ctx } = opts; // const ctx: { // user: User; // Organization: Organization; // } // input includes the validated email of the user being invited & the validated organizationId const { input } = opts; // const input: { // organizationId: string; // email: string; // } return '...'; }), }); ``` ## Inferring the options type of a "Base Procedure" {#inferProcedureBuilderResolverOptions} In addition to being able to [infer the input and output types](https://trpc.io/docs/client/vanilla/infer-types.md#inferring-input--output-types) of a procedure, you can also infer the options type of a specific procedure builder (or base procedure) using `inferProcedureBuilderResolverOptions`. This type helper is useful for declaring a type to a function's parameters. Like for example, separating the procedure's handler (main execution code) from its definition at the router, or for creating a helper function that works with multiple procedures. ```ts async function getMembersOfOrganization( opts: inferProcedureBuilderResolverOptions, ) { // input and ctx are now correctly typed! const { ctx, input } = opts; return await prisma.user.findMany({ where: { membership: { organizationId: ctx.Organization.id, }, }, }); } export const appRouter = t.router({ listMembers: organizationProcedure.query(async (opts) => { // use helper function! const members = await getMembersOfOrganization(opts); return members; }), }); ``` ## Subscriptions For information on subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions.md). --- Source: https://trpc.io/docs/server/context # Context > Your context holds data that all of your tRPC procedures will have access to, and is a great place to put things like authentication information. Setting up the context is done in 2 steps, defining the type during initialization and then creating the runtime context for each request. ## Defining the context type When initializing tRPC using `initTRPC`, you should pipe `.context()` to the `initTRPC` builder function before calling `.create()`. The type `TContext` can either be inferred from a function's return type or be explicitly defined. This will make sure your context is properly typed in your procedures and middlewares. ```ts import { initTRPC } from '@trpc/server'; import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; export const createContext = async (opts: CreateHTTPContextOptions) => { // Example: extract a session token from the request headers const token = opts.req.headers['authorization']; return { token, }; }; export type Context = Awaited>; const t = initTRPC.context().create(); t.procedure.use((opts) => { opts.ctx; // (property) ctx: { // token: string | undefined; // } return opts.next(); }); ``` ## Creating the context The `createContext()` function must be passed to the handler mounting your appRouter. The handler may use HTTP or a [server-side call](https://trpc.io/docs/server/server-side-calls.md). `createContext()` is called once per request, so all procedures within a single batched request share the same context. ```ts // 1. HTTP request import { createHTTPHandler } from '@trpc/server/adapters/standalone'; import { createContext } from './context'; import { appRouter } from './router'; const handler = createHTTPHandler({ router: appRouter, createContext, }); ``` ```ts // 2. Server-side call import { createContext } from './context'; import { createCaller } from './router'; const caller = createCaller(await createContext()); ``` ```ts // 3. Prefetching on the server, see /docs/client/tanstack-react-query/server-components import { dehydrate, QueryClient } from '@tanstack/react-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import { createContext } from './context'; import { appRouter } from './router'; // Call once per request, e.g. in `getServerSideProps` export async function prefetchGreeting() { const queryClient = new QueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: await createContext(), queryClient, }); await queryClient.prefetchQuery(trpc.greeting.queryOptions()); return dehydrate(queryClient); } ``` ## Example code ```ts // ------------------------------------------------- // @filename: context.ts // ------------------------------------------------- import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; /** * Creates context for an incoming request * @see https://trpc.io/docs/v11/context */ export async function createContext(opts: CreateHTTPContextOptions) { const token = opts.req.headers['authorization']; // In a real app, you would verify the token and look up the user const user = token ? { email: 'user@example.com' } : null; return { user, }; } export type Context = Awaited>; // ------------------------------------------------- // @filename: trpc.ts // ------------------------------------------------- import { initTRPC, TRPCError } from '@trpc/server'; import { Context } from './context'; const t = initTRPC.context().create(); export const router = t.router; /** * Unprotected procedure */ export const publicProcedure = t.procedure; /** * Protected procedure */ export const protectedProcedure = t.procedure.use(function isAuthed(opts) { if (!opts.ctx.user?.email) { throw new TRPCError({ code: 'UNAUTHORIZED', }); } return opts.next({ ctx: { // Infers the `user` as non-nullable user: opts.ctx.user, }, }); }); ``` ## Inner and outer context In some scenarios it could make sense to split up your context into "inner" and "outer" functions. **Inner context** is where you define context which doesn’t depend on the request, e.g. your database connection. You can use this function for integration testing or [server-side calls](https://trpc.io/docs/server/server-side-calls.md), where you don’t have a request object. Whatever is defined here will **always** be available in your procedures. > [!NOTE] Tradeoff for large clients in `createContextInner` > Putting a database client such as `prisma` on `createContextInner` is convenient and common, but large generated clients (like Prisma) can increase type-checking overhead because they become part of your context type across procedures. > > If that overhead becomes noticeable, an alternative is to keep context smaller and import the client directly at call sites where needed. **Outer context** is where you define context which depends on the request, e.g. for the user's session. Whatever is defined here is only available for procedures that are called via HTTP. ### Example for inner & outer context ```ts import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; import { getSessionFromCookie, type Session } from './auth'; import { db } from './db'; /** * Defines your inner context shape. * Add fields here that the inner context brings. */ interface CreateInnerContextOptions { session: Session | null; } /** * Inner context. Will always be available in your procedures, in contrast to the outer context. * * Also useful for: * - testing, so you don't have to mock `req`/`res` * - server-side calls where we don't have `req`/`res` * * @see https://trpc.io/docs/v11/context#inner-and-outer-context */ export async function createContextInner(opts?: CreateInnerContextOptions) { return { db, session: opts?.session, }; } /** * Outer context. Used in the routers and will e.g. bring `req` & `res` to the context as "not `undefined`". * * @see https://trpc.io/docs/v11/context#inner-and-outer-context */ export async function createContext(opts: CreateHTTPContextOptions) { const session = getSessionFromCookie(opts.req); const contextInner = await createContextInner({ session }); return { ...contextInner, req: opts.req, res: opts.res, }; } export type Context = Awaited>; // The usage in your router is the same as the example above. ``` It is important to infer your `Context` from the **inner** context, as only what is defined there is really always available in your procedures. If you don't want to check `req` or `res` for `undefined` in your procedures all the time, you could build a small reusable procedure for that: ```ts export const apiProcedure = publicProcedure.use((opts) => { if (!opts.ctx.req || !opts.ctx.res) { throw new Error('You are missing `req` or `res` in your call.'); } return opts.next({ ctx: { // We overwrite the context with the truthy `req` & `res`, which will also overwrite the types used in your procedure. req: opts.ctx.req, res: opts.ctx.res, }, }); }); ``` --- Source: https://trpc.io/docs/server/validators # Input & Output Validators > tRPC procedures may define validation logic for their input and/or output, and validators are also used to infer the types of inputs and outputs (using the [Standard Schema](https://standardschema.dev) interface if available, or custom interfaces for supported validators if not). We have first class support for many popular validators, and you can [integrate validators](#contributing-your-own-validator-library) which we don't directly support. ## Input Validators By defining an input validator, tRPC can check that a procedure call is correct and return a validation error if not. To set up an input validator, use the `procedure.input()` method: ```ts export const appRouter = t.router({ hello: publicProcedure .input( z.object({ name: z.string(), }), ) .query((opts) => { const name = opts.input.name; // const name: string return { greeting: `Hello ${opts.input.name}`, }; }), }); ``` If the input fails validation, the procedure doesn't run and the call fails with a `BAD_REQUEST` error whose `cause` is the error your validator threw. To send structured validation errors (e.g. Zod's field errors) to the client, use [error formatting](https://trpc.io/docs/server/error-formatting.md). ### Input Merging `.input()` can be stacked to build more complex types, which is particularly useful when you want to utilise some common input to a collection of procedures in a [middleware](https://trpc.io/docs/server/middlewares.md). Input merging works by spreading object properties together. This means only **object types** can be chained β€” non-object types (like `z.string()`) cannot be merged. If two chained `.input()` calls define the same property, the later one takes precedence. An optional input (e.g. `z.object({...}).optional()`) can only be chained after another optional input. ```ts const baseProcedure = t.procedure .input(z.object({ townName: z.string() })) .use((opts) => { const input = opts.input; // const input: { // townName: string; // } console.log(`Handling request with user from: ${input.townName}`); return opts.next(); }); export const appRouter = t.router({ hello: baseProcedure .input( z.object({ name: z.string(), }), ) .query((opts) => { const input = opts.input; // const input: { // townName: string; // name: string; // } return { greeting: `Hello ${input.name}, my friend from ${input.townName}`, }; }), }); ``` ## Output Validators Validating outputs is not always as important as defining inputs, since tRPC gives you automatic type-safety by inferring the return type of your procedures. Some reasons to define an output validator include: - Checking that data returned from untrusted sources is correct - Ensure that you are not returning more data to the client than necessary > [!NOTE] Info > If output validation fails, the server will respond with an `INTERNAL_SERVER_ERROR`. The client receives the value your output validator returns, so a schema that strips unknown keys (like `z.object()`) also strips them from the response. ```ts import { z } from 'zod'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .output( z.object({ greeting: z.string(), }), ) .query((opts) => { return { greeting: 'hello world', // (property) greeting: string }; }), }); ``` ### Output validation of subscriptions Since subscriptions are async iterators, you can use the same validation techniques as above. Have a look at the [subscriptions guide](https://trpc.io/docs/server/subscriptions.md#output-validation) for more information. ## The most basic validator: a function You can define a validator without any 3rd party dependencies, with a function. > [!NOTE] Info > We don't recommend making a custom validator unless you have a specific need, but it's important to understand that there's no magic here - it's _just typescript_! > > In most cases we recommend you use a [validation library](#library-integrations) ```ts import { initTRPC } from '@trpc/server'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input((value): string => { if (typeof value === 'string') { return value; } throw new Error('Input is not a string'); }) .output((value): string => { if (typeof value === 'string') { return value; } throw new Error('Output is not a string'); }) .query((opts) => { const { input } = opts; // const input: string return `hello ${input}`; }), }); export type AppRouter = typeof appRouter; ``` ## Library integrations tRPC works out of the box with a number of popular validation and parsing libraries, including any library conforming to [Standard Schema](https://standardschema.dev). The below are some examples of usage with validators which we officially maintain support for. ### With [Zod](https://github.com/colinhacks/zod) Zod is our default recommendation, it has a strong ecosystem which makes it a great choice to use in multiple parts of your codebase. If you have no opinion of your own and want a powerful library which won't limit future needs, Zod is a great choice. ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input( z.object({ name: z.string(), }), ) .output( z.object({ greeting: z.string(), }), ) .query(({ input }) => { // (parameter) input: { // name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [Yup](https://github.com/jquense/yup) ```ts import { initTRPC } from '@trpc/server'; import * as yup from 'yup'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input( yup.object({ name: yup.string().required(), }), ) .output( yup.object({ greeting: yup.string().required(), }), ) .query(({ input }) => { // (parameter) input: { // name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [Superstruct](https://github.com/ianstormtaylor/superstruct) ```ts import { initTRPC } from '@trpc/server'; import { object, string } from 'superstruct'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input(object({ name: string() })) .output(object({ greeting: string() })) .query(({ input }) => { // (parameter) input: { // name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [scale-ts](https://github.com/paritytech/scale-ts) ```ts import { initTRPC } from '@trpc/server'; import * as $ from 'scale-codec'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input($.object($.field('name', $.str))) .output($.object($.field('greeting', $.str))) .query(({ input }) => { // (parameter) input: { // readonly name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [Typia](https://typia.io/docs/utilization/trpc/) ```ts import { initTRPC } from '@trpc/server'; import typia from 'typia'; import { v4 } from 'uuid'; import { IBbsArticle } from '../structures/IBbsArticle'; const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ store: publicProcedure .input(typia.createAssert()) .output(typia.createAssert()) .query(({ input }) => { return { id: v4(), writer: input.writer, title: input.title, body: input.body, created_at: new Date().toString(), }; }), }); export type AppRouter = typeof appRouter; ``` ### With [ArkType](https://github.com/arktypeio/arktype#trpc) ```ts import { initTRPC } from '@trpc/server'; import { type } from 'arktype'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure.input(type({ name: 'string' })).query((opts) => { return { greeting: `hello ${opts.input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [effect](https://effect.website/docs/schema/introduction/) This example uses Effect 4. On Effect 3.13 or later, use `Schema.standardSchemaV1` in place of `Schema.toStandardSchemaV1`. ```ts import { initTRPC } from '@trpc/server'; import { Schema } from 'effect'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input(Schema.toStandardSchemaV1(Schema.Struct({ name: Schema.String }))) .output(Schema.toStandardSchemaV1(Schema.Struct({ greeting: Schema.String }))) .query(({ input }) => { // (parameter) input: { // readonly name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [Valibot](https://github.com/fabian-hiller/valibot) ```ts import { initTRPC } from '@trpc/server'; import * as v from 'valibot'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input(v.object({ name: v.string() })) .output(v.object({ greeting: v.string() })) .query(({ input }) => { // (parameter) input: { // name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [Sury](https://github.com/DZakh/sury) ```ts import { initTRPC } from '@trpc/server'; import * as S from 'sury'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input(S.schema({ name: S.string })) .output(S.schema({ greeting: S.string })) .query(({ input }) => { // (parameter) input: { // name: string; // } return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [@robolex/sure](https://github.com/robolex-app/public_ts) You're able to define your own Error types and error throwing function if necessary. As a convenience `@robolex/sure` provides [sure/src/err.ts](https://github.com/robolex-app/public_ts/blob/main/packages/sure/src/err.ts): ```ts // sure/src/err.ts export const err = (schema: any) => (input: any) => { const [good, result] = schema(input); if (good) return result; throw result; }; ``` ```ts import { err, object, string } from '@robolex/sure'; import { initTRPC } from '@trpc/server'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input( err( object({ name: string, }), ), ) .output( err( object({ greeting: string, }), ), ) .query(({ input }) => { // ^? return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ### With [TypeBox](https://github.com/sinclairzx81/typebox) ```ts import { Type } from '@sinclair/typebox'; import { initTRPC } from '@trpc/server'; import { wrap } from '@typeschema/typebox'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure .input(wrap(Type.Object({ name: Type.String() }))) .output(wrap(Type.Object({ greeting: Type.String() }))) .query(({ input }) => { return { greeting: `hello ${input.name}`, }; }), }); export type AppRouter = typeof appRouter; ``` ## Contributing your own Validator Library If you work on a validator library which supports tRPC usage, please feel free to open a PR for this page with equivalent usage to the other examples here, and a link to your docs. Integration with tRPC in most cases is as simple as meeting one of several existing type interfaces. Conforming to [Standard Schema](https://standardschema.dev) is recommended, but in some cases we may accept a PR to add a new supported interface. Feel free to open an issue for discussion. You can check the existing supported interfaces and functions for parsing/validation [in code](https://github.com/trpc/trpc/blob/main/packages/server/src/unstable-core-do-not-import/parser.ts). --- Source: https://trpc.io/docs/server/middlewares # Middlewares > You can add middleware(s) to a procedure with the `t.procedure.use()` method. The middleware(s) will wrap the invocation of the procedure and must call `opts.next()` and return its result. ## Authorization In the example below, any call to a `adminProcedure` will ensure that the user is an "admin" before executing. ```ts import { TRPCError, initTRPC } from '@trpc/server'; interface Context { user?: { id: string; isAdmin: boolean; // [..] }; } const t = initTRPC.context().create(); export const publicProcedure = t.procedure; export const router = t.router; export const adminProcedure = publicProcedure.use(async (opts) => { const { ctx } = opts; if (!ctx.user?.isAdmin) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return opts.next({ ctx: { user: ctx.user, }, }); }); ``` ```ts import { adminProcedure, publicProcedure, router } from './trpc'; const adminRouter = router({ secretPlace: adminProcedure.query(() => 'a key'), }); export const appRouter = router({ foo: publicProcedure.query(() => 'bar'), admin: adminRouter, }); ``` > [!TIP] > See [Error Handling](https://trpc.io/docs/server/error-handling.md) to learn more about the `TRPCError` thrown in the above example. ## Logging In the example below timings for queries are logged automatically. ```ts export const loggedProcedure = publicProcedure.use(async (opts) => { const start = Date.now(); const result = await opts.next(); const durationMs = Date.now() - start; const meta = { path: opts.path, type: opts.type, durationMs }; result.ok ? console.log('OK request timing:', meta) : console.error('Non-OK request timing', meta); return result; }); ``` ```ts import { loggedProcedure, router } from './trpc'; export const appRouter = router({ foo: loggedProcedure.query(() => 'bar'), abc: loggedProcedure.query(() => 'def'), }); ``` ## Context Extension "Context Extension" enables middlewares to dynamically add and override keys on a base procedure's context in a typesafe manner. Below we have an example of a middleware that changes properties of a context, the changes are then available to all chained consumers, such as other middlewares and procedures: ```ts type Context = { // user is nullable user?: { id: string; }; }; const protectedProcedure = publicProcedure.use(async function isAuthed(opts) { const { ctx } = opts; // `ctx.user` is nullable if (!ctx.user) { // (property) user: { // id: string; // } | undefined throw new TRPCError({ code: 'UNAUTHORIZED' }); } return opts.next({ ctx: { // βœ… user value is known to be non-null now user: ctx.user, // (property) user: { // id: string; // } }, }); }); protectedProcedure.query((opts) => { const { ctx } = opts; return ctx.user; // const ctx: { // user: { // id: string; // }; // } }); ``` The `ctx` you pass to `opts.next()` is merged into the existing context, so you only need to pass the keys you add or override. ## Middleware order and input Middlewares run in the order they're chained, and the parser you pass to `.input()` runs at its position in that chain. A middleware chained before `.input()` gets `opts.input` as `undefined`; it can read the unvalidated input with `opts.getRawInput()` instead. ```ts const auditedProcedure = publicProcedure.use(async (opts) => { const rawInput = await opts.getRawInput(); console.log(`${opts.type} ${opts.path}`, rawInput); return opts.next(); }); auditedProcedure .input(z.object({ id: z.string() })) .use((opts) => { // after `.input()`, `opts.input` is parsed and typed console.log(opts.input.id); return opts.next(); }) .query((opts) => opts.input.id); ``` Besides `ctx`, `input`, `getRawInput` and `next`, a middleware receives the procedure's `path`, `type` (`'query'`, `'mutation'` or `'subscription'`), [`meta`](https://trpc.io/docs/server/metadata.md), and the request's `signal`. ## Using `.concat()` to create reusable middlewares and plugins {#concat} > [!TIP] > > - Creating middlewares using `t.middleware` has the limitation that the `Context` type is tied to the `Context` type of the tRPC instance. > - Creating middlewares with `experimental_standaloneMiddleware()` has the limitation that you cannot define input parsers and similar tied to your module. tRPC has an API called `.concat()` which allows you to independently define a partial procedure that can be used with any tRPC instance that matches the context and metadata of the plugin. This helper primarily targets creating plugins and libraries with tRPC. ```ts // ------------------------------------------------ // 🧩🧩🧩 a library creating a reusable plugin 🧩🧩🧩 // @filename: myPlugin.ts import { initTRPC, TRPCError } from '@trpc/server'; export function createMyPlugin() { // When creating a plugin for tRPC, you use the same API as creating any other tRPC-app // this is the plugin's root `t`-object const t = initTRPC .context<{ // the procedure using the plugin will need to extend this context }>() .meta<{ // the base `initTRPC`-object of the application using this needs to extend this meta }>() .create(); return { // you can also add `.input()` if you want your plugin to do input validation pluginProc: t.procedure.use((opts) => { return opts.next({ ctx: { fromPlugin: 'hello from myPlugin' as const, }, }); }), }; } // ------------------------------------ // πŸš€πŸš€πŸš€ the app using the plugin πŸš€πŸš€πŸš€ // @filename: app.ts import { createMyPlugin } from './myPlugin'; import { initTRPC, TRPCError } from '@trpc/server'; // the app's root `t`-object const t = initTRPC .context<{ // ... }>() .create(); export const publicProcedure = t.procedure; export const router = t.router; // initialize the plugin (a real-world example would likely take options here) const plugin = createMyPlugin(); // create a base procedure using the plugin const procedureWithPlugin = publicProcedure .concat( plugin.pluginProc, ) .use(opts => { const { ctx } = opts; // const ctx: { // fromPlugin: "hello from myPlugin"; // } return opts.next() }) export const appRouter = router({ hello: procedureWithPlugin.query(opts => { return opts.ctx.fromPlugin; }) }) ``` ## Extending middlewares > [!NOTE] Info > We have prefixed this as `unstable_` as it's a new API, but you're safe to use it! [Read more](https://trpc.io/docs/faq.md#unstable). We have a powerful feature called `.pipe()` which allows you to extend middlewares in a typesafe manner. Below we have an example of a middleware that extends a base middleware(foo). Like the context extension example above, piping middlewares will change properties of the context, and procedures will receive the new context value. ```ts const fooMiddleware = t.middleware((opts) => { return opts.next({ ctx: { foo: 'foo' as const, }, }); }); const barMiddleware = fooMiddleware.unstable_pipe((opts) => { const { ctx } = opts; ctx.foo; // (property) foo: "foo" return opts.next({ ctx: { bar: 'bar' as const, }, }); }); const barProcedure = publicProcedure.use(barMiddleware); barProcedure.query((opts) => { const { ctx } = opts; return ctx.bar; // const ctx: { // foo: "foo"; // bar: "bar"; // } }); ``` Beware that the order in which you pipe your middlewares matter and that the context must overlap. An example of a forbidden pipe is shown below. Here, the `fooMiddleware` overrides the `ctx.a` while `barMiddleware` still expects the root context from the initialization in `initTRPC` - so piping `fooMiddleware` with `barMiddleware` would not work, while piping `barMiddleware` with `fooMiddleware` does work. ```ts import { initTRPC } from '@trpc/server'; const t = initTRPC .context<{ a: { b: 'a'; }; }>() .create(); const fooMiddleware = t.middleware((opts) => { const { ctx } = opts; ctx.a; // πŸ‘ˆ fooMiddleware expects `ctx.a` to be an object // (property) a: { // b: "a"; // } return opts.next({ ctx: { a: 'a' as const, // πŸ‘ˆ `ctx.a` is no longer an object }, }); }); const barMiddleware = t.middleware((opts) => { const { ctx } = opts; ctx.a; // πŸ‘ˆ barMiddleware expects `ctx.a` to be an object // (property) a: { // b: "a"; // } return opts.next({ ctx: { foo: 'foo' as const, }, }); }); // ❌ `ctx.a` does not overlap from `fooMiddleware` to `barMiddleware` fooMiddleware.unstable_pipe(barMiddleware); // βœ… `ctx.a` overlaps from `barMiddleware` and `fooMiddleware` barMiddleware.unstable_pipe(fooMiddleware); ``` ## Common mistakes - **Not returning `opts.next()`.** Every middleware must call `opts.next()` and return its result. Otherwise TypeScript reports an error, and at runtime the call fails with an `INTERNAL_SERVER_ERROR` ("No result from middlewares - did you forget to `return next()`?"). - **Wrapping `opts.next()` in `try`/`catch`.** `opts.next()` doesn't throw when a later middleware or the procedure fails: it resolves to a result with `ok: false` and the `TRPCError`. Check `result.ok`, like the [logging example](#logging) does: ```ts const reportedProcedure = publicProcedure.use(async (opts) => { const result = await opts.next(); if (!result.ok) { console.error(`${opts.path} failed`, result.error); } return result; }); ``` ## Experimental: standalone middlewares > [!WARNING] Deprecated > This has been deprecated in favor of [`.concat()`](#concat). Use `.concat()` for new code. tRPC has an experimental API called `experimental_standaloneMiddleware` which allows you to independently define a middleware that can be used with any tRPC instance. Creating middlewares using `t.middleware` has the limitation that the `Context` type is tied to the `Context` type of the tRPC instance. This means that you cannot use the same middleware with multiple tRPC instances that have different `Context` types. Using `experimental_standaloneMiddleware` you can create a middleware that explicitly defines its requirements, i.e. the Context, Input and Meta types: ```ts import { experimental_standaloneMiddleware, initTRPC, TRPCError, } from '@trpc/server'; import * as z from 'zod'; const projectAccessMiddleware = experimental_standaloneMiddleware<{ ctx: { allowedProjects: string[] }; // defaults to 'object' if not defined input: { projectId: string }; // defaults to 'unknown' if not defined // 'meta', not defined here, defaults to 'object | undefined' }>().create((opts) => { if (!opts.ctx.allowedProjects.includes(opts.input.projectId)) { throw new TRPCError({ code: 'FORBIDDEN', message: 'Not allowed', }); } return opts.next(); }); const t1 = initTRPC .context<{ allowedProjects: string[]; }>() .create(); // βœ… `ctx.allowedProjects` satisfies "string[]" and `input.projectId` satisfies "string" const accessControlledProcedure = t1.procedure .input(z.object({ projectId: z.string() })) .use(projectAccessMiddleware); // ❌ `ctx.allowedProjects` satisfies "string[]" but `input.projectId` does not satisfy "string" const accessControlledProcedure2 = t1.procedure .input(z.object({ projectId: z.number() })) .use(projectAccessMiddleware); // ❌ `ctx.allowedProjects` does not satisfy "string[]" even though `input.projectId` satisfies "string" const t2 = initTRPC .context<{ allowedProjects: number[]; }>() .create(); const accessControlledProcedure3 = t2.procedure .input(z.object({ projectId: z.string() })) .use(projectAccessMiddleware); ``` Here is an example with multiple standalone middlewares: ```ts import { experimental_standaloneMiddleware, initTRPC } from '@trpc/server'; import * as z from 'zod'; const t = initTRPC.create(); const schemaA = z.object({ valueA: z.string() }); const schemaB = z.object({ valueB: z.string() }); const valueAUppercaserMiddleware = experimental_standaloneMiddleware<{ input: z.infer; }>().create((opts) => { return opts.next({ ctx: { valueAUppercase: opts.input.valueA.toUpperCase() }, }); }); const valueBUppercaserMiddleware = experimental_standaloneMiddleware<{ input: z.infer; }>().create((opts) => { return opts.next({ ctx: { valueBUppercase: opts.input.valueB.toUpperCase() }, }); }); const combinedInputThatSatisfiesBothMiddlewares = z.object({ valueA: z.string(), valueB: z.string(), extraProp: z.string(), }); t.procedure .input(combinedInputThatSatisfiesBothMiddlewares) .use(valueAUppercaserMiddleware) .use(valueBUppercaserMiddleware) .query( ({ input: { valueA, valueB, extraProp }, ctx: { valueAUppercase, valueBUppercase }, }) => `valueA: ${valueA}, valueB: ${valueB}, extraProp: ${extraProp}, valueAUppercase: ${valueAUppercase}, valueBUppercase: ${valueBUppercase}`, ); ``` --- Source: https://trpc.io/docs/server/merging-routers # Merging Routers > Writing all API-code in the same file can become unwieldy. It's easy to merge routers together in order to break them up. ## Merging with child routers ```ts title="routers/user.ts" import { router, publicProcedure } from '../trpc'; import { z } from 'zod'; export const userRouter = router({ list: publicProcedure.query(() => { // [..] return []; }), }); ``` ```ts title="routers/post.ts" import { router, publicProcedure } from '../trpc'; import { z } from 'zod'; export const postRouter = router({ create: publicProcedure .input( z.object({ title: z.string(), }), ) .mutation((opts) => { const { input } = opts; // [...] }), list: publicProcedure.query(() => { // ... return []; }), }); ``` ```ts title="routers/_app.ts" import { router } from '../trpc'; import { userRouter } from './user'; import { postRouter } from './post'; const appRouter = router({ user: userRouter, post: postRouter, }); appRouter.user // (property) user: DecorateCreateRouterOptions<{ // list: QueryProcedure<{ // input: void; // output: never[]; // meta: object; // errorShape: DefaultErrorShape; // }>; // }> appRouter.post // (property) post: DecorateCreateRouterOptions<{ // create: MutationProcedure<{ // input: { // title: string; // }; // output: void; // meta: object; // errorShape: DefaultErrorShape; // }>; // list: QueryProcedure<{ // input: void; // output: never[]; // meta: object; // errorShape: DefaultErrorShape; // }>; // }> export type AppRouter = typeof appRouter; ``` ## Merging with `t.mergeRouters` If you prefer having all procedures flat in one single namespace, you can instead use `t.mergeRouters`. It throws if two routers define the same procedure path, so keep the names unique. Merge routers from the same [`t`](https://trpc.io/docs/server/routers.md#initialize-trpc): it also throws if they come from separate tRPC instances that each set a transformer or error formatter. ```ts title="routers/user.ts" import { router, publicProcedure } from '../trpc'; import { z } from 'zod'; export const userRouter = router({ userList: publicProcedure.query(() => { // [..] return []; }), }); ``` ```ts title="routers/post.ts" import { router, publicProcedure } from '../trpc'; import { z } from 'zod'; export const postRouter = router({ postCreate: publicProcedure .input( z.object({ title: z.string(), }), ) .mutation((opts) => { const { input } = opts; // [...] }), postList: publicProcedure.query(() => { // ... return []; }), }); ``` ```ts title="routers/_app.ts" import { mergeRouters } from '../trpc'; import { userRouter } from './user'; import { postRouter } from './post'; const appRouter = mergeRouters(userRouter, postRouter); // const appRouter: BuiltRouter<{ // ctx: object; // meta: object; // errorShape: DefaultErrorShape; // transformer: false; // }, DecorateCreateRouterOptions<{ // postCreate: MutationProcedure<{ // input: { // title: string; // }; // output: void; // meta: object; // errorShape: DefaultErrorShape; // }>; // postList: QueryProcedure<{ // input: void; // output: never[]; // meta: object; // errorShape: DefaultErrorShape; // }>; // }> & DecorateCreateRouterOptions<{ // userList: QueryProcedure<{ // input: void; // output: never[]; // meta: object; // errorShape: DefaultErrorShape; // }>; // }>> export type AppRouter = typeof appRouter; ``` ## Dynamically load routers {#lazy-load} You can use the `lazy` function to dynamically load your routers. This can be useful to reduce cold starts of your application. There's no difference in how you use the router after it's been lazy loaded vs. how you use a normal router. ```ts title="routers/greeting.ts" import { router, publicProcedure } from '../trpc'; export const greetingRouter = router({ hello: publicProcedure.query(() => 'world'), }); ``` ```ts title="routers/user.ts" import { router, publicProcedure } from '../trpc'; export const userRouter = router({ list: publicProcedure.query(() => ['John', 'Jane', 'Jim']), }); ``` ```ts title="routers/_app.ts" import { lazy } from '@trpc/server'; import { router } from '../trpc'; export const appRouter = router({ // Option 1: Short-hand when the module has exactly 1 router exported greeting: lazy(() => import('./greeting.js')), // Option 2: if exporting more than 1 router user: lazy(() => import('./user.js').then((m) => m.userRouter)), }); export type AppRouter = typeof appRouter; ``` --- Source: https://trpc.io/docs/server/adapters # Overview > tRPC is not a server on its own, and must therefore be served using other hosts, such as a simple [Node.js HTTP Server](https://trpc.io/docs/server/adapters/standalone.md), [Express](https://trpc.io/docs/server/adapters/express.md), or even [Next.js](https://trpc.io/docs/server/adapters/nextjs.md). Most tRPC features are the same no matter which backend you choose. **Adapters** act as the glue between the host system and your tRPC API. Adapters typically follow some common conventions, allowing you to set up context creation via `createContext`, and globally handle errors via `onError`, but importantly allow you to choose an appropriate host for your application. We support many modes of hosting an API, which you will find documented here. - For serverful APIs, you might want our [Standalone](https://trpc.io/docs/server/adapters/standalone.md) adapter, or use the [Express](https://trpc.io/docs/server/adapters/express.md) or [Fastify](https://trpc.io/docs/server/adapters/fastify.md) adapters to hook into your existing APIs - You might want a serverless solution and choose [AWS Lambda](https://trpc.io/docs/server/adapters/aws-lambda.md), or [Fetch](https://trpc.io/docs/server/adapters/fetch.md) for edge runtimes - You might have a full-stack framework and want a full integration like [Next.js](https://trpc.io/docs/server/adapters/nextjs.md), or you could use the [Fetch](https://trpc.io/docs/server/adapters/fetch.md) adapter with Next.js, Astro, Remix, or SolidStart > [!TIP] > For local development or serverful infrastructure, the simplest Adapter to use is the [Standalone Adapter](https://trpc.io/docs/server/adapters/standalone.md), which can be used to run a standard Node.js HTTP Server. We recommend this when you need to get started quickly and have no existing HTTP Server to integrate with. Swapping out later is trivial if your needs change. ## Common options Every HTTP adapter accepts these options, next to its own (like `endpoint` for Fetch, or `basePath` for Standalone): | Option | Description | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `router` | Your app router. Required. | | `createContext` | Creates the [context](https://trpc.io/docs/server/context.md) for each request. It receives the adapter's own objects (e.g. `req` and `res`) plus `info`. | | `onError` | Called with `{ error, type, path, input, ctx, req }` for every error, e.g. to report it. See [Error handling](https://trpc.io/docs/server/error-handling.md#handling-errors). | | `responseMeta` | Returns `{ status, headers }` for the response, e.g. for [caching](https://trpc.io/docs/server/caching.md). | | `allowBatching` | Set to `false` to reject batch requests. Defaults to `true`. | | `maxBatchSize` | Rejects batch requests with more calls than this with a `400 Bad Request`. Set `maxItems` on your batch link to the same or a lower value. | | `allowMethodOverride` | Accepts queries sent as `POST`, for clients that set `methodOverride: 'POST'` on their link. Defaults to `false`. | The Node.js adapters (Standalone, Express and Next.js) also accept: - `maxBodySize`: the largest request body in bytes; larger ones are rejected with `413 PAYLOAD_TOO_LARGE`. There's no limit by default; see [Request body size](#request-body-size). - `middleware`: a connect-style `(req, res, next)` function that runs before tRPC, e.g. [`cors()`](https://trpc.io/docs/server/adapters/standalone.md#handling-cors--options). ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './router'; createHTTPServer({ router: appRouter, createContext: () => ({}), onError({ error, path }) { console.error(`tRPC error on '${path}':`, error); }, maxBatchSize: 10, maxBodySize: 1024 * 1024, // 1 MiB }).listen(3000); ``` ### Request body size The Node.js adapters read the request body into memory, and `maxBodySize` is unset by default, so they accept bodies of any size. On a server that's reachable from the internet, set `maxBodySize` so a single large request can't exhaust the process's memory. A body over the limit is rejected with `413 PAYLOAD_TOO_LARGE` as soon as it passes the limit, before it's parsed. We recommend `1024 * 1024` (1 MiB) for typical JSON inputs, as in the example above. If you accept files or other large inputs, set it a little above the largest one you expect, and keep it under about `10 * 1024 * 1024` (10 MiB). `maxBodySize` only applies to bodies tRPC reads itself. If a body parser such as `express.json()` or the Next.js API routes body parser has already set `req.body`, limit the size in that parser instead. A limit in your reverse proxy (like nginx's `client_max_body_size`) adds another layer. --- Source: https://trpc.io/docs/server/adapters/standalone # Standalone Adapter > tRPC's Standalone Adapter is the simplest way to get a new project working. It's ideal for local development, and for server-based production environments. In essence it's just a wrapper around the standard [Node.js HTTP Server](https://nodejs.org/api/http.html) with the normal options related to tRPC. If you have an existing API deployment like [Express](https://trpc.io/docs/server/adapters/express.md), [Fastify](https://trpc.io/docs/server/adapters/fastify.md), or [Next.js](https://trpc.io/docs/server/adapters/nextjs.md), which you want to integrate tRPC into, you should have a look at their respective adapters. Likewise if you have a preference to host on serverless or edge compute, we have adapters like [AWS Lambda](https://trpc.io/docs/server/adapters/aws-lambda.md) and [Fetch](https://trpc.io/docs/server/adapters/fetch.md) which may fit your needs. It's also not uncommon, where the deployed adapter is hard to run on local machines, to have 2 entry-points in your application. You could use the Standalone Adapter for local development, and a different adapter when deployed. ## Example app
Description Links
Standalone tRPC Server
Standalone tRPC Server with CORS handling
## Setting up a Standalone tRPC Server ### 1. Implement your App Router Implement your tRPC router. For example: ```ts title="appRouter.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ getUser: t.procedure.input(z.string()).query((opts) => { return { id: opts.input, name: 'Bilbo' }; }), createUser: t.procedure .input(z.object({ name: z.string().min(5) })) .mutation(async (opts) => { // use your ORM of choice return { id: '1', ...opts.input }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ``` For more information, you can look at the [quickstart guide](https://trpc.io/docs/quickstart.md) ### 2. Use the Standalone adapter The Standalone adapter runs a simple Node.js HTTP server. ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './appRouter'; createHTTPServer({ router: appRouter, createContext() { return {}; }, // basePath: '/trpc/', // optional, defaults to '/' }).listen(2022); ``` `createHTTPServer` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters.md#common-options), like `onError` and `maxBatchSize`, plus `middleware`, `maxBodySize` and [`basePath`](#custom-basePath). ## Handling CORS & OPTIONS By default the standalone server will not respond to HTTP OPTIONS requests, or set any CORS headers. If you're not hosting in an environment which can handle this for you, like during local development, you may need to handle it. ### 1. Install cors You can add support yourself with the popular `cors` package ```bash yarn add cors yarn add -D @types/cors ``` For full information on how to configure this package, [check the docs](https://github.com/expressjs/cors#readme) ### 2. Configure the Standalone server This example just throws open CORS to any request, which is useful for development, but you can and should configure it more strictly in a production environment. ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import cors from 'cors'; import { appRouter } from './appRouter'; createHTTPServer({ middleware: cors(), router: appRouter, createContext() { return {}; }, }).listen(3333); ``` The `middleware` option will accept any function which resembles a connect/node.js middleware, so it can be used for more than `cors` handling if you wish. It is, however, intended to be a simple escape hatch and as such won't on its own allow you to compose multiple middlewares together. If you want to do this then you could: 1. Use an alternate adapter with more comprehensive middleware support, like the [Express adapter](https://trpc.io/docs/server/adapters/express.md) 2. Use a solution to compose middlewares such as [connect](https://github.com/senchalabs/connect) 3. Extend the Standalone `createHTTPHandler` with a custom http server (see below) ## Adding a handler to a Custom HTTP server `createHTTPServer` is returning an instance of Node's built-in [`http.Server`](https://nodejs.org/api/http.html#class-httpserver), which means that you have an access to all its properties and APIs. However, if `createHTTPServer` isn't enough for your use case, you can also use the standalone adapter's `createHTTPHandler` function to create your own HTTP server. For instance: ```ts title="server.ts" import { createServer } from 'http'; import { createHTTPHandler } from '@trpc/server/adapters/standalone'; import { appRouter } from './appRouter'; const handler = createHTTPHandler({ router: appRouter, createContext() { return {}; }, }); createServer((req, res) => { /** * Handle the request however you like, * just call the tRPC handler when you're ready */ handler(req, res); }).listen(3001); ``` ## Custom base path for handling requests {#custom-basePath} The Standalone adapter also supports a `basePath` option, which will slice the basePath from the beginning of the request path. ```ts title="server.ts" import { createServer } from 'http'; import { createHTTPHandler } from '@trpc/server/adapters/standalone'; import { appRouter } from './appRouter'; const handler = createHTTPHandler({ router: appRouter, basePath: '/trpc/', }); createServer((req, res) => { if (req.url?.startsWith('/trpc/')) { return handler(req, res); } // [... insert your custom logic here ...] res.statusCode = 404; res.end('Not Found'); }).listen(3001); ``` ## HTTP2 The Standalone adapter also supports HTTP/2. ```ts title="server.ts" import http2 from 'http2'; import { createHTTP2Handler } from '@trpc/server/adapters/standalone'; import { appRouter } from './_app'; import { createContext } from './context'; const handler = createHTTP2Handler({ router: appRouter, createContext, // basePath: '/trpc/', // optional, defaults to '/' }); const server = http2.createSecureServer( { key: '...', cert: '...', }, (req, res) => { /** * Handle the request however you like, * just call the tRPC handler when you're ready */ handler(req, res); }, ); server.listen(3001); ``` ```ts title="context.ts" import { CreateHTTP2ContextOptions } from '@trpc/server/adapters/standalone'; export async function createContext(opts: CreateHTTP2ContextOptions) { opts.req; // (property) req: Http2ServerRequest opts.res; // (property) res: Http2ServerResponse opts.info; // (property) info: TRPCRequestInfo return {}; } export type Context = Awaited>; ``` ## Common mistakes - **Calling the server from another origin without CORS.** The browser's preflight `OPTIONS` request gets no CORS headers, so the browser blocks the call. Pass [`middleware: cors()`](#handling-cors--options), with the origins you allow. --- Source: https://trpc.io/docs/server/adapters/express # Express Adapter > ## Example app
Description Links
Express server & procedure calls with Node.js.
## How to add tRPC to existing Express project ### 1. Install deps ```bash yarn add @trpc/server zod ``` > [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below. ### 2. Create a tRPC router Implement your tRPC router. A sample router is given below: ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ getUser: t.procedure.input(z.string()).query((opts) => { opts.input; // string return { id: opts.input, name: 'Bilbo' }; }), createUser: t.procedure .input(z.object({ name: z.string().min(5) })) .mutation(async (opts) => { // use your ORM of choice return { id: '1', ...opts.input }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ``` If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then [merge them](https://trpc.io/docs/server/merging-routers.md) into a single root `appRouter`. ### 3. Use the Express adapter tRPC includes an adapter for Express out of the box. This adapter lets you convert your tRPC router into an Express middleware. ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import * as trpcExpress from '@trpc/server/adapters/express'; import express from 'express'; // created for each request const createContext = ({ req, res, }: trpcExpress.CreateExpressContextOptions) => ({}); // no context type Context = Awaited>; const t = initTRPC.context().create(); const appRouter = t.router({ // [...] }); const app = express(); app.use( '/trpc', trpcExpress.createExpressMiddleware({ router: appRouter, createContext, }), ); app.listen(4000); ``` Your endpoints are now available via HTTP! | Endpoint | HTTP URI | | ------------ | ---------------------------------------------------------------------------------------------------------- | | `getUser` | `GET http://localhost:4000/trpc/getUser?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | | `createUser` | `POST http://localhost:4000/trpc/createUser`

with `req.body` of type `{name: string}` | `createContext` receives Express's `req` and `res`, so you can, for example, read `req.headers.authorization` to [authorize the user](https://trpc.io/docs/server/authorization.md). The middleware accepts the [options every adapter takes](https://trpc.io/docs/server/adapters.md#common-options), like `onError` and `maxBatchSize`, plus `middleware` and `maxBodySize`. ## Body parsers tRPC parses request bodies itself, so tRPC routes don't need `express.json()`. If a body parser runs before tRPC anyway, tRPC uses the `req.body` it parsed, which works for JSON. For [FormData and binary inputs](https://trpc.io/docs/server/non-json-content-types.md) it depends on your Express version: - **Express 5**: `express.json()` and `express.urlencoded()` leave other content types unread, so tRPC still reads them. - **Express 4**: the parsers set `req.body` to `{}` on content types they skip, so tRPC receives `{}` instead of the form data or file. - In both versions, a parser that reads the body you upload as text, like `express.text()`, breaks binary inputs. `express.raw()` keeps the bytes it read, so tRPC uses them as sent. To be safe, register body parsers only on the routes that need them: ```ts title="server.ts" import * as trpcExpress from '@trpc/server/adapters/express'; import express from 'express'; import { appRouter } from './router'; const app = express(); app.use('/api', express.json()); // only for your own `/api/*` routes app.post('/api/webhook', (req, res) => { res.json({ received: req.body }); }); app.use('/trpc', trpcExpress.createExpressMiddleware({ router: appRouter })); app.listen(4000); ``` --- Source: https://trpc.io/docs/server/adapters/fastify # Fastify Adapter > ## Example app The best way to start with the Fastify adapter is to take a look at the example application.
Description Links
  • Fastify server with WebSocket
  • Simple tRPC client in node
## How to use tRPC with Fastify ### Install dependencies ```bash yarn add @trpc/server fastify zod ``` > ⚠️ **Fastify version requirement** > > The tRPC v11 Fastify adapter requires **Fastify v5+**. > Using Fastify v4 may cause requests to return empty responses without errors. > [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below. ### Create the router First of all you need a [router](https://trpc.io/docs/server/routers.md) to handle your queries, mutations and subscriptions. A sample router is given below, save it in a file named `router.ts`.
router.ts ```ts title="router.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; type User = { id: string; name: string; bio?: string; }; const users: Record = {}; export const t = initTRPC.create(); export const appRouter = t.router({ getUserById: t.procedure.input(z.string()).query((opts) => { return users[opts.input]; // input type is string }), createUser: t.procedure .input( z.object({ name: z.string().min(3), bio: z.string().max(142).optional(), }), ) .mutation((opts) => { const id = Date.now().toString(); const user: User = { id, ...opts.input }; users[user.id] = user; return user; }), }); // export type definition of API export type AppRouter = typeof appRouter; ```
If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then [merge them](https://trpc.io/docs/server/merging-routers.md) into a single root `appRouter`. ### Create the context Then you need a [context](https://trpc.io/docs/server/context.md) that will be created for each request. A sample context is given below, save it in a file named `context.ts`:
context.ts ```ts title="context.ts" import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify'; export function createContext({ req, res }: CreateFastifyContextOptions) { const user = { name: req.headers.username ?? 'anonymous' }; return { req, res, user }; } export type Context = Awaited>; ```
### Create Fastify server tRPC includes an adapter for [Fastify](https://www.fastify.io/) out of the box. This adapter lets you convert your tRPC router into a [Fastify plugin](https://www.fastify.io/docs/latest/Reference/Plugins/). In order to prevent errors during large batch requests, make sure to set the `maxParamLength` Fastify option to a suitable value, as shown. > [!TIP] > Due to limitations in Fastify's plugin system and type inference, there might be some issues getting for example `onError` typed correctly. You can add a `satisfies FastifyTRPCPluginOptions['trpcOptions']` to help TypeScript out and get the correct types. ```ts title="server.ts" import { fastifyTRPCPlugin, FastifyTRPCPluginOptions, } from '@trpc/server/adapters/fastify'; import fastify from 'fastify'; import { createContext } from './context'; import { appRouter, type AppRouter } from './router'; const server = fastify({ routerOptions: { maxParamLength: 5000, }, }); server.register(fastifyTRPCPlugin, { prefix: '/trpc', trpcOptions: { router: appRouter, createContext, onError({ path, error }) { // report to error monitoring console.error(`Error in tRPC handler on path '${path}':`, error); }, } satisfies FastifyTRPCPluginOptions['trpcOptions'], }); (async () => { try { await server.listen({ port: 3000 }); } catch (err) { server.log.error(err); process.exit(1); } })(); ``` Your endpoints are now available via HTTP! | Endpoint | HTTP URI | | ------------- | -------------------------------------------------------------------------------------------------------------- | | `getUserById` | `GET http://localhost:3000/trpc/getUserById?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | | `createUser` | `POST http://localhost:3000/trpc/createUser`

with `req.body` of type `User` | ## Enable WebSockets The Fastify adapter supports [WebSockets](https://trpc.io/docs/server/websockets.md) via the [@fastify/websocket](https://www.npmjs.com/package/@fastify/websocket) plugin. All you have to do in addition to the above steps is install the dependency, add some subscriptions to your router, and activate the `useWSS` [option](#fastify-plugin-options) in the plugin. The minimum `@fastify/websocket` version required is `3.11.0`. ### Install dependencies ```bash yarn add @fastify/websocket ``` ### Import and register `@fastify/websocket` ```ts import ws from '@fastify/websocket'; server.register(ws); ``` ### Add some subscriptions Edit the `router.ts` file created in the previous steps and add the following code: ```ts title="router.ts" import { initTRPC } from '@trpc/server'; const t = initTRPC.create(); export const appRouter = t.router({ randomNumber: t.procedure.subscription(async function* () { while (true) { yield { randomNumber: Math.random() }; await new Promise((resolve) => setTimeout(resolve, 1000)); } }), }); ``` ### Activate the `useWSS` option ```ts title="server.ts" import { fastifyTRPCPlugin, FastifyTRPCPluginOptions, } from '@trpc/server/adapters/fastify'; import fastify from 'fastify'; import { createContext } from './context'; import { appRouter, type AppRouter } from './router'; const server = fastify(); server.register(fastifyTRPCPlugin, { useWSS: true, trpcOptions: { router: appRouter, createContext, // Enable heartbeat messages to keep connection open (disabled by default) keepAlive: { enabled: true, // server ping message interval in milliseconds pingMs: 30000, // connection is terminated if pong message is not received in this many milliseconds pongWaitMs: 5000, }, }, }); ``` You can now subscribe to the `randomNumber` topic and should receive a random number every second πŸš€. ## Fastify plugin options | name | type | optional | default | description | | ----------- | -------------------------------------------------- | -------- | --------- | -------------------------------------------------------------- | | prefix | `string` | `true` | `"/trpc"` | URL prefix for tRPC routes | | useWSS | `boolean` | `true` | `false` | Enable WebSocket support via `@fastify/websocket` | | trpcOptions | `FastifyHandlerOptions` | `false` | `n/a` | tRPC handler options including `router`, `createContext`, etc. | `trpcOptions` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters.md#common-options), like `onError` and `maxBatchSize`. With `useWSS`, it also accepts the WebSocket options `keepAlive`, `dangerouslyDisablePong` and `experimental_encoder`. ## Common mistakes - **Registering `@fastify/websocket` after the tRPC plugin.** It only adds WebSocket support to routes registered after it, so register it first. - **Leaving `maxParamLength` at Fastify's default of `100`.** A batch request puts every procedure in one path parameter, like `/trpc/getUserById,createUser`, and Fastify answers `414 URI Too Long` once that gets longer than `maxParamLength`. - **Using Fastify v4.** The tRPC v11 adapter requires Fastify v5 or later. --- Source: https://trpc.io/docs/server/adapters/nextjs # Next.js Adapter > Serve tRPC from a Next.js API route with createNextApiHandler, or from an App Router route handler with fetchRequestHandler > [!TIP] > tRPC's support for Next.js is far more expansive than just an adapter. This page covers a brief summary of how to set up the adapter. For complete documentation, see the [Next.js Integration guide](https://trpc.io/docs/client/nextjs.md). ## Example app
Description Links
Next.js Prisma Starter: an API route with createNextApiHandler
Next.js Minimal Starter: an App Router route handler with fetchRequestHandler
## Next.js example Serving your tRPC router in a Next.js project is straight-forward. Just create an API handler in `pages/api/trpc/[trpc].ts` as shown below: ```ts title="pages/api/trpc/[trpc].ts" import { createNextApiHandler } from '@trpc/server/adapters/next'; import { createContext } from '../../../server/trpc/context'; import { appRouter } from '../../../server/trpc/router/_app'; export default createNextApiHandler({ router: appRouter, createContext, }); ``` ## Handling CORS and other advanced usage While you can usually just "set and forget" the API Handler as shown above, sometimes you might want to modify it further. The API handler created by `createNextApiHandler` and equivalents in other frameworks is just a function that takes `req` and `res` objects. This means you can also modify those objects before passing them to the handler, for example to [enable CORS](https://trpc.io/docs/client/cors.md). ```ts title="pages/api/trpc/[trpc].ts" import type { NextApiRequest, NextApiResponse } from 'next'; import { createNextApiHandler } from '@trpc/server/adapters/next'; import { createContext } from '../../../server/trpc/context'; import { appRouter } from '../../../server/trpc/router/_app'; // create the API handler, but don't return it yet const nextApiHandler = createNextApiHandler({ router: appRouter, createContext, }); // https://nextjs.org/docs/api-routes/introduction export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { // We can use the response object to enable CORS res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Request-Method', '*'); res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET'); res.setHeader('Access-Control-Allow-Headers', '*'); // If you need to make authenticated CORS calls then // remove what is above and uncomment the below code // Allow-Origin has to be set to the requesting domain that you want to send the credentials back to // res.setHeader('Access-Control-Allow-Origin', 'http://example:6006'); // res.setHeader('Access-Control-Request-Method', '*'); // res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET'); // res.setHeader('Access-Control-Allow-Headers', 'content-type'); // res.setHeader('Referrer-Policy', 'no-referrer'); // res.setHeader('Access-Control-Allow-Credentials', 'true'); if (req.method === 'OPTIONS') { res.writeHead(200); return res.end(); } // finally pass the request on to the tRPC handler return nextApiHandler(req, res); } ``` ## App Router (Route Handlers) If you're using the Next.js **App Router**, use the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) instead, as App Router route handlers are based on the Web standard `Request` and `Response` objects. See the [App Router setup guide](https://trpc.io/docs/client/nextjs/app-router-setup.md) for a complete walkthrough. ```ts title="app/api/trpc/[trpc]/route.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createTRPCContext } from '../../trpc/init'; import { appRouter } from '../../trpc/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: createTRPCContext, }); export { handler as GET, handler as POST }; ``` --- Source: https://trpc.io/docs/server/adapters/aws-lambda # AWS Lambda + API Gateway Adapter > ## AWS Lambda adapter The AWS Lambda adapter is supported for API Gateway [REST API(v1)](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html) and [HTTP API(v2)](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html), and [Lambda Function URL](https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html) use cases. > `httpBatchLink` requires the router to work on a single API Gateway Resource (as shown in the [example](https://github.com/trpc/trpc/tree/main/examples/lambda-api-gateway)). > If you'd like to have a Resource per procedure, you can use the `httpLink` instead ([more info](https://github.com/trpc/trpc/issues/5738#issuecomment-2130001522)). ## Example apps
Description Links
API Gateway with NodeJS client.
API Gateway REST API with response streaming.
## How to add tRPC ### 1. Install deps ```bash yarn add @trpc/server ``` ### 2. Create a tRPC router Implement your tRPC router. A sample router is given below: ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); const appRouter = t.router({ getUser: t.procedure.input(z.string()).query((opts) => { opts.input; // string return { id: opts.input, name: 'Bilbo' }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ``` ### 3. Use the Amazon API Gateway adapter tRPC includes an adapter for API Gateway out of the box. This adapter lets you run your routes through the API Gateway handler. ```ts title="server.ts" import type { APIGatewayProxyEventV2 } from 'aws-lambda'; import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda'; import { awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda'; import { appRouter } from './router'; // created for each request const createContext = ({ event, context, }: CreateAWSLambdaContextOptions) => ({}); // no context type Context = Awaited>; export const handler = awsLambdaRequestHandler({ router: appRouter, createContext, }) ``` `awsLambdaRequestHandler` accepts the [options every adapter takes](https://trpc.io/docs/server/adapters.md#common-options), like `onError` and `maxBatchSize`. Build & deploy your code, now use your API Gateway URL to call your function. | Endpoint | HTTP URI | | --------- | ------------------------------------------------------------------------------------------------------------ | | `getUser` | `GET https:///getUser?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | #### A word about payload format version API Gateway has two different event data formats when it invokes a Lambda. For REST APIs they should be version "1.0"(`APIGatewayProxyEvent`), but you can choose which for HTTP APIs by stating either version "1.0" or "2.0". - Version 1.0: `APIGatewayProxyEvent` - Version 2.0: `APIGatewayProxyEventV2` To infer what version you might have, supply the context as following: ```ts function createContext({ event, context, }: CreateAWSLambdaContextOptions) { // ... } // CreateAWSLambdaContextOptions or CreateAWSLambdaContextOptions ``` [Read more here about payload format version](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html) ## AWS Lambda Response Streaming Adapter AWS Lambda supports streaming responses to clients with both Lambda Function URLs and API Gateway REST APIs. > Response streaming is supported for Lambda Function URLs and API Gateway REST APIs. For API Gateway REST APIs, you need to configure the integration with `responseTransferMode: STREAM`. [Read more about Lambda response streaming](https://aws.amazon.com/blogs/compute/introducing-aws-lambda-response-streaming/) and [API Gateway response streaming](https://aws.amazon.com/blogs/compute/building-responsive-apis-with-amazon-api-gateway-response-streaming/). ### Response Streaming The signature of a streaming handler is different from the default handler. The streaming handler additionally receives a writable stream parameter, `responseStream`, besides the default node handler parameters, `event` and `context`. To indicate that Lambda should stream your responses, you must wrap your function handler with the `awslambda.streamifyResponse()` decorator. > Note that the `awslambda` namespace is automatically provided by the Lambda execution environment. You can import the types from `@types/aws-lambda` to augment the global namespace with the `awslambda` namespace. With streaming, a procedure that returns an async generator, like `iterable` below, sends each value as it's yielded to clients using [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md). ```ts title="server.ts" /// import type { APIGatewayProxyEventV2 } from 'aws-lambda'; import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda'; import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda'; import { appRouter } from './router'; // created for each request const createContext = ({ event, context, }: CreateAWSLambdaContextOptions) => ({ // your context }); type Context = Awaited>; export const handler = awslambda.streamifyResponse( awsLambdaStreamingRequestHandler({ router: appRouter, createContext, }), ); ``` ## Common mistakes - **Using `httpBatchLink` with a resource per procedure.** A batch request puts several procedures in one path, like `/getUser,createUser`, which none of those resources match. Use one greedy resource like `/trpc/{proxy+}`, which tRPC reads the procedure path from, or switch to `httpLink`. - **Forgetting `awslambda.streamifyResponse()`.** Without it, Lambda calls `awsLambdaStreamingRequestHandler` as a regular handler, which has no response stream to write to. - **Expecting the default handler to stream.** `awsLambdaRequestHandler` buffers the whole response before returning it, so `httpBatchStreamLink` responses arrive all at once. Use the [streaming handler](#response-streaming) instead. --- Source: https://trpc.io/docs/server/adapters/fetch # Fetch / Edge Runtimes Adapter > You can create a tRPC server within any edge runtime that follow the [WinterCG](https://wintercg.org/), specifically the [Minimum Common Web Platform API](https://min-common-api.proposal.wintertc.org/) specification. Some of these runtimes include, but are not limited to: - Cloudflare Workers - Deno Deploy - Vercel Edge Runtime (& Next.js Edge Runtime) This also makes it easy to integrate into frameworks that use the web platform APIs to represent requests and responses, such as: - Astro (SSR mode) - Remix - SolidStart ## Example apps
Description Links
Cloudflare Workers example Source
Deno Deploy example Source
Next.js Edge Runtime example Source
Vercel Edge Runtime example Source
## How to use tRPC server with an edge runtime tRPC provides a [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) that uses the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) APIs as input and output. The tRPC-specific code is the same across all runtimes, the only difference being how the response is returned. tRPC includes an adapter for the native [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) out of the box. This adapter lets you convert your tRPC router into a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) handler that returns [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects. ## Required Web APIs tRPC server uses the following Fetch APIs: - `Request`, `Response` - `fetch` - `Headers` - `URL` If your runtime supports these APIs, you can [use tRPC server](#how-to-use-trpc-server-with-an-edge-runtime). > [!TIP] > Fun fact: that also means you can use a tRPC server in your browser! ## Common setup ### Install dependencies > [!TIP] > You can skip this step if you use Deno Deploy. ```package-install @trpc/server @trpc/client zod ``` > [Zod](https://github.com/colinhacks/zod) isn't a required dependency, but it's used in the sample router below. ### Create the router First of all you need a [router](https://trpc.io/docs/server/routers.md) to handle your queries, mutations and subscriptions. A sample router is given below, save it in a file named `router.ts`.
router.ts ```ts title="router.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; import type { Context } from './context'; type User = { id: string; name: string; bio?: string; }; const users: Record = {}; export const t = initTRPC.context().create(); export const appRouter = t.router({ getUserById: t.procedure.input(z.string()).query((opts) => { return users[opts.input]; // input type is string }), createUser: t.procedure // validate input with Zod .input( z.object({ name: z.string().min(3), bio: z.string().max(142).optional(), }), ) .mutation((opts) => { const id = Date.now().toString(); const user: User = { id, ...opts.input }; users[user.id] = user; return user; }), }); // export type definition of API export type AppRouter = typeof appRouter; ```
If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then [merge them](https://trpc.io/docs/server/merging-routers.md) into a single root `appRouter`. ### Create the context Then you need a [context](https://trpc.io/docs/server/context.md) that will be created for each request. A sample context is given below, save it in a file named `context.ts`:
context.ts ```ts title="context.ts" import type { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch'; export function createContext({ req, resHeaders, }: FetchCreateContextFnOptions) { const user = { name: req.headers.get('username') ?? 'anonymous' }; return { req, resHeaders, user }; } export type Context = Awaited>; ```
Headers you set on `resHeaders`, like `Set-Cookie`, are added to the response. `fetchRequestHandler` takes an `endpoint`, the URL path the handler is mounted on, plus the [options every adapter takes](https://trpc.io/docs/server/adapters.md#common-options), like `onError` and `maxBatchSize`. ## Runtime-specific setup ### Astro ```ts title="src/pages/trpc/[trpc].ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import type { APIRoute } from 'astro'; import { createContext } from '../../server/context'; import { appRouter } from '../../server/router'; export const ALL: APIRoute = (opts) => { return fetchRequestHandler({ endpoint: '/trpc', req: opts.request, router: appRouter, createContext, }); }; ``` ### Cloudflare Worker > [!NOTE] > You need the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) to run Cloudflare Workers. #### Create Cloudflare Worker ```ts title="server.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createContext } from './context'; import { appRouter } from './router'; export default { async fetch(request: Request): Promise { return fetchRequestHandler({ endpoint: '/trpc', req: request, router: appRouter, createContext, }); }, }; ``` Run `wrangler dev server.ts` and your endpoints will be available via HTTP! | Endpoint | HTTP URI | | ------------ | -------------------------------------------------------------------------------------------------------------- | | `getUser` | `GET http://localhost:8787/trpc/getUserById?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | | `createUser` | `POST http://localhost:8787/trpc/createUser`

with `req.body` of type `User` | ### Deno Oak > [!NOTE] > This assumes you have Deno installed and setup. Refer to their [getting started guide](https://deno.com/manual/getting_started/installation) for more information. #### Update the imports in `router.ts` ```ts title="router.ts" import { initTRPC } from 'npm:@trpc/server'; import { z } from 'npm:zod'; import { Context } from './context.ts'; ``` #### Update the imports in `context.ts` ```ts title="context.ts" import { FetchCreateContextFnOptions } from 'npm:@trpc/server/adapters/fetch'; ``` #### Use `fetchRequestHandler` with Oak in `app.ts` ```ts title="app.ts" import { Application, Router } from 'https://deno.land/x/oak/mod.ts'; import { fetchRequestHandler } from 'npm:@trpc/server/adapters/fetch'; import { createContext } from './context.ts'; import { appRouter } from './router.ts'; const app = new Application(); const router = new Router(); router.all('/trpc/(.*)', async (ctx) => { const res = await fetchRequestHandler({ endpoint: '/trpc', req: new Request(ctx.request.url, { headers: ctx.request.headers, body: ctx.request.method !== 'GET' && ctx.request.method !== 'HEAD' ? ctx.request.body({ type: 'stream' }).value : void 0, method: ctx.request.method, }), router: appRouter, createContext, }); ctx.response.status = res.status; ctx.response.headers = res.headers; ctx.response.body = res.body; }); app.use(router.routes()); app.use(router.allowedMethods()); await app.listen({ port: 3000 }); ``` ### Deno Deploy > [!NOTE] > This assumes you have Deno installed and setup. Refer to their [getting started guide](https://deno.com/manual/getting_started/installation) for more information. > [!TIP] > See our example [Deno Deploy app](https://github.com/trpc/trpc/tree/main/examples/deno-deploy) for a working example. #### Update the imports in `router.ts` ```ts title="router.ts" import { initTRPC } from 'npm:@trpc/server'; import { z } from 'npm:zod'; import { Context } from './context.ts'; ``` #### Update the imports in `context.ts` ```ts title="context.ts" import { FetchCreateContextFnOptions } from 'npm:@trpc/server/adapters/fetch'; ``` #### Create Deno Deploy Function ```ts title="server.ts" import { fetchRequestHandler } from 'npm:@trpc/server/adapters/fetch'; import { createContext } from './context.ts'; import { appRouter } from './router.ts'; function handler(request) { return fetchRequestHandler({ endpoint: '/trpc', req: request, router: appRouter, createContext, }); } Deno.serve(handler); ``` Run `deno run --allow-net=:8000 --allow-env ./server.ts` and your endpoints will be available via HTTP! | Endpoint | HTTP URI | | ------------ | -------------------------------------------------------------------------------------------------------------- | | `getUser` | `GET http://localhost:8000/trpc/getUserById?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | | `createUser` | `POST http://localhost:8000/trpc/createUser`

with `req.body` of type `User` | ### Next.js Edge Runtime See a full example [here](https://github.com/trpc/trpc/tree/main/examples/next-edge-runtime). ### Remix ```ts title="app/routes/trpc.$trpc.ts" import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node'; import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createContext } from '~/server/context'; import { appRouter } from '~/server/router'; export const loader = async (args: LoaderFunctionArgs) => { return handleRequest(args); }; export const action = async (args: ActionFunctionArgs) => { return handleRequest(args); }; function handleRequest(args: LoaderFunctionArgs | ActionFunctionArgs) { return fetchRequestHandler({ endpoint: '/trpc', req: args.request, router: appRouter, createContext, }); } ``` ### SolidStart ```ts title="src/routes/api/trpc/[trpc].ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import type { APIEvent } from '@solidjs/start/server'; import { createContext } from '../../server/context'; import { appRouter } from '../../server/router'; const handler = (event: APIEvent) => fetchRequestHandler({ endpoint: '/api/trpc', req: event.request, router: appRouter, createContext, }); export { handler as GET, handler as POST }; ``` ### Vercel Edge Runtime > [!NOTE] > See the official [Vercel Edge Runtime documentation](https://edge-runtime.vercel.app/getting-started) for more information. > [!TIP] > See our example [Vercel Edge Runtime app](https://github.com/trpc/trpc/tree/main/examples/vercel-edge-runtime) for a working example. #### Install dependencies
```sh npm install -g edge-runtime ```
```sh yarn global add edge-runtime ```
```sh pnpm add -g edge-runtime ```
```sh bun add -g edge-runtime ```
#### Create Edge Runtime Function ```ts title="server.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createContext } from './context'; import { appRouter } from './router'; // Vercel Edge Runtime uses Service Worker-style addEventListener addEventListener('fetch', (event: any) => { return event.respondWith( fetchRequestHandler({ endpoint: '/trpc', req: event.request, router: appRouter, createContext, }), ); }); ``` Run `edge-runtime --listen server.ts --port 3000` and your endpoints will be available via HTTP! | Endpoint | HTTP URI | | ------------ | -------------------------------------------------------------------------------------------------------------- | | `getUser` | `GET http://localhost:3000/trpc/getUserById?input=INPUT`

where `INPUT` is a URI-encoded JSON string. | | `createUser` | `POST http://localhost:3000/trpc/createUser`

with `req.body` of type `User` | ## Common mistakes - **An `endpoint` that doesn't match the route.** tRPC removes `endpoint` from the start of the URL path to find the procedure, so a handler that serves `/api/trpc/*` needs `endpoint: '/api/trpc'`. With the wrong `endpoint`, every call returns `404 NOT_FOUND`. --- Source: https://trpc.io/docs/server/server-side-calls # Server Side Calls > You may need to call your procedure(s) directly from the same server they're hosted in, `createCallerFactory()` can be used to achieve this. This is useful for server-side calls and for integration testing of your tRPC procedures. > [!NOTE] Info > > `createCaller` should not be used to call procedures from within other procedures. This creates overhead by (potentially) creating context again, executing all middlewares, and validating the input - all of which were already done by the current procedure. Instead, you should extract the shared logic into a separate function and call that from within the procedures, like so: > >
> Instead of this: procedures in paymentRouter call customerRouter.createCaller(ctx).byUserId(ctx.user.id) to reuse its logic > Do this: a standalone getCustomerId(userId, prisma) function holds the shared logic, and every procedure calls it with values from ctx and input >
## Create caller With the `t.createCallerFactory`-function you can create a server-side caller of any router. You first call `createCallerFactory` with an argument of the router you want to call, then this returns a function where you can pass in a `Context` for the following procedure calls. ### Basic example We create the router with a query to list posts and a mutation to add posts, and then we call each method. ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; type Context = { foo: string; }; const t = initTRPC.context().create(); const publicProcedure = t.procedure; const { createCallerFactory, router } = t; interface Post { id: string; title: string; } const posts: Post[] = [ { id: '1', title: 'Hello world', }, ]; const appRouter = router({ post: router({ add: publicProcedure .input( z.object({ title: z.string().min(2), }), ) .mutation((opts) => { const post: Post = { ...opts.input, id: `${Math.random()}`, }; posts.push(post); return post; }), list: publicProcedure.query(() => posts), }), }); // 1. create a caller-function for your router const createCaller = createCallerFactory(appRouter); // 2. create a caller using your `Context` const caller = createCaller({ foo: 'bar', }); // 3. use the caller to add and list posts const addedPost = await caller.post.add({ title: 'How to make server-side call in tRPC', }); const postList = await caller.post.list(); // const postList: Post[] ``` The caller doesn't run your adapter's `createContext`, so pass everything your procedures and middlewares expect. An [inner context](https://trpc.io/docs/server/context.md#inner-and-outer-context) works well here, as it doesn't need a request. Instead of a context object, you can also pass a function that returns the context, or a promise of it. The caller calls it for every procedure call, so cache it (e.g. with React's `cache()`) if it's expensive: ```ts const createCaller = t.createCallerFactory(appRouter); const caller = createCaller(async () => createContext()); const greeting = await caller.hello(); ``` ### Example usage in an integration test > Taken from [https://github.com/trpc/examples-next-prisma-starter/blob/main/src/server/routers/post.test.ts](https://github.com/trpc/examples-next-prisma-starter/blob/main/src/server/routers/post.test.ts) ```ts async function testAddAndGetPost() { const ctx = await createContextInner({}); const caller = createCaller(ctx); const input: inferProcedureInput = { text: 'hello test', title: 'hello test', }; const post = await caller.post.add(input); const byId = await caller.post.byId({ id: post.id }); } ``` ## `router.createCaller()` With the `router.createCaller({})` function (first argument is `Context`) we retrieve an instance of `RouterCaller`. ### Input query example We create the router with an input query, and then we call the asynchronous `greeting` procedure to get the result. ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC.create(); const router = t.router({ // Create procedure at path 'greeting' greeting: t.procedure .input(z.object({ name: z.string() })) .query((opts) => `Hello ${opts.input.name}`), }); const caller = router.createCaller({}); const result = await caller.greeting({ name: 'tRPC' }); // const result: string ``` ### Mutation example We create the router with a mutation, and then we call the asynchronous `post` procedure to get the result. ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const posts = ['One', 'Two', 'Three']; const t = initTRPC.create(); const router = t.router({ post: t.router({ add: t.procedure.input(z.string()).mutation((opts) => { posts.push(opts.input); return posts; }), }), }); const caller = router.createCaller({}); const result = await caller.post.add('Four'); // const result: string[] ``` ### Context with middleware example We create a middleware to check the context before executing the `secret` procedure. Below are two examples: the former fails because the context doesn't fit the middleware logic, and the latter works correctly.
> [!NOTE] Info > > Middlewares are performed before any procedure(s) are called.
```ts import { initTRPC, TRPCError } from '@trpc/server'; type Context = { user?: { id: string; }; }; const t = initTRPC.context().create(); const protectedProcedure = t.procedure.use((opts) => { const { ctx } = opts; if (!ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED', message: 'You are not authorized', }); } return opts.next({ ctx: { // Infers that the `user` is non-nullable user: ctx.user, }, }); }); const router = t.router({ secret: protectedProcedure.query((opts) => opts.ctx.user), }); { // ❌ this will return an error because there isn't the right context param const caller = router.createCaller({}); const result = await caller.secret(); } { // βœ… this will work because user property is present inside context param const authorizedCaller = router.createCaller({ user: { id: 'KATT', }, }); const result = await authorizedCaller.secret(); // const result: { // id: string; // } } ``` ### Example for a Next.js API endpoint > [!TIP] > > This example shows how to use the caller in a Next.js API endpoint. tRPC creates API endpoints for you already, so this file is only meant to show > how to call a procedure from another, custom endpoint. ```ts type ResponseData = { data?: { postTitle: string; }; error?: { message: string; }; }; export default async ( req: NextApiRequest, res: NextApiResponse, ) => { /** We want to simulate an error, so we pick a post ID that does not exist in the database. */ const postId = `this-id-does-not-exist-${Math.random()}`; const caller = appRouter.createCaller({}); try { // the server-side call const postResult = await caller.post.byId({ id: postId }); res.status(200).json({ data: { postTitle: postResult.title } }); } catch (cause) { // If this a tRPC error, we can extract additional information. if (cause instanceof TRPCError) { // We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`). const httpStatusCode = getHTTPStatusCodeFromError(cause); res.status(httpStatusCode).json({ error: { message: cause.message } }); return; } // This is not a tRPC error, so we don't have specific information. res.status(500).json({ error: { message: `Error while accessing post with ID ${postId}` }, }); } }; ``` ### Error handling A procedure called through a caller throws its error as a `TRPCError`; errors that weren't thrown as one become an `INTERNAL_SERVER_ERROR` with the original error as their `cause`. The `createCaller` function can also take an error handler through the `onError` option, for example to log or report errors. The caller still throws the error after the handler runs. Its options also take a `signal`, which your procedures receive as `opts.signal`. The handler is called with the same arguments as an error formatter would be, except for the shape field: ```ts interface OnErrorShape { ctx: unknown; error: TRPCError; path: string | undefined; input: unknown; type: 'query' | 'mutation' | 'subscription' | 'unknown'; } ``` ```ts import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC .context<{ foo?: 'bar'; }>() .create(); const router = t.router({ greeting: t.procedure.input(z.object({ name: z.string() })).query((opts) => { if (opts.input.name === 'invalid') { throw new Error('Invalid name'); } return `Hello ${opts.input.name}`; }), }); const caller = router.createCaller( { /* context */ }, { onError: (opts) => { console.error('An error occurred:', opts.error); }, }, ); // The following will log "An error occurred: Error: Invalid name", and then throw the error await caller.greeting({ name: 'invalid' }); ``` --- Source: https://trpc.io/docs/server/authorization # Authorization > The `createContext` function is called for each incoming request, so here you can add contextual information about the calling user from the request object. ## Create context from request headers ```ts title="server/context.ts" import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; import { decodeAndVerifyJwtToken } from './utils'; export async function createContext({ req, res }: CreateHTTPContextOptions) { // Create your context based on the request object // Will be available as `ctx` in all your resolvers // This is just an example of something you might want to do in your ctx fn async function getUserFromHeader() { if (req.headers.authorization) { const user = await decodeAndVerifyJwtToken( req.headers.authorization.split(' ')[1], ); return user; } return null; } const user = await getUserFromHeader(); return { user, }; } export type Context = Awaited>; ``` ## Option 1: Authorize using resolver ```ts title="server/routers/_app.ts" import { initTRPC, TRPCError } from '@trpc/server'; import { z } from 'zod'; type Context = { user: { name: string } | null }; export const t = initTRPC.context().create(); const appRouter = t.router({ // open for anyone hello: t.procedure .input(z.string().nullish()) .query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`), // checked in resolver secret: t.procedure.query((opts) => { if (!opts.ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return { secret: 'sauce', }; }), }); ``` ## Option 2: Authorize using middleware ```ts title="server/routers/_app.ts" import { initTRPC, TRPCError } from '@trpc/server'; import { z } from 'zod'; type Context = { user: { name: string } | null }; export const t = initTRPC.context().create(); // you can reuse this for any procedure export const protectedProcedure = t.procedure.use( async function isAuthed(opts) { const { ctx } = opts; // `ctx.user` is nullable if (!ctx.user) { // (property) user: { // name: string; // } | null throw new TRPCError({ code: 'UNAUTHORIZED' }); } return opts.next({ ctx: { // βœ… user value is known to be non-null now user: ctx.user, // (property) user: { // name: string; // } }, }); }, ); t.router({ // this is accessible for everyone hello: t.procedure .input(z.string().nullish()) .query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`), admin: t.router({ // this is accessible only to admins secret: protectedProcedure.query((opts) => { return { secret: 'sauce', }; }), }), }); ``` ## Building on a protected procedure Since a procedure's middlewares run in order, you can add more checks on top of `protectedProcedure`, where `ctx.user` is already non-null: ```ts title="server/trpc.ts" import { initTRPC, TRPCError } from '@trpc/server'; type Context = { user: { name: string; role: 'admin' | 'user' } | null }; export const t = initTRPC.context().create(); export const protectedProcedure = t.procedure.use(async (opts) => { if (!opts.ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return opts.next({ ctx: { user: opts.ctx.user } }); }); export const adminProcedure = protectedProcedure.use(async (opts) => { if (opts.ctx.user.role !== 'admin') { // (property) user: { // name: string; // role: "admin" | "user"; // } throw new TRPCError({ code: 'FORBIDDEN' }); } return opts.next(); }); ``` Throw `UNAUTHORIZED` (401) when the caller isn't signed in, and `FORBIDDEN` (403) when they are, but aren't allowed to do this. ## Sending credentials from the client - **Cookies** are sent with every request when the client and server are on the same origin. For another origin, see [CORS & Cookies](https://trpc.io/docs/client/cors.md). - **Headers** like `Authorization` can be set on any HTTP link with the [`headers`](https://trpc.io/docs/client/headers.md) option. - **Subscriptions** over SSE can't send custom headers with the browser's `EventSource`. See [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md#headers-and-authorization--authentication) for the options. - **WebSockets** send [connection params](https://trpc.io/docs/server/websockets.md#connectionParams) when the connection opens, which `createContext` reads from `opts.info.connectionParams`. ## Common mistakes - **Calling `opts.next()` without the narrowed `ctx`.** Procedures after the middleware still see `ctx.user` as nullable. Pass `opts.next({ ctx: { user: opts.ctx.user } })`, as in [Option 2](#option-2-authorize-using-middleware). - **Throwing in `createContext` for a missing or invalid token.** That fails every procedure in the request, public ones too. Return `user: null` instead, and let a middleware reject the procedures that need a user. - **Putting tokens in `httpSubscriptionLink`'s `connectionParams`.** They are sent in the URL, where servers and proxies may log them. Prefer cookies, or headers through an `EventSource` ponyfill. --- Source: https://trpc.io/docs/server/error-handling # Error Handling > Whenever an error occurs in a procedure, tRPC responds to the client with an object that includes an "error" property. This property contains all the information that you need to handle the error in the client. Here's an example error response caused by a bad request input: ```json { "id": null, "error": { "message": "\"password\" must be at least 4 characters", "code": -32600, "data": { "code": "BAD_REQUEST", "httpStatus": 400, "stack": "...", "path": "user.changepassword" } } } ``` ## Stack traces in production By default, tRPC includes `error.data.stack` only when [`isDev`](https://trpc.io/docs/server/routers.md#initialize-trpc) is `true`. `initTRPC.create()` sets `isDev` to `process.env.NODE_ENV !== 'production'` by default. If you need deterministic behavior across runtimes, override `isDev` manually. ```ts title="server.ts" import { initTRPC } from '@trpc/server'; const t = initTRPC.create({ isDev: false }); ``` If you need stricter control over which error fields are returned, use [error formatting](https://trpc.io/docs/server/error-formatting.md). ## Secure error reporting Errors that are not a `TRPCError` are wrapped as `INTERNAL_SERVER_ERROR` and keep the original `message`. A database driver or a library can put table names, queries or file paths in that message, and it would reach the client. This is the kind of information leak [OWASP describes](https://owasp.org/www-community/Improper_Error_Handling). A safe setup has two parts: - [`onError`](#handling-errors) receives the full error. Log it or send it to your error tracker there. - [`errorFormatter`](https://github.com/trpc/trpc/blob/main/www/docs/server/error-formatting) controls what the client sees. Replace the message of `INTERNAL_SERVER_ERROR`s and only return the fields you want to expose. ```ts title="server.ts" import { initTRPC } from '@trpc/server'; const t = initTRPC.create({ errorFormatter({ shape }) { return { message: shape.data.code === 'INTERNAL_SERVER_ERROR' ? 'Internal server error' : shape.message, code: shape.code, data: { code: shape.data.code, httpStatus: shape.data.httpStatus, path: shape.data.path, }, }; }, }); ``` The formatter above keeps the message of every other code. A `TRPCError` you throw yourself with a code like `NOT_FOUND` or `UNAUTHORIZED` is shown as written, so write messages that are safe to show to users. One thrown with `INTERNAL_SERVER_ERROR` is replaced too. > [!NOTE] > > Input validation errors are `BAD_REQUEST`s and their message is the output of your validation library. If you don't want to reveal which library you use or how your input is shaped, replace that message in the `errorFormatter` as well. ## Error codes tRPC defines a list of error codes that each represent a different type of error and response with a different HTTP code. | Code | Description | HTTP code | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | | PARSE_ERROR | Invalid JSON was received by the server, or an error occurred while parsing the request. | 400 | | BAD_REQUEST | The server cannot or will not process the request due to something that is perceived to be a client error. | 400 | | UNAUTHORIZED | The client request has not been completed because it lacks valid authentication credentials for the requested resource. | 401 | | PAYMENT_REQUIRED | The client request requires payment to access the requested resource. | 402 | | FORBIDDEN | The client is not authorized to access the requested resource. | 403 | | NOT_FOUND | The server cannot find the requested resource. | 404 | | METHOD_NOT_SUPPORTED | The server knows the request method, but the target resource doesn't support this method. | 405 | | TIMEOUT | The server would like to shut down this unused connection. | 408 | | CONFLICT | The request conflicts with the current state of the target resource. | 409 | | PRECONDITION_FAILED | Access to the target resource has been denied. | 412 | | PAYLOAD_TOO_LARGE | Request entity is larger than limits defined by server. | 413 | | UNSUPPORTED_MEDIA_TYPE | The server refuses to accept the request because the payload format is in an unsupported format. | 415 | | UNPROCESSABLE_CONTENT | The server understands the request method, and the request entity is correct, but the server was unable to process it. | 422 | | PRECONDITION_REQUIRED | [The server cannot process the request because a required precondition header (such as `If-Match`) is missing. When a precondition header does not match the server-side state, the response should be `412 Precondition Failed`.](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428) | 428 | | TOO_MANY_REQUESTS | The rate limit has been exceeded or too many requests are being sent to the server. | 429 | | CLIENT_CLOSED_REQUEST | The client closed the connection before the server finished responding. | 499 | | INTERNAL_SERVER_ERROR | An unspecified error occurred. | 500 | | NOT_IMPLEMENTED | The server does not support the functionality required to fulfill the request. | 501 | | BAD_GATEWAY | The server received an invalid response from the upstream server. | 502 | | SERVICE_UNAVAILABLE | The server is not ready to handle the request. | 503 | | GATEWAY_TIMEOUT | The server did not get a response in time from the upstream server that it needed in order to complete the request. | 504 | tRPC exposes a helper function, `getHTTPStatusCodeFromError`, to help you extract the HTTP code from the error: ```ts import { getHTTPStatusCodeFromError } from '@trpc/server/http'; // Example error you might get if your input validation fails const error: TRPCError = { name: 'TRPCError', code: 'BAD_REQUEST', message: '"password" must be at least 4 characters', }; if (error instanceof TRPCError) { const httpCode = getHTTPStatusCodeFromError(error); console.log(httpCode); // 400 } ``` > [!TIP] > > There's a full example of how error handling works in a server-side context in the [Server Side Calls docs](https://trpc.io/docs/server/server-side-calls.md). ## Throwing errors tRPC provides an error subclass, `TRPCError`, which you can use to represent an error that occurred inside a procedure. For example, throwing this error: ```ts title="server.ts" import { initTRPC, TRPCError } from '@trpc/server'; const t = initTRPC.create(); const theError = new Error('something went wrong'); const appRouter = t.router({ hello: t.procedure.query(() => { throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'An unexpected error occurred, please try again later.', // optional: pass the original error to retain stack trace cause: theError, }); }), }); // [...] ``` Results in the following response: ```json { "id": null, "error": { "message": "An unexpected error occurred, please try again later.", "code": -32603, "data": { "code": "INTERNAL_SERVER_ERROR", "httpStatus": 500, "stack": "...", "path": "hello" } } } ``` Throw a `TRPCError` with the code that fits, like `NOT_FOUND` or `FORBIDDEN`, so the client gets the right HTTP status. Any other error thrown in a procedure or middleware becomes an `INTERNAL_SERVER_ERROR` with the original error as its `cause`. > [!WARNING] > The `message` of an error you didn't throw as a `TRPCError` is still sent to the client, in production too. If your errors may contain internal details, [hide them in your error formatter](https://trpc.io/docs/server/error-formatting.md#hiding-internal-error-messages). ## Handling errors All errors that occur in a procedure go through the `onError` method before being sent to the client. Here you can handle errors (To change errors see [error formatting](https://trpc.io/docs/server/error-formatting.md)). ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './router'; const server = createHTTPServer({ router: appRouter, onError(opts) { const { error, type, path, input, ctx, req } = opts; console.error('Error:', error); if (error.code === 'INTERNAL_SERVER_ERROR') { // send to bug reporting } }, }); ``` The `onError` parameter is an object that contains all information about the error and the context it occurs in: ```ts interface OnErrorOpts { error: TRPCError; type: 'query' | 'mutation' | 'subscription' | 'unknown'; path: string | undefined; input: unknown; ctx: unknown; req: Request; } ``` --- Source: https://trpc.io/docs/server/error-formatting # Error Formatting > The error formatting in your router will be inferred all the way to your client. ## Usage example highlighted ### Adding custom formatting ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { ZodError } from 'zod'; export const t = initTRPC.create({ errorFormatter(opts) { const { shape, error } = opts; return { ...shape, data: { ...shape.data, zodError: error.code === 'BAD_REQUEST' && error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; }, }); ``` ### Usage in React ```tsx title="components/MyComponent.tsx" import { useMutation } from '@tanstack/react-query'; import { useEffect } from 'react'; import { useTRPC } from '../utils/trpc'; export function MyComponent() { const trpc = useTRPC(); const mutation = useMutation(trpc.addPost.mutationOptions()); useEffect(() => { mutation.mutate({ title: 'example' }); }, []); if (mutation.error?.data?.zodError) { // zodError will be inferred return (
Error: {JSON.stringify(mutation.error.data.zodError, null, 2)}
); } return <>[...]; } ``` ## Hiding internal error messages The default shape includes the error's `message`, even for unexpected errors such as a failed database query. To keep those details out of production responses, replace the message of `INTERNAL_SERVER_ERROR`s: ```ts title="server.ts" import { initTRPC } from '@trpc/server'; export const t = initTRPC.create({ errorFormatter(opts) { const { shape, error } = opts; if ( error.code === 'INTERNAL_SERVER_ERROR' && process.env.NODE_ENV === 'production' ) { return { ...shape, message: 'Internal server error' }; } return shape; }, }); ``` The full error, with its `cause`, still reaches your [`onError`](https://trpc.io/docs/server/error-handling.md#handling-errors) handler. ## Per-procedure error formatting Errors can be formatted on a per-procedure basis using the `.errors()` method, which can be chained to produce a union of possible error shapes for each procedure. When a middleware or procedure throws an error, it bubbles upward through all `.errors()` handlers until one returns a shape or the global errorFormatter is reached. ```ts title="server.ts" const rateLimitedProcedure = t.procedure .errors((opts) => { if (opts.error.cause instanceof RateLimitError) { return { ...opts.shape, data: { ...opts.shape.data, kind: 'RATE_LIMIT' as const }, }; } return undefined; }) .use(opts => { // Important: errors bubble up so a throwing middleware must come after the .errors() handler if (isRateLimited(opts)) { throw new RateLimitError(); } return opts.next(); }); const billedProcedure = rateLimitedProcedure .errors((opts) => { if (opts.error.cause instanceof PaymentRequiredError) { return { ...opts.shape, data: { ...opts.shape.data, kind: 'PAYMENT_REQUIRED' as const, amountDue: opts.error.cause.amountDue, }, }; } return undefined; }); const addPostProcedure = billedProcedure.mutation(opts => { if (isPaymentRequired(opts)) { throw new PaymentRequiredError(100); } return { success: true, }; }); ``` ## All properties sent to `errorFormatter()` > tRPC is compliant with [JSON-RPC 2.0](https://www.jsonrpc.org/specification) ```ts interface ErrorFormatterOpts { error: TRPCError; type: 'query' | 'mutation' | 'subscription' | 'unknown'; path: string | undefined; input: unknown; ctx: unknown; shape: { message: string; code: number; data: unknown }; } ``` **`DefaultErrorShape`:** ```ts type DefaultErrorData = { code: TRPC_ERROR_CODE_KEY; httpStatus: number; /** * Path to the procedure that threw the error */ path?: string; /** * Stack trace of the error (only in development) */ stack?: string; }; interface DefaultErrorShape { message: string; code: TRPC_ERROR_CODE_NUMBER; data: DefaultErrorData; } ``` --- Source: https://trpc.io/docs/server/data-transformers # Data Transformers > You are able to serialize the response data & input args. The transformers need to be added both to the server and the client. > [!NOTE] Info > A transformer is optional. Without one, tRPC serializes data with `JSON.stringify`, so values that JSON can't represent don't round-trip: a `Date` arrives on the client as a string, and a `Map` or `Set` are always converted to an empty object (`{}`). Add a transformer like superjson (below) if you need those types preserved on the client. ## Using [superjson](https://github.com/blitz-js/superjson) SuperJSON allows us to transparently use, e.g., standard `Date`/`Map`/`Set`s over the wire between the server and client. That is, you can return any of these types from your API-resolver and use them in the client without having to recreate the objects from JSON. ### How to #### 1. Install ```package-install superjson ``` #### 2. Add to your `initTRPC` ```ts title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import superjson from 'superjson'; export const t = initTRPC.create({ transformer: superjson, }); ``` #### 3. Add to `httpLink()`, `wsLink()`, etc > TypeScript will guide you to where you need to add `transformer` as soon as you've added it on the `initTRPC`-object `createTRPCClient()`: ```ts title="src/app/_trpc/client.ts" import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server'; import superjson from 'superjson'; export const client = createTRPCClient({ links: [ httpLink({ url: 'http://localhost:3000', transformer: superjson, }), ], }); ``` Every terminating link needs the transformer, including both branches of a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md). With [`wsLink`](https://trpc.io/docs/client/links/wsLink.md), it goes on `wsLink()`, not `createWSClient()`. ```ts title="src/app/_trpc/client.ts" import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; import superjson from 'superjson'; export const client = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: 'http://localhost:3000', transformer: superjson, }), false: httpBatchLink({ url: 'http://localhost:3000', transformer: superjson, }), }), ], }); ``` Now a `Date` returned by a procedure is a `Date` on the client: ```ts title="src/usage.ts" const event = await client.event.query(); event.at.getFullYear(); // (property) at: Date ``` ## Using [devalue](https://github.com/Rich-Harris/devalue) Devalue works like superjson, focusing on performance and compact payloads, but at the cost of a less human-readable body. ### How to #### 1. Install ```package-install devalue ``` #### 2. Add to `utils/trpc.ts` Here we use `parse` and `stringify` as they [mitigate XSS](https://github.com/Rich-Harris/devalue?tab=readme-ov-file#xss-mitigation). ```ts title="utils/trpc.ts" import { parse, stringify } from 'devalue'; // [...] export const transformer = { deserialize: (object: any) => parse(object), serialize: (object: any) => stringify(object), }; ``` #### 3. Add to your `initTRPC` ```ts title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import { transformer } from '../../utils/trpc'; export const t = initTRPC.create({ transformer, }); ``` #### 4. Add to `httpLink()`, `wsLink()`, etc > TypeScript will guide you to where you need to add `transformer` as soon as you've added it on the `initTRPC`-object `createTRPCClient()`: ```ts title="src/app/_trpc/client.ts" import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server/routers/_app'; import { transformer } from './utils/trpc'; export const client = createTRPCClient({ links: [ httpLink({ url: 'http://localhost:3000', transformer, }), ], }); ``` ## Different transformers for upload and download If a transformer should only be used for one direction or different transformers should be used for upload and download (e.g., for performance reasons), you can provide individual transformers for upload and download. Make sure you use the same combined transformer everywhere. ## `DataTransformer` interface ```ts export interface DataTransformer { serialize(object: any): any; deserialize(object: any): any; } interface InputDataTransformer extends DataTransformer { /** * This function runs **on the client** before sending the data to the server. */ serialize(object: any): any; /** * This function runs **on the server** to transform the data before it is passed to the resolver */ deserialize(object: any): any; } interface OutputDataTransformer extends DataTransformer { /** * This function runs **on the server** before sending the data to the client. */ serialize(object: any): any; /** * This function runs **only on the client** to transform the data sent from the server. */ deserialize(object: any): any; } export interface CombinedDataTransformer { /** * Specify how the data sent from the client to the server should be transformed. */ input: InputDataTransformer; /** * Specify how the data sent from the server to the client should be transformed. */ output: OutputDataTransformer; } ``` ## Common mistakes - **A transformer on only one side, or on only some links.** As long as the client is typed with your `AppRouter`, TypeScript catches this: a link without `transformer` fails with `Property 'transformer' is missing`, and a `transformer` on the client when the server has none fails with ``You must define a transformer on your `initTRPC`-object first``. If the types are bypassed, the mismatch shows up at runtime instead: data arrives still encoded (superjson's `{ json, meta }` wrapper), or calls fail with `Unable to transform response from server`. - **Creating a link outside the `links` array.** A link created on its own, for example inside a custom link, isn't checked against your router, so a missing transformer isn't reported. Pass the router type, as in `httpBatchLink({ url, transformer })`, to get the check back. - **Passing `transformer` to `createTRPCClient()`.** TypeScript rejects it with `The transformer property has moved to httpLink/httpBatchLink/wsLink`. - **Forgetting to transform data you hydrate yourself.** The links only transform tRPC requests and responses. If you dehydrate a TanStack Query cache on the server and hydrate it on the client, also set `serializeData` and `deserializeData`, as shown in [the Query Client factory](https://trpc.io/docs/client/tanstack-react-query/server-components.md#3-create-a-query-client-factory). --- Source: https://trpc.io/docs/server/non-json-content-types # Content Types > tRPC supports multiple content types as procedure inputs: JSON-serializable data, FormData, File, Blob, and other binary types. ## JSON (Default) By default, tRPC sends and receives JSON-serializable data. No extra configuration is needed β€” any input that can be serialized to JSON works out of the box with all links (`httpLink`, `httpBatchLink`, `httpBatchStreamLink`). ```ts import { z } from 'zod'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure.input(z.object({ name: z.string() })).query((opts) => { return { greeting: `Hello ${opts.input.name}` }; }), }); ``` ## Non-JSON Content Types In addition to JSON, tRPC can use FormData, File, and other binary types as procedure inputs. ### Client Setup > [!NOTE] Info > While tRPC natively supports several non-JSON serializable types, your client may need a little link configuration to support them depending on your setup. `httpLink` supports non-JSON content types out of the box β€” if you're only using this link, your existing setup should work immediately. ```ts import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server'; createTRPCClient({ links: [ httpLink({ url: 'http://localhost:2022', }), ], }); ``` However, not all links support these content types. If you're using `httpBatchLink` or `httpBatchStreamLink`, you will need to include a `splitLink` and route requests based on the content type. ```ts import { createTRPCClient, httpBatchLink, httpLink, isNonJsonSerializable, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; const url = 'http://localhost:2022'; createTRPCClient({ links: [ splitLink({ condition: (op) => isNonJsonSerializable(op.input), true: httpLink({ url, }), false: httpBatchLink({ url, }), }), ], }); ``` If you are using `transformer` in your tRPC server, TypeScript requires that your tRPC client link defines `transformer` as well. Use this example as a base: ```ts import { createTRPCClient, httpBatchLink, httpLink, isNonJsonSerializable, splitLink, } from '@trpc/client'; import superjson from 'superjson'; import type { AppRouter } from './server'; const url = 'http://localhost:2022'; createTRPCClient({ links: [ splitLink({ condition: (op) => isNonJsonSerializable(op.input), true: httpLink({ url, transformer: { // request - convert data before sending to the tRPC server serialize: (data) => data, // response - convert the tRPC response before using it in client deserialize: (data) => superjson.deserialize(data), // or your other transformer }, }), false: httpBatchLink({ url, transformer: superjson, // or your other transformer }), }), ], }); ``` ### Server Setup > [!NOTE] Info > When a request is handled by tRPC, it takes care of parsing the request body based on the `Content-Type` header of the request. > If you encounter errors like `Failed to parse body as XXX`, make sure that your server (e.g., Express, Next.js) isn't parsing the request body before tRPC handles it: > > - Express: see [Body parsers](https://trpc.io/docs/server/adapters/express.md#body-parsers). > - Next.js Pages Router: turn off Next's body parser in the tRPC API route with `export const config = { api: { bodyParser: false } }`, as in our [FormData example](https://github.com/trpc/trpc/tree/main/examples/next-formdata). #### `FormData` Input FormData is natively supported, and for more advanced usage you could also combine this with a library like [zod-form-data](https://www.npmjs.com/package/zod-form-data) to validate inputs in a type-safe way. ```ts import { z } from 'zod'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ hello: publicProcedure.input(z.instanceof(FormData)).mutation((opts) => { const data = opts.input; // const data: FormData return { greeting: `Hello ${data.get('name')}`, }; }), }); ``` On the client, pass a `FormData` instance to the mutation: ```ts const form = new FormData(); form.append('name', 'Bilbo'); const result = await client.hello.mutate(form); // const result: { // greeting: string; // } ``` For a more advanced code sample you can see our [example project here](https://github.com/juliusmarminge/trpc-interop/blob/66aa760141030ffc421cae1a3bda9b5f1ab340b6/src/server.ts#L28-L43) #### `File` and other Binary Type Inputs tRPC converts many octet content types to a `ReadableStream` which can be consumed in a procedure. Currently these are `Blob` `Uint8Array` and `File`. ```ts import { octetInputParser } from '@trpc/server/http'; export const t = initTRPC.create(); const publicProcedure = t.procedure; export const appRouter = t.router({ upload: publicProcedure.input(octetInputParser).mutation(async (opts) => { const data = opts.input; // const data: ReadableStream const reader = data.getReader(); let bytes = 0; while (true) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; } return { bytes }; }), }); ``` On the client, pass a `File`, `Blob` or `Uint8Array` to the mutation: ```ts const file = new File(['hello world'], 'hello.txt', { type: 'text/plain' }); await client.upload.mutate(file); ``` ## Common mistakes - **Using a query.** FormData and binary inputs are sent as the body of a `POST` request, so they only work with mutations: for a query, `httpLink` throws `FormData is only supported for mutations` or `Octet type input is only supported for mutations`. The exception is an `httpLink` with `methodOverride: 'POST'`, which sends every call as a `POST` and so also sends FormData and binary inputs for queries; the server must [allow the method override](https://trpc.io/docs/rpc.md#overriding-the-default-http-method). - **Sending them through a batching link.** `httpBatchLink`, `httpBatchStreamLink` and `wsLink` (with its default encoder) serialize inputs as JSON, which turns a `FormData` or `File` into `{}`, so input validation fails. Route them to `httpLink` with a [`splitLink`](#client-setup). Only `httpLink` sends non-JSON inputs: | Link | `application/json` | `FormData` | `File` / `Blob` / `Uint8Array` | | --------------------------------------------------------------- | :----------------: | :---------: | :----------------------------: | | [`httpLink`](https://trpc.io/docs/client/links/httpLink.md) | βœ… | βœ… (`POST`) | βœ… (`POST`) | | [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md) | βœ… | ❌ | ❌ | | [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md) | βœ… | ❌ | ❌ | | [`wsLink`](https://trpc.io/docs/server/websockets.md) | βœ… | ❌ | ❌ | With a binary `experimental_encoder` such as MessagePack, `wsLink` can carry `Uint8Array` values, as in the [WebSocket encoder example](https://github.com/trpc/trpc/tree/main/examples/next-websockets-encoder). - **Transforming the request.** tRPC passes FormData and binary inputs to your procedure as they are, without your `transformer`. If you use one, give the non-JSON `httpLink` a transformer that leaves the request alone, as [shown above](#client-setup). - **Letting your server parse the body first.** See [Server Setup](#server-setup). --- Source: https://trpc.io/docs/server/metadata # Metadata > Procedure metadata allows you to add an optional procedure specific `meta` property which will be available in all [middleware](https://trpc.io/docs/server/middlewares.md) function parameters. > [!TIP] > Use metadata together with [`trpc-openapi`](https://github.com/jlalmes/trpc-openapi) if you want to expose REST-compatible endpoints for your application. ## Create router with typed metadata ```tsx import { initTRPC } from '@trpc/server'; type Context = { user: { name: string } | null }; interface Meta { authRequired: boolean; } export const t = initTRPC.context().meta().create(); export const appRouter = t.router({ // [...] }); ``` ## Example with per route authentication settings ```tsx title="server.ts" import { initTRPC, TRPCError } from '@trpc/server'; type Context = { user: { name: string } | null }; interface Meta { authRequired: boolean; } export const t = initTRPC.context().meta().create(); export const authedProcedure = t.procedure.use(async (opts) => { const { meta, next, ctx } = opts; // only check authorization if enabled if (meta?.authRequired && !ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return next(); }); export const appRouter = t.router({ hello: authedProcedure.meta({ authRequired: false }).query(() => { return { greeting: 'hello world', }; }), protectedHello: authedProcedure.meta({ authRequired: true }).query(() => { return { greeting: 'hello-world', }; }), }); ``` ## Default meta, chaining, and shallow merging You can set default values for your meta type, and if you chain meta on top of a base procedure it will be shallow merged. ```tsx import { initTRPC } from '@trpc/server'; type Context = { user: { name: string } | null }; interface Meta { authRequired?: boolean; role?: 'user' | 'admin' } export const t = initTRPC .context() .meta() .create({ // Set a default value defaultMeta: { authRequired: false } }); const authMiddleware = t.middleware((opts) => opts.next()); const publicProcedure = t.procedure // ^ Default Meta: { authRequired: false } const authProcedure = publicProcedure .use(authMiddleware) .meta({ authRequired: true, role: 'user' }); // ^ Meta: { authRequired: true, role: 'user' } const adminProcedure = authProcedure .meta({ role: 'admin' }); // ^ Meta: { authRequired: true, role: 'admin' } ``` --- Source: https://trpc.io/docs/server/caching # Response Caching > Since all tRPC queries are normal HTTP `GET` requests, you can use standard HTTP cache headers to cache responses. This can make responses snappy, give your database a rest, and help scale your API. > [!NOTE] Info > Always be careful with caching - especially if you handle personal information. > >   > Since batching is enabled by default, it's recommended to set your cache headers in the `responseMeta` function and make sure that there are not any concurrent calls that may include personal data - or to omit cache headers completely if there is an auth header or cookie. > >   > You can also use a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md) to split your public requests and those that should be private and uncached. ## Using `responseMeta` to cache responses Most tRPC adapters support a `responseMeta` callback that lets you set HTTP headers (including cache headers) based on the procedures being called. > This works with any hosting provider that supports standard HTTP cache headers (e.g. Vercel, Cloudflare, AWS CloudFront). ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { createHTTPServer } from '@trpc/server/adapters/standalone'; import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; export const createContext = async (opts: CreateHTTPContextOptions) => { return { req: opts.req, res: opts.res, }; }; type Context = Awaited>; export const t = initTRPC.context().create(); const waitFor = async (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export const appRouter = t.router({ public: t.router({ slowQueryCached: t.procedure.query(async (opts) => { await waitFor(5000); // wait for 5s return { lastUpdated: new Date().toJSON(), }; }), }), }); // Exporting `type AppRouter` only exposes types that can be used for inference // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export export type AppRouter = typeof appRouter; // export API handler const server = createHTTPServer({ router: appRouter, createContext, responseMeta(opts) { const { info, errors, type, eagerGeneration } = opts; // assuming all your public routes are in the `public` router const allPublic = info?.calls.every((call) => call.path.startsWith('public.'), ); // checking that no procedures errored // (when streaming, headers are sent before any results are known) const allOk = !eagerGeneration && errors.length === 0; // checking we're doing a query request const isQuery = type === 'query'; if (allPublic && allOk && isQuery) { // cache request for 1 day + revalidate once every second const ONE_DAY_IN_SECONDS = 60 * 60 * 24; return { headers: new Headers([ [ 'cache-control', `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`, ], ]), }; } return {}; }, }); server.listen(3000); ``` `responseMeta` runs once per HTTP response, so with batching it decides the headers for every procedure in the batch: only cache if all of them are public. It also gets the request's `ctx`, e.g. to skip caching for signed-in users. For streamed responses, like those of [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md), the headers are sent before any procedure has finished, so `responseMeta` runs with `eagerGeneration: true` and an empty `errors` array. > [!TIP] > If you are using the Next.js Pages Router, see [Server-Side Rendering](https://trpc.io/docs/client/nextjs/pages-router/ssr.md#set-the-status-and-cache-headers) for caching pages in `getServerSideProps`, and for caching responses with the Next.js adapter. ## Next.js App Router With the App Router, tRPC runs in a [route handler](https://trpc.io/docs/client/nextjs/app-router-setup.md) with the fetch adapter. Next.js sends the route handler's `Response` as it is, so set `Cache-Control` in the `responseMeta` of `fetchRequestHandler`. Route segment config like `export const dynamic = 'force-dynamic'` or `export const revalidate = 60` doesn't change the header. ```ts title="app/api/trpc/[trpc]/route.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createTRPCContext } from './trpc/init'; import { appRouter } from './trpc/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: () => createTRPCContext({ headers: req.headers }), responseMeta(opts) { const { info, errors, type, eagerGeneration } = opts; // assuming all your public routes are in the `public` router const allPublic = info?.calls.every((call) => call.path.startsWith('public.'), ); const allOk = !eagerGeneration && errors.length === 0; const isQuery = type === 'query'; if (allPublic && allOk && isQuery) { return { headers: new Headers([ ['cache-control', 's-maxage=60, stale-while-revalidate=86400'], ]), }; } return {}; }, }); export { handler as GET, handler as POST }; ``` > [!WARNING] Caution > Don't set `Cache-Control` for your tRPC endpoint with [`headers` in `next.config.js`](https://nextjs.org/docs/app/api-reference/config/next-config-js/headers). In a production build it replaces the header from `responseMeta`, and it's added to every response on the matching path, including batches with private procedures, errors and mutations. ### Batching `responseMeta` runs once per batch, not once per procedure. With `httpBatchLink`, a public query made at the same time as a private one shares its request, so the response isn't cached. And a CDN caches each batch by its URL, which holds every procedure and input in the batch, so the same public query rarely hits the cache. Send cacheable public queries through `httpLink` with a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md), so each one is a `GET` request of its own, and keep batching the rest. `getUrl()` is the one from the [App Router setup](https://trpc.io/docs/client/nextjs/app-router-setup.md): ```ts title="trpc/client.tsx" import { createTRPCClient, httpBatchLink, httpLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './routers/_app'; const trpcClient = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'query' && op.path.startsWith('public.'), true: httpLink({ url: getUrl() }), false: httpBatchLink({ url: getUrl() }), }), ], }); ``` --- Source: https://trpc.io/docs/server/subscriptions # Subscriptions > ## Introduction Subscriptions are a type of real-time event stream between the client and server. Use subscriptions when you need to push real-time updates to the client. With tRPC's subscriptions, the client establishes and maintains a persistent connection to the server plus automatically attempts to reconnect and recover gracefully if disconnected with the help of [`tracked()`](#tracked) events. ## WebSockets or Server-sent Events? You can either use WebSockets or [Server-sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to setup real-time subscriptions in tRPC. - For WebSockets, see [the WebSockets page](https://trpc.io/docs/server/websockets.md) - For SSE, see the [httpSubscriptionLink](https://trpc.io/docs/client/links/httpSubscriptionLink.md) If you are unsure which one to use, we recommend using SSE for subscriptions as it's easier to setup and doesn't require setting up a WebSocket server. ## Reference projects | Type | Example Type | Link | | ---------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | WebSockets | Bare-minimum Node.js WebSockets example | [/examples/standalone-server](https://github.com/trpc/trpc/tree/main/examples/standalone-server) | | SSE | Full-stack SSE implementation | [github.com/trpc/examples-tanstack-start-sse-chat](https://github.com/trpc/examples-tanstack-start-sse-chat) | | WebSockets | Full-stack WebSockets implementation | [github.com/trpc/examples-next-prisma-websockets-starter](https://github.com/trpc/examples-next-prisma-starter-websockets) | ## Basic example > [!TIP] > For a full example, see [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat). ```ts title="server.ts" import EventEmitter, { on } from 'node:events'; import { initTRPC } from '@trpc/server'; const t = initTRPC.create(); type Post = { id: string; title: string }; const ee = new EventEmitter(); export const appRouter = t.router({ onPostAdd: t.procedure.subscription(async function* (opts) { // listen for new events for await (const [data] of on(ee, 'add', { // Passing the AbortSignal from the request automatically cancels the event emitter when the request is aborted signal: opts.signal, })) { const post = data as Post; yield post; } }), }); ``` ## Automatic tracking of id using `tracked()` (recommended) {#tracked} If you `yield` an event using our `tracked()`-helper and include an `id`, the client will automatically reconnect when it gets disconnected and send the last known ID. You can send an initial `lastEventId` when initializing the subscription and it will be automatically updated as the browser receives data. - For SSE, this is part of the [`EventSource`-spec](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header) and will be propagated through `lastEventId` in your `.input()`. - For WebSockets, our `wsLink` will automatically send the last known ID and update it as the browser receives data. > [!TIP] > If you're fetching data based on the `lastEventId`, and capturing all events is critical, make sure you set up the event listener before fetching events from your database as is done in [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat), this can prevent newly emitted events being ignored while yield'ing the original batch based on `lastEventId`. ```ts import EventEmitter, { on } from 'node:events'; import { initTRPC, tracked } from '@trpc/server'; import { z } from 'zod'; class IterableEventEmitter extends EventEmitter { toIterable(eventName: string, opts?: { signal?: AbortSignal }) { return on(this, eventName, opts); } } type Post = { id: string; title: string }; const t = initTRPC.create(); const publicProcedure = t.procedure; const router = t.router; const ee = new IterableEventEmitter(); export const subRouter = router({ onPostAdd: publicProcedure .input( z .object({ // lastEventId is the last event id that the client has received // On the first call, it will be whatever was passed in the initial setup // If the client reconnects, it will be the last event id that the client received lastEventId: z.string().nullish(), }) .optional(), ) .subscription(async function* (opts) { // We start by subscribing to the ee so that we don't miss any new events while fetching const iterable = ee.toIterable('add', { // Passing the AbortSignal from the request automatically cancels the event emitter when the request is aborted signal: opts.signal, }); if (opts.input?.lastEventId) { // [...] get the posts since the last event id and yield them // const items = await db.post.findMany({ ... }) // for (const item of items) { // yield tracked(item.id, item); // } } // listen for new events from the iterable we set up above for await (const [data] of iterable) { const post = data as Post; // tracking the post id ensures the client can reconnect at any time and get the latest events since this id yield tracked(post.id, post); } }), }); ``` ## Subscribing from the client Route subscriptions to [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md) (SSE) or [`wsLink`](https://trpc.io/docs/client/links/wsLink.md) with a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md), then call `.subscribe()` with the input and your callbacks. Tracked events arrive in `onData` as `{ id, data }`. ```ts title="client.ts" import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: 'http://localhost:3000' }), false: httpBatchLink({ url: 'http://localhost:3000' }), }), ], }); const subscription = client.onPostAdd.subscribe( { lastEventId: null }, { onData(event) { // (parameter) event: { // data: Post; // id: string; // } console.log(event.id, event.data.title); }, onError(err) { console.error(err); }, }, ); // stop listening subscription.unsubscribe(); ``` Without callbacks, `.subscribe()` returns an async iterator, so you can consume the subscription with `for await` instead. It has no `unsubscribe()`: leaving the loop or aborting the `signal` you passed unsubscribes, and errors are thrown from the loop. See [the vanilla client](https://trpc.io/docs/client/vanilla/setup.md#5-use-subscriptions) for the details. ```ts title="client.ts" for await (const event of client.onPostAdd.subscribe({ lastEventId: null })) { console.log(event.id, event.data.title); } ``` For React, see [`subscriptionOptions`](https://trpc.io/docs/client/tanstack-react-query/usage.md#subscriptionOptions) with TanStack React Query, or the deprecated classic [`useSubscription()`](https://trpc.io/docs/client/react/useSubscription.md). ## Pull data in a loop This recipe is useful when you want to periodically check for new data from a source like a database and push it to the client. ```ts title="server.ts" import { tracked } from '@trpc/server'; import { z } from 'zod'; import { publicProcedure, router } from './trpc'; export const subRouter = router({ onPostAdd: publicProcedure .input( z.object({ // lastEventId is the last event id that the client has received // On the first call, it will be whatever was passed in the initial setup // If the client reconnects, it will be the last event id that the client received // The id is the createdAt of the post lastEventId: z.coerce.date().nullish(), }), ) .subscription(async function* (opts) { // `opts.signal` is an AbortSignal that will be aborted when the client disconnects. let lastEventId = opts.input?.lastEventId ?? null; // We use a `while` loop that checks `!opts.signal.aborted` while (!opts.signal!.aborted) { const posts = await db.post.findMany({ // If we have a `lastEventId`, we only fetch posts created after it. where: lastEventId ? { createdAt: { gt: lastEventId, }, } : undefined, orderBy: { createdAt: 'asc', }, }); for (const post of posts) { // `tracked` is a helper that sends an `id` with each event. // This allows the client to resume from the last received event upon reconnection. yield tracked(post.createdAt.toJSON(), post); lastEventId = post.createdAt; } // Wait for a bit before polling again to avoid hammering the database. await sleep(1_000); } }), }); ``` ## Stopping a subscription from the server {#stopping-from-server} If you need to stop a subscription from the server, simply `return` in the generator function. ```ts export const subRouter = router({ onPostAdd: publicProcedure .input( z.object({ lastEventId: z.coerce.number().min(0).optional(), }), ) .subscription(async function* (opts) { let index = opts.input.lastEventId ?? 0; while (!opts.signal!.aborted) { const idx = index++; if (idx > 100) { // With this, the subscription will stop and the client will disconnect return; } await new Promise((resolve) => setTimeout(resolve, 10)); } }), }); ``` On the client, you just `.unsubscribe()` the subscription, or leave the `for await` loop. ## Cleanup of side effects If you need to clean up any side-effects of your subscription you can use the [`try...finally`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return#using_return_with_try...finally) pattern, as `trpc` invokes the `.return()` of the Generator Instance when the subscription stops for any reason. ```ts import EventEmitter, { on } from 'events'; import { initTRPC } from '@trpc/server'; type Post = { id: string; title: string }; const t = initTRPC.create(); const publicProcedure = t.procedure; const router = t.router; const ee = new EventEmitter(); export const subRouter = router({ onPostAdd: publicProcedure.subscription(async function* (opts) { let timeout: ReturnType | undefined; try { for await (const [data] of on(ee, 'add', { signal: opts.signal, })) { timeout = setTimeout(() => console.log('Pretend like this is useful')); const post = data as Post; yield post; } } finally { if (timeout) clearTimeout(timeout); } }), }); ``` ## Error handling Throwing an error in a generator function propagates to `trpc`'s `onError()` on the backend. If the error thrown is a 5xx error, the client will automatically attempt to reconnect based on the last event id that is [tracked using `tracked()`](#tracked). For other errors, the subscription will be cancelled and propagate to the `onError()` callback. ## Output validation {#output-validation} Since subscriptions are async iterators, you have to go through the iterator to validate the output. ### Example with Zod v4 ```ts title="zAsyncIterable.ts" import type { TrackedEnvelope } from '@trpc/server'; import { isTrackedEnvelope, tracked } from '@trpc/server'; import { z } from 'zod'; function isAsyncIterable( value: unknown, ): value is AsyncIterable { return !!value && typeof value === 'object' && Symbol.asyncIterator in value; } const trackedEnvelopeSchema = z.custom>(isTrackedEnvelope); /** * A Zod schema helper designed specifically for validating async iterables. This schema ensures that: * 1. The value being validated is an async iterable. * 2. Each item yielded by the async iterable conforms to a specified type. * 3. The return value of the async iterable, if any, also conforms to a specified type. */ export function zAsyncIterable< TYieldIn, TYieldOut, TReturnIn = void, TReturnOut = void, Tracked extends boolean = false, >(opts: { /** * Validate the value yielded by the async generator */ yield: z.ZodType; /** * Validate the return value of the async generator * @remarks not applicable for subscriptions */ return?: z.ZodType; /** * Whether the yielded values are tracked * @remarks only applicable for subscriptions */ tracked?: Tracked; }) { return z .custom< AsyncIterable< Tracked extends true ? TrackedEnvelope : TYieldIn, TReturnIn > >((val) => isAsyncIterable(val)) .transform(async function* (iter) { const iterator = iter[Symbol.asyncIterator](); try { let next; while ((next = await iterator.next()) && !next.done) { if (opts.tracked) { const [id, data] = trackedEnvelopeSchema.parse(next.value); yield tracked(id, await opts.yield.parseAsync(data)); continue; } yield opts.yield.parseAsync(next.value); } if (opts.return) { return await opts.return.parseAsync(next.value); } return; } finally { await iterator.return?.(); } }) as z.ZodType< AsyncIterable< Tracked extends true ? TrackedEnvelope : TYieldIn, TReturnIn, unknown >, AsyncIterable< Tracked extends true ? TrackedEnvelope : TYieldOut, TReturnOut, unknown > >; } ``` Now you can use this helper to validate the output of your subscription procedures: ```ts title="_app.ts" import { tracked } from '@trpc/server'; import { z } from 'zod'; import { publicProcedure, router } from './trpc'; import { zAsyncIterable } from './zAsyncIterable'; export const appRouter = router({ mySubscription: publicProcedure .input( z.object({ lastEventId: z.coerce.number().min(0).optional(), }), ) .output( zAsyncIterable({ yield: z.object({ count: z.number(), }), tracked: true, }), ) .subscription(async function* (opts) { let index = opts.input.lastEventId ?? 0; while (true) { index++; yield tracked(String(index), { count: index, }); await new Promise((resolve) => setTimeout(resolve, 1000)); } }), }); ``` ## Common mistakes - **Not passing `opts.signal` on.** Pass it to what you're waiting on, like `on(ee, 'add', { signal: opts.signal })`, or check `opts.signal.aborted` in loops. Otherwise your generator can keep waiting, with its listeners attached, after the client is gone. - **Fetching missed events before listening for new ones.** Events emitted in between are lost. Start listening first, as in the [`tracked()` example](#tracked). - **Tracking an event with an empty id.** `tracked('', data)` throws, since an empty id means "no id" in SSE. - **Returning an `observable()`.** Observable subscriptions are deprecated and will be removed in v12. Use an async generator. - **Pinging less often than the client reconnects.** With SSE, keep `sse.ping.intervalMs` lower than `sse.client.reconnectAfterInactivityMs`, or the client reconnects between pings. tRPC throws when the ping interval is the longer one. See [Server Ping Configuration](https://trpc.io/docs/client/links/httpSubscriptionLink.md#server-ping). --- Source: https://trpc.io/docs/server/websockets # WebSockets > You can use WebSockets for all or some of the communication with your server, see [wsLink](https://trpc.io/docs/client/links/wsLink.md) for how to set it up on the client. > [!TIP] > The document here outlines the specific details of using WebSockets. For general usage of subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions.md). ### Creating a WebSocket-server ```bash yarn add ws ``` ```ts title="server/wsServer.ts" import { applyWSSHandler } from '@trpc/server/adapters/ws'; import { WebSocketServer } from 'ws'; import { appRouter } from './routers/app'; import { createContext } from './trpc'; const wss = new WebSocketServer({ port: 3001, }); const handler = applyWSSHandler({ wss, router: appRouter, createContext, // Enable heartbeat messages to keep connection open (disabled by default) keepAlive: { enabled: true, // server ping message interval in milliseconds pingMs: 30000, // connection is terminated if pong message is not received in this many milliseconds pongWaitMs: 5000, }, }); wss.on('connection', (ws) => { console.log(`++ Connection (${wss.clients.size})`); ws.once('close', () => { console.log(`-- Connection (${wss.clients.size})`); }); }); console.log('WebSocket Server listening on ws://localhost:3001'); process.on('SIGTERM', () => { console.log('SIGTERM'); handler.broadcastReconnectNotification(); wss.close(); }); ``` ### Sharing a port with your HTTP server To serve HTTP and WebSockets on the same port, pass your HTTP server to `WebSocketServer`. `ws` then handles the upgrade requests, and your adapter handles the rest. ```ts title="server/index.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { applyWSSHandler } from '@trpc/server/adapters/ws'; import { WebSocketServer } from 'ws'; import { appRouter } from './router'; const server = createHTTPServer({ router: appRouter }); const wss = new WebSocketServer({ server }); applyWSSHandler({ wss, router: appRouter }); server.listen(3000); ``` ### Limiting batch size `applyWSSHandler` accepts the same `maxBatchSize` option as the [HTTP adapters](https://trpc.io/docs/server/adapters.md#common-options). A WebSocket message that batches more requests than this is rejected as a whole: no procedure runs, and every request in it, except `subscription.stop` entries, gets a `BAD_REQUEST` error with the message `Batch call exceeds maximum size`. `wsLink` sends all requests made in the same tick as one message and has no `maxItems` option, so pick a limit above the number of calls your client makes at once. ### Rejecting cross-origin connections Browsers don't apply CORS to WebSockets: a page on any origin can open a connection to your server, and the browser sends its cookies with it. If you authenticate with cookies, check the `Origin` header against the origins you trust. With `ws`, do this in `verifyClient`, and pass `403` to its callback so a rejected upgrade gets `403 Forbidden`: ```ts title="server/wsServer.ts" import { applyWSSHandler } from '@trpc/server/adapters/ws'; import { WebSocketServer } from 'ws'; import { appRouter } from './router'; const allowedOrigins = new Set(['https://app.example.com']); const wss = new WebSocketServer({ port: 3001, verifyClient: ({ origin }, callback) => { // Browsers always send `Origin`, but other clients may not. // Decide whether your app accepts connections without one. callback(!origin || allowedOrigins.has(origin), 403); }, }); applyWSSHandler({ wss, router: appRouter }); ``` If you handle upgrades yourself with `noServer: true`, check `req.headers.origin` in your server's `upgrade` listener instead. For an origin you don't trust, end the socket with a `403` response, such as `socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')`, rather than calling `wss.handleUpgrade()`. ### Setting `TRPCClient` to use WebSockets > [!TIP] > You can use [Links](https://trpc.io/docs/client/links.md) to route queries and/or mutations to HTTP transport and subscriptions over WebSockets. ```tsx title="client.ts" import { createTRPCClient, createWSClient, wsLink } from '@trpc/client'; import type { AppRouter } from './server'; // create persistent WebSocket connection const wsClient = createWSClient({ url: `ws://localhost:3001`, }); // configure TRPCClient to use WebSockets transport const client = createTRPCClient({ links: [ wsLink({ client: wsClient, }), ], }); ``` ## Authentication / connection params {#connectionParams} > [!TIP] > If you're doing a web application, you can ignore this section as the cookies are sent as part of the request. In order to authenticate with WebSockets, you can define `connectionParams` to `createWSClient`. This will be sent as the first message when the client establishes a WebSocket connection. ```ts title="server/context.ts" import type { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws'; export const createContext = async (opts: CreateWSSContextFnOptions) => { const token = opts.info.connectionParams?.token; // const token: string | undefined // [... authenticate] return {}; }; export type Context = Awaited>; ``` ```ts title="client/trpc.ts" import { createTRPCClient, createWSClient, wsLink } from '@trpc/client'; import type { AppRouter } from './server'; import superjson from 'superjson'; const wsClient = createWSClient({ url: `ws://localhost:3000`, connectionParams: async () => { return { token: 'supersecret', }; }, }); export const trpc = createTRPCClient({ links: [wsLink({ client: wsClient, transformer: superjson })], }); ``` `createContext` runs once per connection (after the connection params arrive, if you send them), and every call over that connection shares its result. If it throws, the server sends the error and closes the connection. A token is only checked when the connection opens, so it stays accepted on that connection after it expires. ## Automatic tracking of id using `tracked()` (recommended) If you `yield` an event using our `tracked()`-helper and include an `id`, the client will automatically reconnect when it gets disconnected and send the last known ID when reconnecting as part of the `lastEventId`-input. You can send an initial `lastEventId` when initializing the subscription and it will be automatically updated as the browser receives data. > [!NOTE] Info > If you're fetching data based on the `lastEventId`, and capturing all events is critical, you may want to use `ReadableStream`'s or a similar pattern as an intermediary as is done in [our full-stack SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat) to prevent newly emitted events being ignored while yield'ing the original batch based on `lastEventId`. ```ts import EventEmitter, { on } from 'events'; import { initTRPC, tracked } from '@trpc/server'; import { z } from 'zod'; type Post = { id: string; title: string }; const t = initTRPC.create(); const publicProcedure = t.procedure; const router = t.router; const ee = new EventEmitter(); export const subRouter = router({ onPostAdd: publicProcedure .input( z .object({ // lastEventId is the last event id that the client has received // On the first call, it will be whatever was passed in the initial setup // If the client reconnects, it will be the last event id that the client received lastEventId: z.string().nullish(), }) .optional(), ) .subscription(async function* (opts) { if (opts.input?.lastEventId) { // [...] get the posts since the last event id and yield them } // listen for new events for await (const [data] of on(ee, 'add', { // Passing the AbortSignal from the request automatically cancels the event emitter when the subscription is aborted signal: opts.signal, })) { const post = data as Post; // tracking the post id ensures the client can reconnect at any time and get the latest events since this id yield tracked(post.id, post); } }), }); ``` ## WebSockets RPC Specification > You can read more details by drilling into the TypeScript definitions: > > - [/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts) > - [/packages/server/src/unstable-core-do-not-import/rpc/codes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/codes.ts). ### `query` / `mutation` #### Request ```ts interface RequestMessage { id: number | string; jsonrpc?: '2.0'; method: 'query' | 'mutation'; params: { path: string; input?: unknown; // <-- pass input of procedure, serialized by transformer }; } ``` #### Response _... below, or an error._ ```ts interface ResponseMessage { id: number | string; jsonrpc?: '2.0'; result: { type: 'data'; // always 'data' for mutation / queries data: TOutput; // output from procedure }; } ``` ### `subscription` / `subscription.stop` #### Start a subscription ```ts interface SubscriptionRequest { id: number | string; jsonrpc?: '2.0'; method: 'subscription'; params: { path: string; input?: unknown; // <-- pass input of procedure, serialized by transformer }; } ``` #### To cancel a subscription, call `subscription.stop` ```ts interface SubscriptionStopRequest { id: number | string; // <-- id of your created subscription jsonrpc?: '2.0'; method: 'subscription.stop'; } ``` #### Subscription response shape _... below, or an error._ ```ts interface SubscriptionResponse { id: number | string; jsonrpc?: '2.0'; result: | { type: 'data'; data: TData; // subscription emitted data } | { type: 'started'; // subscription started } | { type: 'stopped'; // subscription stopped }; } ``` #### Connection params If the connection is initialized with `?connectionParams=1`, the first message has to be connection params. ```ts interface ConnectionParamsMessage { data: Record | null; method: 'connectionParams'; } ``` ## Errors See [https://www.jsonrpc.org/specification#error_object](https://www.jsonrpc.org/specification#error_object) or [Error Formatting](https://trpc.io/docs/server/error-formatting.md). ## Notifications from Server to Client ### `{ id: null, type: 'reconnect' }` Tells clients to reconnect before shutting down the server. Invoked by `wssHandler.broadcastReconnectNotification()`. --- Source: https://trpc.io/docs/server/service-oriented-architecture # Service-Oriented Architecture > A tRPC backend doesn't have to run as one server. You can split your routers across several services, each deployed on its own, and still call them all through one fully typed client. > [!WARNING] Caution > You probably don't need this. Splitting a tRPC API into services adds moving parts, and every service still has to share the same context type, error formatter and transformer. If you're not sure you need it, stick to a single router and [merge routers](https://trpc.io/docs/server/merging-routers.md) instead. The setup has four parts: - a **shared library** that creates the one tRPC instance every service uses - the **services**, each with its own router and server - a **faux gateway**, which merges the service routers into one `AppRouter` type but never runs - a **client** with a custom terminating link that sends each call to the service that owns it A runnable version is in the [SOA example](https://github.com/trpc/trpc/tree/main/examples/soa). ## 1. Share one tRPC instance Put `initTRPC` in a library that every service imports. This is what guarantees that the services agree on context, error formatting and transformer, so their routers can be typed together. ```ts title="server-lib/index.ts" import { initTRPC } from '@trpc/server'; type Context = { requestId?: string; }; const t = initTRPC.context().create(); export const router = t.router; export const publicProcedure = t.procedure; ``` ## 2. Build and serve each service Each service defines its own router with the shared helpers and runs its own server. Here they use the [standalone adapter](https://trpc.io/docs/server/adapters/standalone.md), but any adapter works. ```ts title="server-a/router.ts" import { z } from 'zod'; import { publicProcedure, router } from '../server-lib'; export const serverARouter = router({ greet: publicProcedure .input(z.string()) .query(({ input }) => ({ greeting: `hello, ${input}!` })), }); ``` ```ts title="server-a/index.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { serverARouter } from './router'; createHTTPServer({ router: serverARouter, createContext() { return {}; }, }).listen(2021); ``` `server-b` looks the same, with its own router, `serverBRouter`, listening on port 2022. ## 3. Combine the types in a faux gateway The gateway merges the service routers under one name each, and exports the result's type. It's never deployed or run: the client only imports its `AppRouter` type, so none of the services' code ends up in the client. ```ts title="faux-gateway/index.ts" import { serverARouter } from '../server-a/router'; import { serverBRouter } from '../server-b/router'; import { router } from '../server-lib'; const appRouter = router({ serverA: serverARouter, serverB: serverBRouter, }); export type AppRouter = typeof appRouter; ``` ## 4. Route calls to the right service On the client, a [custom link](https://trpc.io/docs/client/links.md#creating-a-custom-link) reads the first segment of each procedure path, `serverA` in `serverA.greet`, and forwards the call to that service's link with the segment removed, since the service itself only knows `greet`. ```ts title="client/client.ts" import { createTRPCClient, httpBatchLink, type TRPCLink } from '@trpc/client'; import type { AppRouter } from '../faux-gateway'; const serviceLink: TRPCLink = (runtime) => { // Created once, so calls to the same service are batched together const services = { serverA: httpBatchLink({ url: 'http://localhost:2021' })(runtime), serverB: httpBatchLink({ url: 'http://localhost:2022' })(runtime), }; return (ctx) => { const [name, ...rest] = ctx.op.path.split('.'); const link = services[name as keyof typeof services]; if (!link) { throw new Error(`No service for procedure "${ctx.op.path}"`); } return link({ ...ctx, op: { ...ctx.op, path: rest.join('.') } }); }; }; export const client = createTRPCClient({ links: [serviceLink], }); ``` Each service gets its own link, so each can have its own options, such as [headers](https://trpc.io/docs/client/headers.md). Calls are fully typed through the gateway's `AppRouter`: ```ts title="client/index.ts" import { client } from './client'; const { greeting } = await client.serverA.greet.query('tRPC'); // const greeting: string const status = await client.serverB.status.query(); // const status: "ok" ``` ## Common mistakes - **Forwarding the full path.** If the link doesn't strip the service name, the service is asked for `serverA.greet` and answers with `No procedure found on path "serverA.greet"`. - **Creating the service links per call.** `httpBatchLink(...)(runtime)` sets up a new batch queue each time it runs, so create the service links once, in the setup function, as shown above. Otherwise nothing gets batched. - **Using a separate `initTRPC` in each service.** The gateway's `AppRouter` can only describe one context, error shape and transformer, so give every service the same instance from the shared library. - **Leaving the router type off the service links.** Links created inside a custom link aren't checked against your router. Pass ``, as in `httpBatchLink(...)`, so TypeScript still requires a [transformer](https://trpc.io/docs/server/data-transformers.md) when you use one. - **Running the gateway.** The faux gateway only exists for its type. Each service serves its own router, and the client talks to the services directly. --- Source: https://trpc.io/docs/client # Client Overview > While a tRPC API can be called using normal HTTP requests like any other REST API, you will need a **client** to benefit from tRPC's typesafety. A client knows the procedures that are available in your API, and their inputs and outputs. It uses this information to give you autocomplete on your queries and mutations, correctly type the returned data, and show errors if you are writing requests that don't match the shape of your backend. If you are using React, the recommended way to call a tRPC API is by using our [TanStack React Query Integration](https://trpc.io/docs/client/tanstack-react-query/setup.md), which in addition to typesafe API calls also offers caching, invalidation, and management of loading and error state. If you are using Next.js, see the [Next.js integration](https://trpc.io/docs/client/nextjs.md): it uses the same TanStack React Query integration, with the App Router or the Pages Router. If you want to call a tRPC API from another server or from a frontend framework for which we don't have an integration, you can use the [Vanilla Client](https://trpc.io/docs/client/vanilla.md). In addition to the React and Next.js integrations and the Vanilla Client, there are a variety of [community-built integrations for other frameworks](https://trpc.io/docs/community/awesome-trpc.md#frontend-frameworks). Please note that these are not maintained by the tRPC team. --- Source: https://trpc.io/docs/client/links # Links Overview > Links enable you to customize the flow of data between the tRPC Client and Server. A link should do only one thing, which can be either a self-contained modification to a tRPC operation (query, mutation, or subscription) or a side-effect based on the operation (such as logging). You can compose links together into an array that you can provide to the tRPC client configuration via the `links` property, which represents a link chain. This means that the tRPC client will execute the links in the order they are added to the `links` array when doing a request and will execute them again in reverse when it's handling a response. Here's a visual representation of the link chain:
tRPC Link Diagram tRPC Link Diagram. Based on Apollo's.
```ts title="utils/trpc.ts" import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client'; import type { AppRouter } from './server'; export const trpc = createTRPCClient({ links: [ loggerLink(), httpBatchLink({ url: 'http://localhost:3000', }), ], }); ``` ## Creating a custom link A link is a function that follows the `TRPCLink` type. Each link is composed of three parts: 1. The link returns a function that has no parameters. This is the setup phase where the link is initialized β€” it happens once per app and is useful for storing caches or other state. 2. The function in step 1 returns another function that receives an object with two properties: `op` which is the `Operation` that is being executed by the client, and `next` which is the function we use to call the next link down the chain. 3. The function in step 2 returns a final function that returns the `observable` function provided by `@trpc/server`. The `observable` accepts a function that receives an `observer` which helps our link notify the next link up the chain how they should handle the operation result. In this function, we can just return `next(op)` and leave it as is, or we can subscribe to `next`, which enables our link to handle the operation result. ### Example ```tsx title="utils/customLink.ts" import { TRPCLink } from '@trpc/client'; import { observable } from '@trpc/server/observable'; import type { AppRouter } from './server'; export const customLink: TRPCLink = () => { // here we just got initialized in the app - this happens once per app // useful for storing cache for instance return ({ next, op }) => { // this is when passing the result to the next link // each link needs to return an observable which propagates results return observable((observer) => { console.log('performing operation:', op); const unsubscribe = next(op).subscribe({ next(value) { console.log('we received value', value); observer.next(value); }, error(err) { console.log('we received error', err); observer.error(err); }, complete() { observer.complete(); }, }); return unsubscribe; }); }; }; ``` ### References If you need a more real reference for creating your custom link, you can check out some of the built-in links tRPC provides on [GitHub](https://github.com/trpc/trpc/tree/main/packages/client/src/links). ## The terminating link The **terminating link** is the last link in a link chain. Instead of calling the `next` function, the terminating link is responsible for sending your composed tRPC operation to the tRPC server and returning an `OperationResultEnvelope`. The `links` array that you add to the tRPC client config should have at least one link, and that link should be a terminating link. If `links` don't have a terminating link at the end of them, the tRPC operation will not be sent to the tRPC server. [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md) is the recommended terminating link by tRPC. Pick another one depending on your needs: | Link | Use it for | | --- | --- | | [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md) | Queries and mutations. Calls made together, for example in a `Promise.all`, are sent as one HTTP request. | | [`httpLink`](https://trpc.io/docs/client/links/httpLink.md) | One HTTP request per call, for example to [skip batching](https://trpc.io/docs/client/links/splitLink.md#disable-batching-for-certain-requests) or to send [`FormData` and binary inputs](https://trpc.io/docs/server/non-json-content-types.md). | | [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md) | Batching, but each response is streamed as soon as it's ready. Required for procedures that return async generators or promises nested in the output. | | [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md) | Subscriptions over Server-sent Events. | | [`wsLink`](https://trpc.io/docs/client/links/wsLink.md) | Any operation over a WebSocket. | | [`unstable_localLink`](https://trpc.io/docs/client/links/localLink.md) | Calling a router in the same process, without HTTP. | The HTTP links don't handle subscriptions, so to use subscriptions alongside them, route by operation type with a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md): ```ts title="utils/trpc.ts" import { createTRPCClient, httpBatchLink, httpSubscriptionLink, loggerLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; export const trpc = createTRPCClient({ links: [ loggerLink(), splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: 'http://localhost:3000' }), false: httpBatchLink({ url: 'http://localhost:3000' }), }), ], }); ``` ## Managing context As an operation moves along your link chain, it maintains a context that each link can read and modify. This allows links to pass metadata along the chain that other links use in their execution logic. Obtain the current context object and modify it by accessing `op.context`. You can set the context object's initial value for a particular operation by providing the context parameter to the `query` or `useQuery` hook (or `mutation`, `subscription`, etc.). For an example use case, see [Disable batching for certain requests](https://trpc.io/docs/client/links/splitLink.md#disable-batching-for-certain-requests). ## Common mistakes - **No terminating link at the end of the chain.** Calls fail with `No more links to execute - did you forget to add an ending link?`. Links listed after the terminating link never run, so put `loggerLink`, `retryLink` and your own links before it. - **A `splitLink` branch without a terminating link.** Each branch is its own chain, so each one needs to end in a terminating link. - **Sending subscriptions through `httpLink`, `httpBatchLink` or `httpBatchStreamLink`.** They throw on subscriptions. Route them to `httpSubscriptionLink` or `wsLink` with a `splitLink`, as shown in [The terminating link](#the-terminating-link). - **Returning an async generator from a query through `httpLink` or `httpBatchLink`.** The server responds with `Cannot use stream-like response in non-streaming request - use httpBatchStreamLink`. - **Reading `op` in a batch link's `headers` callback.** `httpBatchLink` and `httpBatchStreamLink` call `headers({ opList })` once per batch, with all its operations. Only `httpLink` gets a single `{ op }`. - **Unbounded batches.** `maxURLLength` and `maxItems` default to `Infinity`. If long URLs hit limits in your server or CDN, set `maxURLLength`. If the server sets `maxBatchSize`, set `maxItems` to the same or a lower value, or larger batches are rejected with `400 Bad Request`. See [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md#setting-a-maximum-url-length). - **Forgetting the transformer on one link.** If your server uses a [data transformer](https://trpc.io/docs/server/data-transformers.md), every terminating link needs the same `transformer`, in every `splitLink` branch. --- Source: https://trpc.io/docs/client/links/httpLink # HTTP Link > A terminating link that sends each tRPC call as its own HTTP request `httpLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that sends a tRPC operation to a tRPC procedure over HTTP. `httpLink` supports both POST and GET requests. ## Usage You can import and add the `httpLink` to the `links` array as such: ```ts title="client/index.ts" import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpLink({ url: 'http://localhost:3000', // transformer, }), ], }); ``` ## `httpLink` Options The `httpLink` function takes an options object that has the `HTTPLinkOptions` shape. ```ts export interface HTTPLinkOptions { url: string | URL; /** * Add ponyfill for fetch */ fetch?: typeof fetch; /** * Data transformer * @see https://trpc.io/docs/server/data-transformers **/ transformer?: DataTransformerOptions; /** * Headers to be set on outgoing requests or a callback that of said headers * @see https://trpc.io/docs/client/headers */ headers?: | HTTPHeaders | ((opts: { op: Operation }) => HTTPHeaders | Promise); /** * Send all requests as POSTS requests regardless of the procedure type * The server must separately allow overriding the method. See: * @see https://trpc.io/docs/rpc */ methodOverride?: 'POST'; /** * The character between a procedure path's segments in URLs. Must match * the server's `pathSeparator`. * @default '.' * @see https://trpc.io/docs/rpc#path-separator */ pathSeparator?: '.' | '_' | '~' | '-'; } ``` ## Reference You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/httpLink.ts) --- Source: https://trpc.io/docs/client/links/httpBatchLink # HTTP Batch Link > A terminating link that batches concurrent tRPC calls into a single HTTP request `httpBatchLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that batches an array of individual tRPC operations into a single HTTP request. A batch can include calls to different procedures (queries and mutations are batched separately). ## Usage You can import and add the `httpBatchLink` to the `links` array as such: ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000', // transformer, }), ], }); ``` After that, calls made in the same event loop tick are batched together, so you don't need `Promise.all`, though it's a common way to do it. The code below will produce exactly **one** HTTP request, and the server will call `createContext` **once** for it: ```ts const somePosts = await Promise.all([ trpc.post.byId.query(1), trpc.post.byId.query(2), trpc.post.byId.query(3), ]); ``` Each procedure still runs its own resolver, so whether this makes one database query depends on your data layer. Prisma [batches `findUnique()` calls made in the same tick](https://www.prisma.io/docs/orm/prisma-client/queries/query-optimization-performance#solving-the-n1-problem) into one query, and a [DataLoader](https://github.com/graphql/dataloader) can do the same for other queries. Otherwise, each resolver makes its own query. ## `httpBatchLink` Options {#options} The `httpBatchLink` function takes an options object that has the `HTTPBatchLinkOptions` shape. ```ts export interface HTTPBatchLinkOptions extends HTTPLinkOptions { /** * Maximum length of HTTP URL allowed before operations are split into multiple requests * @default Infinity */ maxURLLength?: number; /** * Maximum number of operations allowed in a single batch request * @default Infinity */ maxItems?: number; } export interface HTTPLinkOptions { url: string | URL; /** * Add ponyfill for fetch */ fetch?: typeof fetch; /** * Data transformer * @see https://trpc.io/docs/server/data-transformers **/ transformer?: DataTransformerOptions; /** * Headers to be set on outgoing requests or a callback that of said headers * @see https://trpc.io/docs/client/headers */ headers?: | HTTPHeaders | ((opts: { opList: NonEmptyArray }) => HTTPHeaders | Promise); /** * Send all requests as POST requests regardless of the procedure type * The server must separately allow overriding the method. See: * @see https://trpc.io/docs/rpc */ methodOverride?: 'POST'; /** * The character between a procedure path's segments in URLs. Must match * the server's `pathSeparator`. * @default '.' * @see https://trpc.io/docs/rpc#path-separator */ pathSeparator?: '.' | '_' | '~' | '-'; } ``` ## Setting a maximum URL length When sending batch requests, sometimes the URL can become too large causing HTTP errors like [`413 Payload Too Large`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413), [`414 URI Too Long`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/414), and [`404 Not Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404). The `maxURLLength` option will limit the number of requests that can be sent together in a batch. ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000', maxURLLength: 2083, // a suitable size // alternatively, you can make all RPC-calls to be called with POST (also requires `allowMethodOverride: true` on the server) // methodOverride: 'POST', }), ], }); ``` ## Limiting batch size ### 1. Set a maximum batch size on your server: `maxBatchSize` limits how many operations may be sent in a single batch request. Requests exceeding this limit will be rejected with a `400 Bad Request` error. This can be passed to any tRPC adapter. ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './router'; createHTTPServer({ router: appRouter, maxBatchSize: 10, }); ``` or for example if using Next.js: ```ts title="pages/api/trpc/[trpc].ts" import { createNextApiHandler } from '@trpc/server/adapters/next'; import { appRouter } from '../../../router'; export default createNextApiHandler({ router: appRouter, maxBatchSize: 10, }); ``` ### 2. Set a matching limit on the client: Use the `maxItems` option on your batch link to ensure the client doesn't exceed the server's limit. This splits large batches into multiple HTTP requests automatically ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from '../server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000', // πŸ‘‡ should be the same or lower than the server's maxBatchSize maxItems: 10, }), ], }); ``` ## Disabling request batching ### 1. Disable `batching` on your server: ```ts title="server.ts" import { createHTTPServer } from '@trpc/server/adapters/standalone'; import { appRouter } from './router'; createHTTPServer({ router: appRouter, // πŸ‘‡ disable batching allowBatching: false, }); ``` or, if you're using Next.js: ```ts title="pages/api/trpc/[trpc].ts" import { createNextApiHandler } from '@trpc/server/adapters/next'; import { appRouter } from '../../../router'; export default createNextApiHandler({ router: appRouter, // πŸ‘‡ disable batching allowBatching: false, }); ``` ### 2. Replace `httpBatchLink` with [`httpLink`](https://trpc.io/docs/client/links/httpLink.md) in your tRPC Client ```ts title="client/index.ts" import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpLink({ url: 'http://localhost:3000', }), ], }); ``` With Next.js, it's the same: swap the link in the `createTRPCClient` you pass to `TRPCProvider`. --- Source: https://trpc.io/docs/client/links/httpBatchStreamLink # HTTP Batch Stream Link > A terminating link that batches tRPC calls and streams each response as soon as it is ready `httpBatchStreamLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that batches an array of individual tRPC operations into a single HTTP request (equivalent to [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md)), but doesn't wait for all the responses of the batch to be ready and streams the responses as soon as any data is available. ## Options Options are identical to [`httpBatchLink options`](https://trpc.io/docs/client/links/httpBatchLink.md#options), with the following addition: | Option | Type | Default | Description | | -------------- | ----------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `streamHeader` | `'trpc-accept'` \| `'accept'` | `'trpc-accept'` | Which header to use to signal the server that the client wants a streaming response. `'accept'` uses the standard `Accept` header instead of the custom `trpc-accept` header, which can avoid CORS preflight for cross-origin streaming queries since `Accept` is a CORS-safelisted header. | ## Usage > All usage and options are identical to [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md). > [!NOTE] > If you require the ability to change/set response headers (which includes cookies) from within your procedures, make sure to use `httpBatchLink` instead! This is due to the fact that `httpBatchStreamLink` does not support setting headers once the stream has begun. [Read more](https://trpc.io/docs/client/links/httpBatchLink.md). You can import and add the `httpBatchStreamLink` to the `links` array as such: ```ts title="client/index.ts" import { createTRPCClient, httpBatchStreamLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchStreamLink({ url: 'http://localhost:3000', }), ], }); ``` After that, calls made in the same event loop tick are batched together, so you don't need `Promise.all`, though it's a common way to do it. The code below will produce exactly **one** HTTP request, and the server will call `createContext` **once** for it: ```ts const somePosts = await Promise.all([ trpc.post.byId.query(1), trpc.post.byId.query(2), trpc.post.byId.query(3), ]); ``` Each procedure still runs its own resolver, so whether this makes one database query depends on your data layer. Prisma [batches `findUnique()` calls made in the same tick](https://www.prisma.io/docs/orm/prisma-client/queries/query-optimization-performance#solving-the-n1-problem) into one query, and a [DataLoader](https://github.com/graphql/dataloader) can do the same for other queries. Otherwise, each resolver makes its own query. ## Streaming mode When batching requests together, the behavior of a regular `httpBatchLink` is to wait for all requests to finish before sending the response. If you want to send responses as soon as they are ready, you can use `httpBatchStreamLink` instead. This is useful for long-running requests. ```ts title="client/index.ts" import { createTRPCClient, httpBatchStreamLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchStreamLink({ url: 'http://localhost:3000', }), ], }); ``` Compared to a regular `httpBatchLink`, a `httpBatchStreamLink` will: - Cause the requests to be sent with a `trpc-accept: application/jsonl` header (or `Accept: application/jsonl` when using `streamHeader: 'accept'`) - Cause the response to be sent with `transfer-encoding: chunked` and `content-type: application/json` by default. You can set the streamed response `content-type` to `application/jsonl`, `application/x-ndjson`, or another value on the server via `initTRPC.create({ jsonl: { contentType: ... } })`. - Remove the `data` key from the argument object passed to `responseMeta` (because with a streamed response, the headers are sent before the data is available) ## Async generators and deferred promises {#generators} You can try this out on the homepage of tRPC.io: [https://trpc.io/?try=minimal#try-it-out](https://trpc.io/?try=minimal#try-it-out) ```ts import { createTRPCClient, httpBatchStreamLink } from '@trpc/client'; import type { AppRouter } from './server'; const trpc = createTRPCClient({ links: [ httpBatchStreamLink({ url: 'http://localhost:3000', }), ], }); const iterable = await trpc.examples.iterable.query(); // const iterable: AsyncIterable for await (const value of iterable) { console.log('Iterable:', value); // const value: number } ``` ## Compatibility (client-side) ### Browsers Browser support should be identical to [`fetch`](https://caniuse.com/fetch) support. ### Node.js / Deno For runtimes other than the browser ones, the `fetch` implementation should support streaming, meaning that the response obtained by `await fetch(...)` should have a `body` property of type `ReadableStream | NodeJS.ReadableStream`, meaning that: - either `response.body.getReader` is a function that returns a `ReadableStreamDefaultReader` object - or `response.body` is a `Uint8Array` `Buffer` This includes support for `undici`, `node-fetch`, native Node.js fetch implementation, and WebAPI fetch implementation (browsers). ### React Native Receiving the stream relies on the `TextDecoder` and `TextDecoderStream` APIs, which are not available in React Native. It's important to note that if your `TextDecoderStream` polyfill does not automatically polyfill `ReadableStream` and `WritableStream` those will also need to be polyfilled. If you still want to enable streaming, you need to polyfill those. You will also need to override the default fetch in the `httpBatchStreamLink` configuration options with one that can stream. In the below example we will be using [`react-native-fetch-api`](https://github.com/react-native-community/fetch), which streams text when you pass its `reactNative` option. On Expo, you can pass `fetch` from [`expo/fetch`](https://docs.expo.dev/versions/latest/sdk/expo/) instead, which streams without extra options. ```ts import { httpBatchStreamLink } from '@trpc/client'; import { fetch } from 'react-native-fetch-api'; httpBatchStreamLink({ fetch: (url, opts) => fetch(url, { ...opts, reactNative: { textStreaming: true }, }), url: 'http://localhost:3000', }); ``` ## Compatibility (server-side) > [!WARNING] AWS Lambda > `httpBatchStreamLink` only supported on AWS Lambda when your [infrastructure is set up](https://trpc.io/docs/server/adapters/aws-lambda.md#aws-lambda-response-streaming-adapter) for streaming responses. If not this Link will simply behave like a regular `httpBatchLink`. > [!WARNING] Cloudflare Workers > You need to enable the `ReadableStream` API through a feature flag: [`streams_enable_constructors`](https://developers.cloudflare.com/workers/platform/compatibility-dates#streams-constructors). ## Reference You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/httpBatchStreamLink.ts) ## Configure JSONL streaming options When setting up your root config, you can pass in a `jsonl` option to configure ping behavior and the response `content-type` for streamed batch responses. ```ts import { initTRPC } from '@trpc/server'; const t = initTRPC.create({ jsonl: { pingMs: 1000, contentType: 'application/jsonl', }, }); ``` The default `contentType` remains `application/json` for backwards compatibility. Use `application/jsonl` if you want the response header to match the `trpc-accept` / `Accept` header sent by `httpBatchStreamLink`, or choose another value that works better with your tooling. --- Source: https://trpc.io/docs/client/links/httpSubscriptionLink # HTTP Subscription Link > A terminating link for subscriptions over Server-sent Events `httpSubscriptionLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that uses [Server-sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (SSE) for subscriptions. SSE is a good option for real-time as it's a bit easier than setting up a WebSockets-server. ## Setup {#setup} > [!NOTE] Info > If your client's environment doesn't support EventSource, you need an [EventSource polyfill](https://www.npmjs.com/package/event-source-polyfill). For React Native specific instructions please defer to the [compatibility section](#compatibility-react-native). To use `httpSubscriptionLink`, you need to use a [splitLink](https://trpc.io/docs/client/links/splitLink.md) to make it explicit that we want to use SSE for subscriptions. ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink, httpSubscriptionLink, loggerLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; const trpcClient = createTRPCClient({ /** * @see https://trpc.io/docs/v11/client/links */ links: [ // adds pretty logs to your console in development and logs errors in production loggerLink(), splitLink({ // uses the httpSubscriptionLink for subscriptions condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: `/api/trpc`, }), false: httpBatchLink({ url: `/api/trpc`, }), }), ], }); ``` > [!TIP] > The document here outlines the specific details of using `httpSubscriptionLink`. For general usage of subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions.md). ## Headers and authorization / authentication ### Web apps #### Same domain If you're doing a web application, cookies are sent as part of the request as long as your client is on the same domain as the server. #### Cross-domain If the client and server are not on the same domain, you can use `withCredentials: true` ([read more on MDN here](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/withCredentials)). **Example:** ```tsx // [...] httpSubscriptionLink({ url: 'https://example.com/api/trpc', eventSourceOptions() { return { withCredentials: true, // <--- }; }, }); ``` ### Custom headers through ponyfill **Recommended for non-web environments** You can ponyfill `EventSource` and use the `eventSourceOptions` -callback to populate headers. ```tsx import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink, } from '@trpc/client'; import { EventSourcePolyfill } from 'event-source-polyfill'; import type { AppRouter } from './server'; // Initialize the tRPC client const trpc = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: 'http://localhost:3000', // ponyfill EventSource EventSource: EventSourcePolyfill, // options to pass to the EventSourcePolyfill constructor eventSourceOptions: async ({ op }) => { // ^ Includes the operation that's being executed // you can use this to generate a signature for the operation const signature = await getSignature(op); return { headers: { authorization: 'Bearer supersecret', 'x-signature': signature, }, }; }, }), false: httpBatchLink({ url: 'http://localhost:3000', }), }), ], }); ``` ### Updating configuration on an active connection {#updatingConfig} `httpSubscriptionLink` leverages SSE through `EventSource`, ensuring that connections encountering errors like network failures or bad response codes are automatically retried. However, `EventSource` does not allow re-execution of the `eventSourceOptions()` or `url()` options to update its configuration, which is particularly important in scenarios where authentication has expired since the last connection. To address this limitation, you can use a [`retryLink`](https://trpc.io/docs/client/links/retryLink.md) in conjunction with `httpSubscriptionLink`. This approach ensures that the connection is re-established with the latest configuration, including any updated authentication details. > [!WARNING] Caution > Please note that restarting the connection will result in the `EventSource` being recreated from scratch, which means any previously tracked events will be lost. ```tsx import { createTRPCClient, httpBatchLink, httpSubscriptionLink, retryLink, splitLink, } from '@trpc/client'; import { EventSourcePolyfill, EventSourcePolyfillInit, } from 'event-source-polyfill'; import type { AppRouter } from './server'; // Initialize the tRPC client const trpc = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'subscription', false: httpBatchLink({ url: 'http://localhost:3000', }), true: [ retryLink({ retry: (opts) => { opts.op.type; const code = opts.error.data?.code; if (!code) { // This shouldn't happen as our httpSubscriptionLink will automatically retry within when there's a non-parsable response console.error('No error code found, retrying', opts); return true; } if (code === 'UNAUTHORIZED' || code === 'FORBIDDEN') { console.log('Retrying due to 401/403 error'); return true; } return false; }, }), httpSubscriptionLink({ url: async () => { // calculate the latest URL if needed... return getAuthenticatedUri(); }, // ponyfill EventSource EventSource: EventSourcePolyfill, eventSourceOptions: async () => { // ...or maybe renew an access token const token = await auth.getOrRenewToken(); return { headers: { authorization: `Bearer ${token}`, }, }; }, }), ], }), ], }); ``` ### Connection params {#connectionParams} In order to authenticate with `EventSource`, you can define `connectionParams` in `httpSubscriptionLink`. This will be sent as part of the URL, which is why other methods are preferred. ```ts title="server/context.ts" import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone'; export const createContext = async (opts: CreateHTTPContextOptions) => { const token = opts.info.connectionParams?.token; // const token: string | undefined // [... authenticate] return {}; }; export type Context = Awaited>; ``` ```ts title="client/trpc.ts" import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; // Initialize the tRPC client const trpc = createTRPCClient({ links: [ splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url: 'http://localhost:3000', connectionParams: async () => { // Will be serialized as part of the URL return { token: 'supersecret', }; }, }), false: httpBatchLink({ url: 'http://localhost:3000', }), }), ], }); ``` ## Timeout Configuration {#timeout} The `httpSubscriptionLink` supports configuring a timeout for inactivity through the `reconnectAfterInactivityMs` option. If no messages (including ping messages) are received within the specified timeout period, the connection will be marked as "connecting" and automatically attempt to reconnect. The timeout configuration is set on the server side when initializing tRPC: ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; export const t = initTRPC.create({ sse: { client: { reconnectAfterInactivityMs: 3_000, }, }, }); ``` ## Server Ping Configuration {#server-ping} The server can be configured to send periodic ping messages to keep the connection alive and prevent timeout disconnections. This is particularly useful when combined with the `reconnectAfterInactivityMs`-option. ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; export const t = initTRPC.create({ sse: { // Maximum duration of a single SSE connection in milliseconds // maxDurationMs: 60_000, ping: { // Enable periodic ping messages to keep connection alive enabled: true, // Send ping message every 2s intervalMs: 2_000, }, // client: { // reconnectAfterInactivityMs: 3_000 // } }, }); ``` ## Compatibility (React Native) {#compatibility-react-native} The `httpSubscriptionLink` makes use of the `EventSource` API, Streams API, and `AsyncIterator`s, these are not natively supported by React Native and will have to be ponyfilled. To ponyfill `EventSource` we recommend to use a polyfill that utilizes the networking library exposed by React Native, over using a polyfill that uses the `XMLHttpRequest` API. Libraries that polyfill `EventSource` using `XMLHttpRequest` fail to reconnect after the app has been in the background. Consider using the [rn-eventsource-reborn](https://www.npmjs.com/package/rn-eventsource-reborn) package. The Streams API can be ponyfilled using the [web-streams-polyfill](https://www.npmjs.com/package/web-streams-polyfill) package. `AsyncIterator`s can be polyfilled using the [@azure/core-asynciterator-polyfill](https://www.npmjs.com/package/@azure/core-asynciterator-polyfill) package. ### Installation Install the required polyfills: ```package-install rn-eventsource-reborn web-streams-polyfill @azure/core-asynciterator-polyfill ``` Add the polyfills to your project before the link is used (e.g. where you add your TRPCReact.Provider): ```ts title="utils/api.tsx" import '@azure/core-asynciterator-polyfill'; import { RNEventSource } from 'rn-eventsource-reborn'; import { ReadableStream, TransformStream } from 'web-streams-polyfill'; globalThis.ReadableStream = globalThis.ReadableStream || ReadableStream; globalThis.TransformStream = globalThis.TransformStream || TransformStream; ``` Once the ponyfills are added, you can continue setting up the `httpSubscriptionLink` as described in the [setup](#setup) section. ## `httpSubscriptionLink` Options ```ts type HTTPSubscriptionLinkOptions< TRoot extends AnyClientTypes, TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource, > = { /** * The URL to connect to (can be a function that returns a URL) */ url: string | (() => string | Promise); /** * Connection params that are available in `createContext()` * Serialized as part of the URL under the `connectionParams` query parameter */ connectionParams?: | Record | null | (() => | Record | null | Promise | null>); /** * Data transformer * @see https://trpc.io/docs/v11/data-transformers */ transformer?: DataTransformerOptions; /** * EventSource ponyfill */ EventSource?: TEventSource; /** * EventSource options or a callback that returns them */ eventSourceOptions?: | EventSourceLike.InitDictOf | ((opts: { op: Operation; }) => | EventSourceLike.InitDictOf | Promise>); }; ``` ## SSE Options on the server ```ts export interface SSEStreamProducerOptions { ping?: { /** * Enable ping comments sent from the server * @default false */ enabled: boolean; /** * Interval in milliseconds * @default 1000 */ intervalMs?: number; }; /** * Maximum duration in milliseconds for the request before ending the stream * @default undefined */ maxDurationMs?: number; /** * End the request immediately after data is sent * Only useful for serverless runtimes that do not support streaming responses * @default false */ emitAndEndImmediately?: boolean; /** * Client-specific options - these will be sent to the client as part of the first message * @default {} */ client?: { /** * Timeout and reconnect after inactivity in milliseconds * @default undefined */ reconnectAfterInactivityMs?: number; }; } ``` --- Source: https://trpc.io/docs/client/links/localLink # Local Link > A link for direct procedure calls without HTTP overhead `localLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that allows you to make tRPC procedure calls directly in your application without going through HTTP. > [!NOTE] Info > `localLink` used to be called `unstable_localLink`. The old name still works, but it's deprecated and will be removed in a future major release. ## Usage ```tsx import { createTRPCClient, localLink } from '@trpc/client'; import type { AppRouter } from './server'; import { appRouter } from './server'; const client = createTRPCClient({ links: [ localLink({ router: appRouter, createContext: async () => { // Create your context here return {}; }, onError: (opts) => { // Log errors here, similarly to how you would in an API route console.error('Error:', opts.error); }, }), ], }); ``` ## Features - Direct procedure calls without HTTP overhead - Full support for queries, mutations, and subscriptions - Automatic error handling and transformation - Support for abort signals - Type-safe context creation ## Options The `localLink` accepts the following options: ```ts type LocalLinkOptions = { router: TRouter; createContext: (opts: { info: { signal: AbortSignal }; }) => Promise>; onError?: (opts: ErrorHandlerOptions>) => void; } & TransformerOptions>; ``` ### router The tRPC router instance to use for procedure calls. ### createContext A function that creates the context for each procedure call. This is called for each request and should return a promise that resolves to the context object. It receives `info.signal`, which aborts when the call is cancelled, for example when you pass `signal` to `.query()` or unsubscribe. Pass it on to slow work like database or `fetch()` calls. The same signal reaches your procedures as `opts.signal`. If the call is cancelled before or while the context is created, the procedure doesn't run. ```ts import { localLink } from '@trpc/client'; localLink({ router: appRouter, createContext: async (opts) => { const session = await getSession({ signal: opts.info.signal }); return { session }; }, }); ``` ### onError An optional error handler that is called when an error occurs during a procedure call. It receives the error, operation type, path, input, and context. ### transformer Optional input/output transformers for serialization/deserialization of data. ## Notes - It's recommended to use this link in scenarios where you need direct procedure calls without HTTP - For most client-side applications, you should use the `httpLink` or other HTTP-based links instead - The link supports all tRPC features including queries, mutations, and subscriptions - Error handling and transformation are handled automatically, just like with HTTP-based links --- Source: https://trpc.io/docs/client/links/wsLink # WebSocket Link > A terminating link that sends tRPC operations over a WebSocket `wsLink` is a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) that's used when using tRPC's WebSockets Client and Subscriptions, which you can learn more about [here](https://trpc.io/docs/server/subscriptions.md). ## Usage To use `wsLink`, you need to pass it a `TRPCWebSocketClient`, which you can create with `createWSClient`: ```ts title="client/index.ts" import { createTRPCClient, createWSClient, wsLink } from '@trpc/client'; import type { AppRouter } from './server'; const wsClient = createWSClient({ url: 'ws://localhost:3000', }); const trpcClient = createTRPCClient({ links: [wsLink({ client: wsClient })], }); ``` ## Authentication / Connection params [See more here](https://trpc.io/docs/server/websockets.md#connection-params) ## `wsLink` / `createWSClient` Options The `wsLink` function requires a `TRPCWebSocketClient` to be passed, which can be configured with the fields defined in `WebSocketClientOptions`: ```ts export interface WebSocketLinkOptions { client: TRPCWebSocketClient; /** * Data transformer * @see https://trpc.io/docs/v11/data-transformers **/ transformer?: DataTransformerOptions; } declare function createWSClient(opts: WebSocketClientOptions): TRPCWebSocketClient; export interface WebSocketClientOptions { /** * The URL to connect to (can be a function that returns a URL) */ url: string | (() => MaybePromise); /** * Connection params that are available in `createContext()` * These are sent as the first message */ connectionParams?: Record | null | (() => MaybePromise | null>); /** * Ponyfill which WebSocket implementation to use */ WebSocket?: typeof WebSocket; /** * The number of milliseconds before a reconnect is attempted. * @default {@link exponentialBackoff} */ retryDelayMs?: typeof exponentialBackoff; /** * Triggered when a WebSocket connection is established */ onOpen?: () => void; /** * Triggered when a WebSocket connection encounters an error */ onError?: (evt?: Event) => void; /** * Triggered when a WebSocket connection is closed */ onClose?: (cause?: { code?: number }) => void; /** * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests) */ lazy?: { /** * Enable lazy mode * @default false */ enabled: boolean; /** * Close the WebSocket after this many milliseconds * @default 0 */ closeMs: number; }; /** * Send ping messages to the server and kill the connection if no pong message is returned */ keepAlive?: { /** * @default false */ enabled: boolean; /** * Send a ping message every this many milliseconds * @default 5_000 */ intervalMs?: number; /** * Close the WebSocket after this many milliseconds if the server does not respond * @default 1_000 */ pongTimeoutMs?: number; }; /** * Custom encoder for wire encoding (e.g. custom binary formats) * @default jsonEncoder */ experimental_encoder?: Encoder; } ``` ## Reference You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/wsLink) --- Source: https://trpc.io/docs/client/links/splitLink # Split Link > A link that routes each operation down one of two link chains based on a condition `splitLink` is a link that allows you to branch your link chain's execution depending on a given condition. Both the `true` and `false` branches are required. You can provide just one link, or multiple links per branch via an array. It's important to note that when you provide links for `splitLink` to execute, `splitLink` will create an entirely new link chain based on the links you passed. Therefore, you need to use a [**terminating link**](https://trpc.io/docs/client/links.md#the-terminating-link) if you only provide one link or add the terminating link at the end of the array if you provide multiple links to be executed on a branch. Here's a visual representation of how `splitLink` works:
## Usage Example ### Disable batching for certain requests Let's say you're using `httpBatchLink` as the terminating link in your tRPC client config. This means request batching is enabled in every request. However, if you need to disable batching only for certain requests, you would need to change the terminating link in your tRPC client config dynamically between `httpLink` and `httpBatchLink`. This is a perfect opportunity for `splitLink` to be used: #### 1. Configure client / `utils/trpc.ts` ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink, httpLink, splitLink, } from '@trpc/client'; import type { AppRouter } from './server'; const url = `http://localhost:3000`; const client = createTRPCClient({ links: [ splitLink({ condition(op) { // check for context property `skipBatch` return Boolean(op.context.skipBatch); }, // when condition is true, use normal request true: httpLink({ url, }), // when condition is false, use batching false: httpBatchLink({ url, }), }), ], }); ``` #### 2. Perform request without batching ```ts title="client.ts" const postResult = proxy.posts.query(undefined, { context: { skipBatch: true, }, }); ``` or: ```tsx title="MyComponent.tsx" import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './trpc'; export function MyComponent() { const trpc = useTRPC(); const postsQuery = useQuery( trpc.posts.queryOptions(undefined, { trpc: { context: { skipBatch: true, }, }, }), ); return (
{JSON.stringify(postsQuery.data ?? null, null, 4)}
) } ``` ## `splitLink` Options The `splitLink` function takes an options object that has three fields: `condition`, `true`, and `false`. ```ts declare function splitLink(opts: { condition: (op: Operation) => boolean; /** * The link to execute next if the test function returns `true`. */ true: TRPCLink | TRPCLink[]; /** * The link to execute next if the test function returns `false`. */ false: TRPCLink | TRPCLink[]; }): TRPCLink; ``` ## Reference You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/splitLink.ts) --- Source: https://trpc.io/docs/client/links/loggerLink # Logger Link > A link that logs tRPC operations and their results `loggerLink` is a link that lets you implement a logger for your tRPC client. It allows you to see more clearly what operations are queries, mutations, or subscriptions, their requests, and responses. The link, by default, prints a prettified log to the browser's console. However, you can customize the logging behavior and the way it prints to the console with your own implementations. ## Usage You can import and add the `loggerLink` to the `links` array as such: ```ts title="client/index.ts" import { createTRPCClient, httpBatchLink, loggerLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ /** * The function passed to enabled is an example in case you want to the link to * log to your console in development and only log errors in production */ loggerLink({ enabled: (opts) => (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') || (opts.direction === 'down' && opts.result instanceof Error), }), httpBatchLink({ url: 'http://localhost:3000', }), ], }); ``` ## `loggerLink` Options The `loggerLink` function takes an options object that has the `LoggerLinkOptions` shape: ```ts type LoggerLinkOptions = { logger?: LogFn; /** * It is a function that returns a condition that determines whether to enable the logger. * It is true by default. */ enabled?: EnabledFn; /** * Used in the built-in defaultLogger */ console?: ConsoleEsque; /** * Color mode used in the default logger. * @default typeof window === 'undefined' ? 'ansi' : 'css' */ colorMode?: 'ansi' | 'css' | 'none'; /** * Include context in the log - defaults to false unless colorMode is 'css' */ withContext?: boolean; }; ``` ## Reference You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/loggerLink.ts) --- Source: https://trpc.io/docs/client/links/retryLink # Retry Link > A link that retries failed operations `retryLink` is a link that allows you to retry failed operations in your tRPC client. It provides a customizable way to handle transient errors, such as network failures or server errors, by automatically retrying the failed requests based on specified conditions. > [!TIP] > If you use `@trpc/react-query` you will generally **not** need this link as it's built into the `useQuery()` and the `useMutation()` hooks from `@tanstack/react-query`. ## Usage You can import and add the `retryLink` to the `links` array when creating your tRPC client. This link can be placed before or after other links in your setup, depending on your requirements. ```ts import { createTRPCClient, httpBatchLink, retryLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ retryLink({ retry(opts) { if ( opts.error.data && opts.error.data.code !== 'INTERNAL_SERVER_ERROR' ) { // Don't retry on non-500s return false; } if (opts.op.type !== 'query') { // Only retry queries return false; } // Retry up to 3 times return opts.attempts <= 3; }, // Double every attempt, with max of 30 seconds (starting at 1 second) retryDelayMs: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), }), httpBatchLink({ url: 'http://localhost:3000', }), ], }); ``` In the example above, we add the `retryLink` before the `httpBatchLink`. The `retry` function is required and defines when to retry. In this example, it will: - Retry the request if the error is a `TRPCClientError` with a status code of 500 or if we couldn't get a valid tRPC error. - Retry the request up to 3 times. ## Options ```ts interface RetryLinkOptions { /** * The retry function */ retry: (opts: RetryFnOptions) => boolean; /** * The delay between retries in ms (defaults to 0) */ retryDelayMs?: (attempt: number) => number; } interface RetryFnOptions { /** * The operation that failed */ op: Operation; /** * The error that occurred */ error: TRPCClientError; /** * The number of attempts that have been made (including the first call) */ attempts: number; } ``` ## Handling tracked() events When using `retryLink` with subscriptions that use [`tracked()`](https://trpc.io/docs/server/subscriptions.md#tracked), the link will automatically include the last known event ID when retrying. This ensures that when a subscription reconnects, it can resume from where it left off without missing any events. For example, if you're using Server-sent Events (SSE) with `httpSubscriptionLink`, the `retryLink` will automatically handle reconnecting with the last event ID when errors like `401 Unauthorized` occur. --- Source: https://trpc.io/docs/client/headers # Headers > The headers option may be used with any of our HTTP links: [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md), [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md), [`httpLink`](https://trpc.io/docs/client/links/httpLink.md), or [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md). `headers` can be both an object or a function. If it's a function it will get called dynamically for every HTTP request. ```ts title="utils/trpc.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; let token: string; export function setToken(newToken: string) { /** * You can also save the token to cookies, and initialize from * cookies above. */ token = newToken; } export const trpc = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000', /** * Headers will be called on each request. */ headers() { return { Authorization: token, }; }, }), ], }); ``` ## Example with auth login ```ts title="auth.ts" const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' }); setToken(result.accessToken); ``` The `token` can be whatever you want it to be. It's entirely up to you whether that's just a client-side variable that you update the value of on success or whether you store the token and pull it from local storage. --- Source: https://trpc.io/docs/client/cors # Send cookies cross-origin > If your API resides on a different origin than your front-end and you wish to send cookies to it, you will need to enable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) on your server and send cookies with your requests by providing the option `{credentials: "include"}` to fetch. The arguments provided to the fetch function used by tRPC can be modified as follows. ```ts title="app.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'YOUR_SERVER_URL', fetch(url, options) { return fetch(url, { ...options, credentials: 'include', }); }, }), ], }); ``` > [!NOTE] Info > You also need to enable CORS on your server by modifying your [adapter](https://trpc.io/docs/server/adapters.md), or the HTTP server which fronts your API. The best way to do this varies adapter-by-adapter and based on your hosting infrastructure, and individual adapters generally document this process where applicable. --- Source: https://trpc.io/docs/client/vanilla # tRPC Client > # tRPC Client The "Vanilla" tRPC client can be used to call your API procedures as if they are local functions, enabling a seamless development experience. ```ts import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [httpBatchLink({ url: 'http://localhost:3000' })], }); const bilbo = await client.getUser.query('id_bilbo'); // => { id: 'id_bilbo', name: 'Bilbo' }; ``` ### When to use the Vanilla Client? You are likely to use this client in two scenarios: - With a frontend framework for which we don't have an official integration - With a separate backend service written in TypeScript. ### When **NOT** to use the Vanilla Client? - While you _can_ use the client to call procedures from a React component, you should usually use our [TanStack React Query Integration](https://trpc.io/docs/client/tanstack-react-query/setup.md). It offers many additional features such as the ability to manage loading and error state, caching, and invalidation. - We recommend you do not use this client when calling procedures of the same API instance, this is because the invocation has to pass through the network layer. For complete recommendations on invoking a procedure in the current API, you can [read more here](https://trpc.io/docs/server/server-side-calls.md). --- Source: https://trpc.io/docs/client/vanilla/setup # Set up a tRPC Client > ### 1. Install the tRPC Client library Use your preferred package manager to install the `@trpc/client` library, and also install `@trpc/server` which contains some required types. ```package-install @trpc/server @trpc/client ``` ### 2. Import your App Router Import your `AppRouter` type into the client application. This type holds the shape of your entire API. ```ts title="utils/trpc.ts" import type { AppRouter } from '../server/router'; ``` > [!TIP] > By using `import type` you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, [see the Typescript docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export). ### 3. Initialize the tRPC client Create a tRPC client with the `createTRPCClient` method, and add a `links` array with a [terminating link](https://trpc.io/docs/client/links.md#the-terminating-link) pointing at your API. To learn more about tRPC links, [click here](https://trpc.io/docs/client/links.md). ```ts title="client.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000/trpc', // You can pass any HTTP headers you wish here async headers() { return { authorization: getAuthCookie(), }; }, }), ], }); ``` ### 4. Use the tRPC Client Under the hood this creates a typed [JavaScript Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) which allows you to interact with your tRPC API in a fully type-safe way: ```ts title="client.ts" const bilbo = await client.getUser.query('id_bilbo'); // => { id: 'id_bilbo', name: 'Bilbo' }; const frodo = await client.createUser.mutate({ name: 'Frodo' }); // => { id: 'id_frodo', name: 'Frodo' }; ``` ### 5. Use subscriptions Given a [subscription procedure](https://trpc.io/docs/server/subscriptions.md) and a link that supports subscriptions, such as [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md) or [`wsLink`](https://trpc.io/docs/client/links/wsLink.md), `.subscribe()` starts the subscription. Either pass callbacks, or leave them out and iterate the result with `for await`: ```ts title="client.ts" // with callbacks const sub = client.onUserAdd.subscribe(undefined, { onData(user) { console.log(user); }, }); // stop listening sub.unsubscribe(); // or with `for await`, without callbacks const ac = new AbortController(); const users = client.onUserAdd.subscribe(undefined, { signal: ac.signal }); for await (const user of users) { // const user: { // name: string; // } console.log(user); } // `ac.abort()` stops it from outside the loop ``` When you iterate a subscription: - A subscription is either iterated or uses callbacks. Iterating one that was started with callbacks throws, and is a type error. - Without callbacks, `.subscribe()` returns an async iterator with no `unsubscribe()`, like Node's `events.on()`. Stop it from inside the loop with `break` or `return`, or from outside by aborting the `signal` you passed. - Data is queued from when `.subscribe()` is called until the loop reads it. The queue has no size limit. A subscription can be iterated once: a second `for await` over it throws. To consume it twice, call `.subscribe()` twice. - A subscription you never loop over or abort keeps running, so pass a `signal`. - If you called `unsubscribe()` on a subscription started without callbacks, pass a `signal` and `abort()` it instead. - Leaving the loop with `break`, `return` or a thrown error unsubscribes and drops the queued data. - Aborting the `signal` unsubscribes, and the loop yields the data already queued before it ends. - An error from the subscription is thrown from the loop as a `TRPCClientError`, after the data received before it. You're all set! ## Common mistakes - **Leaving out the `AppRouter` type parameter.** `createTRPCClient({ links })` without `` compiles, but none of your procedures are typed. If the `AppRouter` import doesn't resolve (often a monorepo path or `tsconfig` issue), fix the import rather than reaching for `createTRPCClient`. - **Importing the router value instead of its type.** `import { appRouter } from '../server/router'` pulls your server code into the client bundle. Export `type AppRouter = typeof appRouter` from the server and import it with `import type`. - **Passing `transformer` to `createTRPCClient`.** The transformer belongs on each terminating link (`httpBatchLink`, `httpLink`, `wsLink`, ...), and TypeScript rejects it on the client itself. See [Data Transformers](https://trpc.io/docs/server/data-transformers.md). - **Using `createTRPCProxyClient`.** It's the v10 name, kept as a deprecated alias of `createTRPCClient`. - **Calling procedures like REST endpoints.** Procedures are addressed by their dot-separated path, for example `GET /trpc/post.byId?input=...`, not `/trpc/post/1`. Call them through the client, or see the [HTTP RPC Specification](https://trpc.io/docs/rpc.md) for the wire format. - **A JSON parse error like `Unexpected token '<'`.** The request reached something that answered with an HTML page, usually a 404, so the link's `url` doesn't match where your adapter serves tRPC (check the `/trpc` prefix). --- Source: https://trpc.io/docs/client/vanilla/infer-types # Inferring Types > It is often useful to access the types of your API within your clients. For this purpose, you are able to infer the types contained in your `AppRouter`. `@trpc/server` exports the following helper types to assist with inferring these types from the `AppRouter` exported by your `@trpc/server` router: - `inferRouterInputs` - `inferRouterOutputs` - `inferProcedureInput` - `inferProcedureOutput` - `inferSubscriptionInput` - `inferSubscriptionOutput` ## Inferring Input & Output Types Let's assume we have this example router: ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { z } from "zod"; const t = initTRPC.create(); const appRouter = t.router({ post: t.router({ list: t.procedure .query(() => { // imaginary db call return [{ id: 1, title: 'tRPC is the best!' }]; }), byId: t.procedure .input(z.string()) .query((opts) => { // imaginary db call return { id: 1, title: 'tRPC is the best!' }; }), create: t.procedure .input(z.object({ title: z.string(), text: z.string(), })) .mutation((opts) => { // imaginary db call return { id: 1, ...opts.input }; }), onPostAdd: t.procedure .input(z.object({ authorId: z.string() })) .subscription(async function* ({ input }) { // imaginary event source yield { id: 1, title: 'tRPC is the best!', authorId: input.authorId, }; }), }), }); export type AppRouter = typeof appRouter; ``` Using the helpers, we can infer the types of our router. The following example shows how to infer the types of the `post.create` procedure: ```ts title="client.ts" import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server'; import type { AppRouter } from './server'; type RouterInput = inferRouterInputs; type RouterOutput = inferRouterOutputs; type PostCreateInput = RouterInput['post']['create']; // type PostCreateInput = { // title: string; // text: string; // } type PostCreateOutput = RouterOutput['post']['create']; // type PostCreateOutput = { // title: string; // text: string; // id: number; // } ``` ## Inferring Individual Procedure Types If you already have access to a specific procedure on your router, you can infer its input or output directly: ```ts title="client.ts" import type { inferProcedureInput, inferProcedureOutput, } from '@trpc/server'; import type { AppRouter } from './server'; type PostByIdInput = inferProcedureInput; // type PostByIdInput = string type PostByIdOutput = inferProcedureOutput; // type PostByIdOutput = { // id: number; // title: string; // } ``` For subscriptions, you can infer the subscription input and the emitted data type: ```ts title="client.ts" import type { inferSubscriptionInput, inferSubscriptionOutput, } from '@trpc/server'; import type { AppRouter } from './server'; type OnPostAddInput = inferSubscriptionInput; // type OnPostAddInput = { // authorId: string; // } type OnPostAddOutput = inferSubscriptionOutput; // type OnPostAddOutput = { // id: number; // title: string; // authorId: string; // } ``` ## Infer `TRPCClientError` types It's also useful to infer the error type for your `AppRouter` ```ts title="client.ts" import { TRPCClientError } from '@trpc/client'; import type { AppRouter } from './server'; import { trpc } from './trpc'; export function isTRPCClientError( cause: unknown, ): cause is TRPCClientError { return cause instanceof TRPCClientError; } async function main() { try { await trpc.post.byId.query('1'); } catch (cause) { if (isTRPCClientError(cause)) { // `cause` is now typed as your router's `TRPCClientError` console.log('data', cause.data); // (property) TRPCClientError>; }>>>.data: Maybe } else { // [...] } } } main(); ``` --- Source: https://trpc.io/docs/client/vanilla/error-handling # Error Handling > A failed procedure call rejects with a [`TRPCClientError`](https://trpc.io/docs/client/vanilla/infer-types.md#infer-trpcclienterror-types). You can either let it throw and catch it, or use `safe()` to get it back as a type-safe value. ## Catching a thrown error `query()` and `mutate()` behave like any other promise, so a `try`/`catch` works as you would expect. TypeScript has no way to describe what a function throws, though, so `cause` arrives as `unknown` and has to be narrowed: ```ts title="client.ts" import { TRPCClientError } from '@trpc/client'; import type { AppRouter } from './server'; import { trpc } from './trpc'; try { const post = await trpc.post.byId.query('1'); } catch (cause) { if (cause instanceof TRPCClientError) { console.log(cause.data); } else { // something that isn't a tRPC error } } ``` See [Inferring Types](https://trpc.io/docs/client/vanilla/infer-types.md#infer-trpcclienterror-types) for a reusable `isTRPCClientError` guard. ## Errors as values with `safe()` `safe()` awaits a `query()` or `mutate()` call without letting it throw, handing back a `[data, error]` pair instead. Exactly one side is ever set, so checking either one narrows the other: ```ts title="client.ts" import { safe } from '@trpc/client'; import { trpc } from './trpc'; const [post, error] = await safe(trpc.post.byId.query('1')); if (error) { console.log(error.data); // (property) TRPCClientError<{ errorShape: FoldErrorShape; transformer: boolean; }>.data: Maybe } else { console.log(post.title); } ``` > [!NOTE] Info > Subscriptions don't need `safe()` - they never throw at the call site, and report failures through `onError`, which is already typed with the procedure's error shape. --- Source: https://trpc.io/docs/client/vanilla/aborting-procedure-calls # Aborting Procedure Calls > tRPC supports the standard `AbortController`/`AbortSignal` API for aborting procedures. All you have to do is pass an `AbortSignal` to the query or mutation options, and call the `AbortController` instance's `abort` method if you need to cancel the request. ```ts title="utils.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from './server'; const client = createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000/trpc', }), ], }); // 1. Create an AbortController instance - this is a standard javascript API const ac = new AbortController(); // 2. Pass the signal to a query or mutation const query = client.userById.query('id_bilbo', { signal: ac.signal }); // 3. Cancel the request if needed ac.abort(); ``` --- Source: https://trpc.io/docs/client/tanstack-react-query # TanStack React Query > TanStack React Query integration for tRPC This is the recommended way to use tRPC with React and TanStack Query. It provides factories for common TanStack React Query interfaces like `QueryKeys`, `QueryOptions`, and `MutationOptions`, giving you a more TanStack Query-native experience. If you're starting a new project, use this integration rather than the [classic React Query integration](https://trpc.io/docs/client/react.md), which only gets bug fixes and will be removed in the next major version of tRPC. To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). Read the [announcement post](/blog/introducing-tanstack-react-query-client) for more information about this change. Head to the [Setup](https://trpc.io/docs/client/tanstack-react-query/setup.md) guide to get started. --- Source: https://trpc.io/docs/client/tanstack-react-query/setup # TanStack React Query > Set up the TanStack React Query integration with or without React context, then query, mutate and invalidate Compared to our [classic React Query Integration](https://trpc.io/docs/client/react.md) this client is simpler and more TanStack Query-native, providing factories for common TanStack React Query interfaces like QueryKeys, QueryOptions, and MutationOptions. We think it's the future and recommend using this over the classic client, read the announcement post for more information about this change. > [!TIP] > You can try this integration out on the homepage of tRPC.io: [https://trpc.io/?try=minimal-react#try-it-out](https://trpc.io/?try=minimal-react#try-it-out)
❓ Do I have to use an integration? No! The integration is fully optional. You can use `@tanstack/react-query` using just a [vanilla tRPC client](https://trpc.io/docs/client/vanilla.md), although then you'll have to manually manage query keys and do not get the same level of DX as when using the integration package. ```ts title="utils/trpc.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from '../server/router'; export const trpc = createTRPCClient({ links: [httpBatchLink({ url: 'YOUR_API_URL' })], }); ``` ```tsx title="components/PostList.tsx" import { useQuery } from '@tanstack/react-query'; import { trpc } from './utils/trpc'; function PostList() { const { data } = useQuery({ queryKey: ['posts'] as const, queryFn: () => trpc.post.list.query(), }); data; // Post[] // ... } ```
## Setup ### 1. Install dependencies The following dependencies should be installed ```package-install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query ``` ### 2. Import your `AppRouter` Import your `AppRouter` type into the client application. This type holds the shape of your entire API. ```ts title="utils/trpc.ts" import type { AppRouter } from '../server/router'; ``` > [!TIP] > By using `import type` you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, [see the Typescript docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export). ### 3a. Set up the tRPC context provider In cases where you rely on React context, such as when using server-side rendering in full-stack frameworks like Next.js, it's important to create a new QueryClient for each request so that your users don't end up sharing the same cache, you can use the `createTRPCContext` to create a set of type-safe context providers and consumers from your `AppRouter` type signature. ```tsx title="utils/trpc.ts" import { createTRPCContext } from '@trpc/tanstack-react-query'; import type { AppRouter } from '../server/router'; export const { TRPCProvider, useTRPC, useTRPCClient } = createTRPCContext(); ``` Then, create a tRPC client, and wrap your application in the `TRPCProvider`, as below. You will also need to set up and connect React Query, which [they document in more depth](https://tanstack.com/query/latest/docs/framework/react/quick-start). > [!TIP] > If you already use React Query in your application, you **should** re-use the `QueryClient` and `QueryClientProvider` you already have. You can read more about the QueryClient initialization in the [React Query docs](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#initial-setup). ```tsx title="components/App.tsx" import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { useState } from 'react'; import type { AppRouter } from '../server/router'; import { TRPCProvider } from '../utils/trpc'; function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { // With SSR, we usually want to set some default staleTime // above 0 to avoid refetching immediately on the client staleTime: 60 * 1000, }, }, }); } let browserQueryClient: QueryClient | undefined = undefined; function getQueryClient() { if (typeof window === 'undefined') { // Server: always make a new query client return makeQueryClient(); } else { // Browser: make a new query client if we don't already have one // This is very important, so we don't re-make a new client if React // suspends during the initial render. This may not be needed if we // have a suspense boundary BELOW the creation of the query client if (!browserQueryClient) browserQueryClient = makeQueryClient(); return browserQueryClient; } } export function App() { const queryClient = getQueryClient(); const [trpcClient] = useState(() => createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:2022', }), ], }), ); return ( {null /* Your app here */} ); } ``` ### 3b. Set up with Query/Mutation Key Prefixing enabled If you want to prefix all queries and mutations with a specific key, see [Query Key Prefixing](https://trpc.io/docs/client/tanstack-react-query/usage.md#keyPrefix) for setup and usage examples. ### 3c. Set up without React context When building an SPA using only client-side rendering with something like Vite, you can create the `QueryClient` and tRPC client outside of React context as singletons. ```ts title="utils/trpc.ts" import { QueryClient } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { AppRouter } from '../server/router'; export const queryClient = new QueryClient(); const trpcClient = createTRPCClient({ links: [httpBatchLink({ url: 'http://localhost:2022' })], }); export const trpc = createTRPCOptionsProxy({ client: trpcClient, queryClient, }); ``` ```tsx title="components/App.tsx" import { QueryClientProvider } from '@tanstack/react-query'; import { queryClient } from '../utils/trpc'; export function App() { return ( {/* Your app here */} ); } ``` ### 4. Fetch data You can now use the tRPC React Query integration to call queries and mutations on your API. ```tsx title="components/user-list.tsx" import { useMutation, useQuery } from '@tanstack/react-query'; import { useTRPC } from '../utils/trpc'; export default function UserList() { const trpc = useTRPC(); // use `import { trpc } from './utils/trpc'` if you're using the singleton pattern const userQuery = useQuery(trpc.getUser.queryOptions({ id: 'id_bilbo' })); const userCreator = useMutation(trpc.createUser.mutationOptions()); return (

{userQuery.data?.name}

); } ``` > [!TIP] > A component that starts its own query can only fetch once it renders. If a route loader or server component knows the input, start the query there with `const [{ user }] = await loadHandles(trpc, { user: ensureEntry(trpc.getUser, { id }) })`. That gives you a **handle**: pass `user` to the component, which reads the query with `useQuery(fromHandle(trpc, props.user))`, without repeating the procedure or its input. The handle only names the query, so the data must be in the browser's cache. A loader in the browser already shares that cache. A server has to send its cache along, for example with [`HydrateClient`](https://trpc.io/docs/client/tanstack-react-query/handles.md#hydrate-client) in Next.js. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). ### 5. Invalidate queries after a mutation There is no tRPC-specific cache API: use TanStack's `QueryClient` with the keys and filters from `trpc`. `queryFilter()` matches one procedure, for every input if you leave the input out, `pathFilter()` matches every query under a router, and `trpc.pathFilter()` matches every tRPC query. See [Usage](https://trpc.io/docs/client/tanstack-react-query/usage.md) for all of them. ```tsx title="components/create-user.tsx" import { useMutation, useQueryClient } from '@tanstack/react-query'; import { useTRPC } from '../utils/trpc'; export function CreateUser() { const trpc = useTRPC(); const queryClient = useQueryClient(); const userCreator = useMutation( trpc.user.create.mutationOptions({ onSuccess: async (user) => { // Write the new user into the cache... queryClient.setQueryData(trpc.user.byId.queryKey({ id: user.id }), user); // ...and refetch every query under the `user` router await queryClient.invalidateQueries(trpc.user.pathFilter()); }, }), ); return ( ); } ``` ## Common mistakes - **Calling `queryFilter()` on a router.** `queryOptions`, `queryKey` and `queryFilter` only exist on query procedures. For a router, use `pathKey()` and `pathFilter()`. - **Writing query keys by hand.** A `useQuery({ queryKey: ['user', id], queryFn })` that calls the tRPC client works, but its key isn't tRPC's, so `queryFilter()`/`pathFilter()` invalidations and server-prefetched data never match it. Use the `trpc` factories instead. - **Using the classic hooks.** `trpc.user.byId.useQuery()` and `trpc.useUtils()` belong to the [classic `@trpc/react-query` client](https://trpc.io/docs/client/react.md). In this package, pass `trpc.*.queryOptions()` to TanStack's hooks and use `useQueryClient()` for the cache. See [Migrating](https://trpc.io/docs/client/tanstack-react-query/migrating.md). - **Calling `useTRPC()` outside the provider.** It throws `useTRPC() can only be used inside of a `. Mount `TRPCProvider`, with the same `queryClient` you give `QueryClientProvider`, above every component that calls `useTRPC()`. The [singleton setup](#3c-set-up-without-react-context) has no provider: import `trpc` instead. - **Sharing one `QueryClient` across server requests.** A module-level `new QueryClient()` is fine in a client-only SPA, but with server rendering it leaks one user's cache into another's. Create one per request on the server, as `getQueryClient()` does above. --- Source: https://trpc.io/docs/client/tanstack-react-query/usage # TanStack React Query > The options and key factories on the trpc proxy, such as queryOptions, infiniteQueryOptions, mutationOptions, subscriptionOptions, queryKey, queryFilter and pathFilter, plus key prefixing and type inference ## Quick example query ```tsx import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './trpc'; function Greeting() { const trpc = useTRPC(); const greetingQuery = useQuery(trpc.greeting.queryOptions({ name: 'Jerry' })); // greetingQuery.data === 'Hello Jerry' return

{greetingQuery.data}

; } ``` ## Usage The philosophy of this client is to provide thin and type-safe factories which work natively and type-safely with Tanstack React Query. This means just by following the autocompletes the client gives you, you can focus on building just with the knowledge the [TanStack React Query docs](https://tanstack.com/query/latest/docs/framework/react/overview) provide. ```tsx export default function Basics() { const trpc = useTRPC(); const queryClient = useQueryClient(); // Create QueryOptions which can be passed to query hooks const myQueryOptions = trpc.path.to.query.queryOptions({ /** inputs */ }) const myQuery = useQuery(myQueryOptions) // or: // useSuspenseQuery(myQueryOptions) // useInfiniteQuery(myQueryOptions) // Create MutationOptions which can be passed to useMutation const myMutationOptions = trpc.path.to.mutation.mutationOptions() const myMutation = useMutation(myMutationOptions) // Create a QueryKey which can be used to manipulate many methods // on TanStack's QueryClient in a type-safe manner const myQueryKey = trpc.path.to.query.queryKey() const invalidateMyQueryKey = () => { queryClient.invalidateQueries({ queryKey: myQueryKey }) } return ( // Your app here null ) } ``` The `trpc` object is fully type-safe and will provide autocompletes for all the procedures in your `AppRouter`. At the end of the proxy, the following methods are available: ### `queryOptions` - querying data {#queryOptions} Available for all query procedures. Provides a type-safe wrapper around [Tanstack's `queryOptions` function](https://tanstack.com/query/latest/docs/framework/react/reference/queryOptions). The first argument is the input for the procedure, and the second argument accepts any native Tanstack React Query options. ```ts const queryOptions = trpc.path.to.query.queryOptions( { /** input */ id: 'foo', }, { // Any Tanstack React Query options staleTime: 1000, }, ); ``` You can additionally provide a `trpc` object to the `queryOptions` function to provide tRPC request options to the client. ```ts const queryOptions = trpc.path.to.query.queryOptions( { /** input */ id: 'foo', }, { trpc: { // Provide tRPC request options to the client context: { // see https://trpc.io/docs/client/links#managing-context }, }, }, ); ``` If you want to disable a query in a type safe way, you can use `skipToken`: ```ts const query = useQuery( trpc.user.details.queryOptions( user?.id && project?.id ? { userId: user.id, projectId: project.id, } : skipToken, { staleTime: 1000, }, ), ); ``` The result can be passed to `useQuery` or `useSuspenseQuery` hooks or query client methods like `fetchQuery`, `prefetchQuery`, `prefetchInfiniteQuery`, `invalidateQueries`, etc. #### Streaming responses {#streaming} A query that returns an async generator streams with [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md#generators). `data` is an array of the chunks so far, through TanStack Query's [`experimental_streamedQuery`](https://tanstack.com/query/latest/docs/framework/react/reference/functions/experimental_streamedQuery): - The query is `pending` until the first chunk, then `success`, and `fetching` until the last chunk. - When a refetch's response arrives, `data` is cleared and the query is `pending` until its first chunk. - A refetch or `queryClient.cancelQueries()` stops the older stream: its chunks no longer reach the cache, and its request is aborted at its next chunk. - Unmounting doesn't stop the stream, unless you set `trpc: { abortOnUnmount: true }`. ```tsx import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './trpc'; export function Numbers() { const trpc = useTRPC(); const query = useQuery(trpc.numbers.queryOptions()); // const query: UseQueryResult> return
{query.data?.join(', ')}
; } ``` ### `infiniteQueryOptions` - querying infinite data {#infiniteQueryOptions} Available for all query procedures that take a cursor input. Provides a type-safe wrapper around [Tanstack's `infiniteQueryOptions` function](https://tanstack.com/query/latest/docs/framework/react/reference/infiniteQueryOptions). The first argument is the input for the procedure, and the second argument accepts any native Tanstack React Query options. ```ts const infiniteQueryOptions = trpc.path.to.query.infiniteQueryOptions( { /** input */ }, { // Any Tanstack React Query options getNextPageParam: (lastPage, pages) => lastPage.nextCursor, }, ); ``` ### `loadHandles` and `fromHandle` - passing queries as handles {#handles} On the server or in a route loader, list the queries as entries and load them in one call with the proxy from `createTRPCOptionsProxy`: ```ts import { ensureEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; const [handles, data] = await loadHandles(trpc, { comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }), post: ensureEntry(trpc.post.byId, { id }), }); ``` The load starts every entry before it waits for any, and resolves to a serializable handle for every entry and the data of the entries it waited for. Components read a handle with `fromHandle(trpc, handle)`, which returns the same options as `trpc.x.queryOptions(input)`, or `trpc.x.infiniteQueryOptions(input)` for an infinite handle. Type props with `inferQueryHandle` and `inferInfiniteQueryHandle`. - `prefetchEntry` doesn't wait. The reader shows a loading state until the data streams in: a `Suspense` fallback with `useSuspenseQuery`, or `status: 'pending'` with `useQuery`. - `ensureEntry` waits until the data is in the cache, so the reader shows the data on its first render. - `fetchEntry` also waits, and refetches stale data before it resolves. - For infinite queries, use `prefetchInfiniteEntry`, `ensureInfiniteEntry` and `fetchInfiniteEntry`. - When an ensure or fetch entry fails, the load rejects with a `TRPCEntryError` naming the entry. `isTRPCEntryError(error, trpc.post.byId)` checks which procedure failed, and `loadHandlesSettled` returns each entry's error as a value instead: see [Errors](https://trpc.io/docs/client/tanstack-react-query/handles.md#errors-ensure). - For an input only known during render, read the query directly with `trpc.x.queryOptions(input)`. - Handles carry no data. If the cache loses the data, for example after `queryClient.resetQueries()`, the reader loads it again, so give it a loading state either way. See [When the cache loses the data](https://trpc.io/docs/client/tanstack-react-query/handles.md#cache-loses-data). - Each entry maps to a single TanStack Query call: see [TanStack Query equivalents](https://trpc.io/docs/client/tanstack-react-query/handles.md#tanstack-equivalents). > [!NOTE] Info > The handle APIs are plain functions from `@trpc/tanstack-react-query/unstable-handles`. The `unstable-` in the path means they're new and may change, but you're safe to use them! [Read more](https://trpc.io/docs/faq.md#unstable). See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). ### `queryKey` - getting the query key and performing operations on the query client {#queryKey} Available for all query procedures. Allows you to access the query key in a type-safe manner. ```ts const queryKey = trpc.path.to.query.queryKey(); ``` Since Tanstack React Query uses fuzzy matching for query keys, you can also create a partial query key for any sub-path to match all queries belonging to a router: ```ts const queryKey = trpc.router.pathKey(); ``` Or even the root path to match all tRPC queries: ```ts const queryKey = trpc.pathKey(); ``` ### `infiniteQueryKey` - getting the infinite query key {#infiniteQueryKey} Available for all query procedures that take a cursor input. Allows you to access the query key for an infinite query in a type-safe manner. ```ts const infiniteQueryKey = trpc.path.to.query.infiniteQueryKey({ /** input */ }); ``` The result can be used with query client methods like `getQueryData`, `setQueryData`, `invalidateQueries`, etc. ```ts // Get cached data for an infinite query const cachedData = queryClient.getQueryData( trpc.path.to.query.infiniteQueryKey({ cursor: 0 }), ); // Set cached data for an infinite query queryClient.setQueryData( trpc.path.to.query.infiniteQueryKey({ cursor: 0 }), (data) => { // Modify the data return data; }, ); ``` ### `queryFilter` - creating query filters {#queryFilter} Available for all query procedures. Allows creating [query filters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters) in a type-safe manner. ```ts const queryFilter = trpc.path.to.query.queryFilter( { /** input */ }, { // Any Tanstack React Query filter predicate: (query) => { return !!query.state.data; }, }, ); ``` Like with query keys, if you want to run a filter across a whole router you can use `pathFilter` to target any sub-path. ```ts const queryFilter = trpc.path.pathFilter({ // Any Tanstack React Query filter predicate: (query) => { return !!query.state.data; }, }); ``` Useful for creating filters that can be passed to client methods like `queryClient.invalidateQueries` etc. ### `infiniteQueryFilter` - creating infinite query filters {#infiniteQueryFilter} Available for all query procedures that take a cursor input. Allows creating [query filters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters) for infinite queries in a type-safe manner. ```ts const infiniteQueryFilter = trpc.path.to.query.infiniteQueryFilter( { /** input */ }, { // Any Tanstack React Query filter predicate: (query) => { return !!query.state.data; }, }, ); ``` Useful for creating filters that can be passed to client methods like `queryClient.invalidateQueries` etc. ```ts await queryClient.invalidateQueries( trpc.path.to.query.infiniteQueryFilter( {}, { predicate: (query) => { // Filter logic based on query state return query.state.status === 'success'; }, }, ), ); ``` ### `mutationOptions` - creating mutation options {#mutationOptions} Available for all mutation procedures. Provides a type-safe identity function for constructing options that can be passed to `useMutation`. ```ts const mutationOptions = trpc.path.to.mutation.mutationOptions({ // Any Tanstack React Query options onSuccess: (data) => { // do something with the data }, }); ``` ### `mutationKey` - getting the mutation key {#mutationKey} Available for all mutation procedures. Allows you to get the mutation key in a type-safe manner. ```ts const mutationKey = trpc.path.to.mutation.mutationKey(); ``` ### `subscriptionOptions` - creating subscription options {#subscriptionOptions} TanStack does not provide a subscription hook, so we continue to expose our own abstraction here which works with a [standard tRPC subscription setup](https://trpc.io/docs/server/subscriptions.md). Available for all subscription procedures. Provides a type-safe identity function for constructing options that can be passed to `useSubscription`. Note that you need to have either the [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md) or [`wsLink`](https://trpc.io/docs/client/links/wsLink.md) configured in your tRPC client to use subscriptions. ```tsx function SubscriptionExample() { const trpc = useTRPC(); const subscription = useSubscription( trpc.path.to.subscription.subscriptionOptions( { /** input */ }, { enabled: true, onStarted: () => { // do something when the subscription is started }, onData: (data) => { // you can handle the data here }, onError: (error) => { // you can handle the error here }, onComplete: () => { // the subscription was ended by the server, `status` is now `'idle'` }, onConnectionStateChange: (state) => { // you can handle the connection state here }, }, ), ); // Or you can handle the state here subscription.data; // The lastly received data subscription.error; // The lastly received error /** * The current status of the subscription. * Will be one of: `'idle'`, `'connecting'`, `'pending'`, or `'error'`. * * - `idle`: subscription is disabled or ended * - `connecting`: trying to establish a connection * - `pending`: connected to the server, receiving data * - `error`: an error occurred and the subscription is stopped */ subscription.status; // Reset the subscription (if you have an error etc) subscription.reset(); return <>{/* ... */}; } ``` ### Query Key Prefixing {#keyPrefix} When using multiple tRPC providers in a single application (e.g., connecting to different backend services), queries with the same path will collide in the cache. You can prevent this by enabling query key prefixing. ```tsx // Without prefixes - these would collide! const authQuery = useQuery(trpcAuth.list.queryOptions()); // auth service const billingQuery = useQuery(trpcBilling.list.queryOptions()); // billing service ``` Enable the feature flag when creating your context: ```tsx title="utils/trpc.ts" // [...] const billing = createTRPCContext(); export const BillingProvider = billing.TRPCProvider; export const useBilling = billing.useTRPC; export const createBillingClient = () => createTRPCClient({ links: [ /* ... */ ], }); const account = createTRPCContext(); export const AccountProvider = account.TRPCProvider; export const useAccount = account.useTRPC; export const createAccountClient = () => createTRPCClient({ links: [ /* ... */ ], }); ``` ```tsx title="App.tsx" import { useState } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { BillingProvider, AccountProvider, createBillingClient, createAccountClient, } from './utils/trpc'; // [...] export function App() { const [queryClient] = useState(() => new QueryClient()); const [billingClient] = useState(() => createBillingClient()); const [accountClient] = useState(() => createAccountClient()); return (
{/* ... */}
); } ``` ```tsx title="components/MyComponent.tsx" import { useQuery } from '@tanstack/react-query'; import { useBilling, useAccount } from '../utils/trpc'; // [...] export function MyComponent() { const billing = useBilling(); const account = useAccount(); const billingList = useQuery(billing.list.queryOptions()); const accountList = useQuery(account.list.queryOptions()); return (
Billing: {JSON.stringify(billingList.data ?? null)}
Account: {JSON.stringify(accountList.data ?? null)}
); } ``` The query keys will be properly prefixed to avoid collisions: ```tsx // Example of how the query keys look with prefixes const queryKeys = [ [['billing'], ['list'], { type: 'query' }], [['account'], ['list'], { type: 'query' }], ]; ``` ### Inferring Input and Output types When you need to infer the input and output types for a procedure or router, there are 2 options available depending on the situation. Infer the input and output types of a full router ```ts import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server'; import type { AppRouter } from './server/router'; export type Inputs = inferRouterInputs; export type Outputs = inferRouterOutputs; ``` Infer types for a single procedure ```ts import type { inferInput, inferOutput } from '@trpc/tanstack-react-query'; function Component() { const trpc = useTRPC(); type Input = inferInput; type Output = inferOutput; } ``` ### Accessing the tRPC client {#useTRPCClient} If you used the [setup with React Context](https://trpc.io/docs/client/tanstack-react-query/setup.md#3a-set-up-the-trpc-context-provider), you can access the tRPC client using the `useTRPCClient` hook. ```tsx import { useTRPCClient } from './trpc'; async function Component() { const trpcClient = useTRPCClient(); const result = await trpcClient.getUser.query({ id: '1', }); } ``` If you [setup without React Context](https://trpc.io/docs/client/tanstack-react-query/setup.md#3c-set-up-without-react-context), you can import the global client instance directly instead. ```ts import { client } from './trpc'; const result = await client.path.to.procedure.query({ /** input */ id: 'foo', }); ``` --- Source: https://trpc.io/docs/client/tanstack-react-query/migrating # Migrating from the classic React Client > Migrating from the classic React Client There are a few approaches to migrate over, and this library is a significant departure from the classic client, so we're not expecting anybody to do it in one shot. But you will probably want to try a combination of... ## Codemod migration Run the upgrade CLI from the folder with your `tsconfig.json`, on a git working tree without uncommitted changes: ```sh npx @trpc/upgrade --yes ``` It runs two transforms over the files git tracks: - **Setup:** `createTRPCReact` becomes `createTRPCContext`, `trpc.Provider` becomes `TRPCProvider`, and `trpc.createClient()` becomes `createTRPCClient()`. A `createTRPCNext` setup becomes the same file exporting `makeTRPCClient()`, `makeQueryClient()` and a `withTRPC()` for `_app`, which hydrates `trpcState` like before. See [Moving from `createTRPCNext`](https://trpc.io/docs/client/nextjs/pages-router/setup.md#moving-from-createtrpcnext). - **Hooks:** each hook becomes the TanStack Query hook with an options factory, such as `useQuery(trpc.a.queryOptions(input))`, and `trpc.useUtils()` becomes `useQueryClient()` with the matching filters and keys. `trpc.useQueries()`, `useSuspenseQueries()`, `utils.client` and `getQueryKey()` are covered too, as in the [table below](#equivalents-for-the-other-hooks-and-useutils). Each component or hook that needs it gets `const trpc = useTRPC()`. Then it installs `@trpc/tanstack-react-query`, and uninstalls `@trpc/react-query` and `@trpc/next` unless a file still imports them, e.g. `createServerSideHelpers` from `@trpc/react-query/server`. Pass `--skipTanstackQuery` to leave your packages alone, or `--transforms provider` or `--transforms hooks` to run one transform. Without `--yes` or `--transforms`, it asks which to run. What it can't move safely, such as `ssr: true` or a `trpc` used outside a component, gets a `TODO(@trpc/upgrade)` comment. Afterwards, format the changed files, typecheck, and search for those comments: ```sh npx tsc --noEmit ``` ## Gradual migration The new and classic clients are compatible with each other and [can live together in the same application](https://github.com/juliusmarminge/trpc-interop/blob/main/src/client.tsx). This means you can start migrating by using the new client in new parts of your application, and gradually migrate over existing usage as you see fit. Most importantly, Query Keys are identical, which means you can use the new client and classic client together and still rely on TanStack Query's caching. ### Migrating the provider Install the new package, and create its hooks next to the classic ones ```package-install @trpc/tanstack-react-query ``` ```ts title="utils/trpc.ts" import { createTRPCReact } from '@trpc/react-query'; import { createTRPCContext } from '@trpc/tanstack-react-query'; import type { AppRouter } from '../server/router'; // Classic, until nothing uses it export const trpc = createTRPCReact(); export const { TRPCProvider, useTRPC, useTRPCClient } = createTRPCContext(); ``` The classic `trpc.Provider` takes the tRPC client as `client`; `TRPCProvider` takes it as `trpcClient`. While both are mounted, give them the same `QueryClient` and tRPC client, so they share one cache. `trpc.createClient()` becomes `createTRPCClient()` from `@trpc/client`. ```tsx title="components/App.tsx" import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { useState } from 'react'; import type { AppRouter } from '../server/router'; import { trpc, TRPCProvider } from '../utils/trpc'; export function App(props: { children: React.ReactNode }) { const [queryClient] = useState(() => new QueryClient()); const [trpcClient] = useState(() => createTRPCClient({ links: [httpBatchLink({ url: '/api/trpc' })], }), ); return ( {/* Remove once nothing uses the classic hooks */} {props.children} ); } ``` ### Migrating Queries A classic query would look like this ```tsx import { trpc } from './trpc'; function Users() { const greetingQuery = trpc.greeting.useQuery({ name: 'Jerry' }); // greetingQuery.data === 'Hello Jerry' } ``` and changes to ```tsx import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './trpc'; function Users() { const trpc = useTRPC(); const greetingQuery = useQuery(trpc.greeting.queryOptions({ name: 'Jerry' })); // greetingQuery.data === 'Hello Jerry' } ``` > [!TIP] > Once a component is on `queryOptions`, you can also start its query ahead of time. `const [{ greeting }] = await loadHandles(trpc, { greeting: ensureEntry(trpc.greeting, { name: 'Jerry' }) })` in a route loader or server component gives you a **handle** for it. Pass `greeting` to the component, which reads it with `useQuery(fromHandle(trpc, props.greeting))`. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). ### Migrating Invalidations and other QueryClient usages A classic invalidation pattern would look like this ```tsx import { trpc } from './trpc'; function Users() { const utils = trpc.useUtils(); async function invalidateGreeting() { await utils.greeting.invalidate({ name: 'Jerry' }); } } ``` and changes to ```tsx import { useQueryClient } from '@tanstack/react-query'; import { useTRPC } from './trpc'; function Users() { const trpc = useTRPC(); const queryClient = useQueryClient(); async function invalidateGreeting() { await queryClient.invalidateQueries( trpc.greeting.queryFilter({ name: 'Jerry' }), ); } } ``` This is the same for any QueryClient usage, instead of using tRPC's `useUtils` you can now follow the TanStack documentation directly ### Migrating Mutations A classic mutation might look like this ```tsx import { trpc } from './trpc'; function Users() { const createUserMutation = trpc.createUser.useMutation(); createUserMutation.mutate({ name: 'Jerry' }); } ``` and changes to ```tsx import { useMutation } from '@tanstack/react-query'; import { useTRPC } from './trpc'; function Users() { const trpc = useTRPC(); const createUserMutation = useMutation(trpc.createUser.mutationOptions()); createUserMutation.mutate({ name: 'Jerry' }); } ``` ### Equivalents for the other hooks and `useUtils` Every hook takes the `trpc` from `useTRPC()`, and `utils` becomes `const queryClient = useQueryClient()`. Here `a` is a procedure and `r` a router. | Classic | New | | --------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `trpc.a.useSuspenseQuery(input)` | `useSuspenseQuery(trpc.a.queryOptions(input))`, which returns the query, not a `[data, query]` pair | | `trpc.a.useInfiniteQuery(input, opts)` | `useInfiniteQuery(trpc.a.infiniteQueryOptions(input, opts))` | | `trpc.a.useSubscription(input, opts)` | `useSubscription(trpc.a.subscriptionOptions(input, opts))`, imported from `@trpc/tanstack-react-query` | | `trpc.useQueries((t) => [t.a(input)])` | `useQueries({ queries: [trpc.a.queryOptions(input)] })` | | `utils.a.invalidate(input)` | `queryClient.invalidateQueries(trpc.a.queryFilter(input))` | | `utils.r.invalidate()` / `utils.invalidate()` | `queryClient.invalidateQueries(trpc.r.pathFilter())` / `(trpc.pathFilter())` | | `utils.a.refetch()`, `reset()`, `cancel()` | `refetchQueries`, `resetQueries`, `cancelQueries` with the same filters | | `utils.a.fetch(input)`, `prefetch`, `ensureData` | `queryClient.fetchQuery(trpc.a.queryOptions(input))`, `prefetchQuery`, `ensureQueryData` | | `utils.a.fetchInfinite(input)`, `prefetchInfinite` | `fetchInfiniteQuery(trpc.a.infiniteQueryOptions(input))`, `prefetchInfiniteQuery` | | `utils.a.getData(input)`, `setData(input, updater)` | `queryClient.getQueryData(trpc.a.queryKey(input))`, `setQueryData(trpc.a.queryKey(input), updater)` | | `utils.a.getInfiniteData`, `setInfiniteData` | The same, with `trpc.a.infiniteQueryKey(input)` | | `utils.client` | `useTRPCClient()` | ### Migrating `abortOnUnmount` The classic integration takes `abortOnUnmount` when you create the client, which sets the default for every query β€” an individual query can still override it through its own `trpc` option ```ts title="trpc.ts" import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from './server/router'; export const trpc = createTRPCReact({ abortOnUnmount: true, }); ``` `createTRPCContext()` takes no options, so there is no global equivalent. Set `abortOnUnmount` per query instead, in the same `trpc` option the classic integration uses per request ```tsx import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './trpc'; function Users() { const trpc = useTRPC(); const greetingQuery = useQuery( trpc.greeting.queryOptions({ name: 'Jerry' }, { trpc: { abortOnUnmount: true } }), ); } ``` > [!NOTE] > @tanstack/react-query only supports aborting queries, so this applies to `queryOptions` and `infiniteQueryOptions`. ### Migrating `overrides` `createTRPCContext()` doesn't take the classic `overrides` either. To run something after every mutation, such as [invalidating the whole cache](https://trpc.io/docs/client/react/useUtils.md#invalidate-full-cache-on-every-mutation), use TanStack's own `MutationCache` callbacks ```ts title="utils/query-client.ts" import { MutationCache, QueryClient } from '@tanstack/react-query'; export const queryClient: QueryClient = new QueryClient({ mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries(), }), }); ``` ## Common mistakes - **Destructuring `useSuspenseQuery`.** The classic hook returns `[data, query]`; TanStack's returns the query, so `const [data] = ...` becomes `const { data } = ...`. - **Mounting a second `QueryClient`.** While both clients are in use, a separate `QueryClient` for each provider splits the cache, so an invalidation from one side doesn't refresh queries on the other. Share one. - **Losing `@trpc/react-query` mid-migration.** The upgrade CLI uninstalls it unless you pass `--skipTanstackQuery`. - **Trusting the codemod blindly.** It rewrites the common patterns only. Typecheck after it runs, and check custom wrappers around tRPC hooks by hand. --- Source: https://trpc.io/docs/client/tanstack-react-query/server-components # Set up with React Server Components > Prefetch tRPC queries in React Server Components, hydrate them into client components, and call procedures directly on the server > [!TIP] > **Using Next.js?** See the dedicated [Next.js App Router setup guide](https://trpc.io/docs/client/nextjs/app-router-setup.md) for a streamlined walkthrough tailored to Next.js. This guide is an overview of how one may use tRPC with a React Server Components (RSC) framework such as Next.js App Router. Be aware that RSC on its own solves a lot of the same problems tRPC was designed to solve, so you may not need tRPC at all. There is also not a one-size-fits-all way to integrate tRPC with RSCs, so see this guide as a starting point and adjust it to your needs and preferences. > [!NOTE] Info > If you're looking for how to use tRPC with Server Actions, see the [Server Actions guide](https://trpc.io/docs/client/nextjs/server-actions.md). > [!WARNING] Caution > Please read React Query's [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) docs before proceeding to understand the different types of server rendering > and what footguns to avoid. ## Add tRPC to existing projects ### 1. Install deps ```package-install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query@latest zod client-only server-only ``` ### 2. Create a tRPC router Initialize your tRPC backend in `trpc/init.ts` using the `initTRPC` function, and create your first router. We're going to make a simple "hello world" router and procedure here - but for deeper information on creating your tRPC API you should refer to the [Quickstart guide](https://trpc.io/docs/quickstart.md) and [Backend usage docs](https://trpc.io/docs/server/overview.md) for tRPC information. > [!NOTE] Info > The file names used here are not enforced by tRPC. You may use any file structure you wish.
View sample backend ```ts title="trpc/init.ts" import { initTRPC } from '@trpc/server'; import { cache } from 'react'; export const createTRPCContext = cache(async () => { /** * @see: https://trpc.io/docs/server/context */ return { userId: 'user_123' }; }); // Avoid exporting the entire t-object // since it's not very descriptive. // For instance, the use of a t variable // is common in i18n libraries. const t = initTRPC.create({ /** * @see https://trpc.io/docs/server/data-transformers */ // transformer: superjson, }); // Base router and procedure helpers export const createTRPCRouter = t.router; export const createCallerFactory = t.createCallerFactory; export const baseProcedure = t.procedure; ```
```ts title="trpc/routers/_app.ts" import { z } from 'zod'; import { baseProcedure, createTRPCRouter } from '../init'; export const appRouter = createTRPCRouter({ hello: baseProcedure .input( z.object({ text: z.string(), }), ) .query((opts) => { return { greeting: `hello ${opts.input.text}`, }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ```
> [!NOTE] > The backend adapter depends on your framework and how it sets up API routes. The following example sets up GET and POST routes at `/api/trpc/*` using the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) in Next.js. ```ts title="app/api/trpc/[trpc]/route.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createTRPCContext } from '../../../../trpc/init'; import { appRouter } from '../../../../trpc/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: createTRPCContext, }); export { handler as GET, handler as POST }; ```
### 3. Create a Query Client factory Create a shared file `trpc/query-client.ts` that exports a function that creates a `QueryClient` instance. ```ts title="trpc/query-client.ts" import { defaultShouldDehydrateQuery, QueryClient, } from '@tanstack/react-query'; import superjson from 'superjson'; export function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { staleTime: 30 * 1000, }, dehydrate: { // serializeData: superjson.serialize, shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', shouldRedactErrors: (error) => { // Next.js detects dynamic pages by catching the errors we throw, so // we must not redact them here. Next.js redacts with a better digest // of its own. return false; }, }, hydrate: { // deserializeData: superjson.deserialize, }, }, }); } ``` We're setting a few default options here: - `staleTime`: With SSR, we usually want to set some default staleTime above 0 to avoid refetching immediately on the client. - `shouldDehydrateQuery`: This is a function that determines whether a query should be dehydrated or not. Since the RSC transport protocol supports hydrating promises over the network, we extend the `defaultShouldDehydrateQuery` function to also include queries that are still pending. This will allow us to start prefetching in a server component high up the tree, then consuming that promise in a client component further down. - `shouldRedactErrors`: Next.js detects dynamic rendering by looking for the `digest` on an error thrown during the render. Because `shouldDehydrateQuery` also dehydrates queries that are still pending, a query that is pending during the build can reject afterwards, and its error gets dehydrated and redacted before Next.js sees the `digest`. The build then fails. Returning `false` here keeps the `digest` intact so Next.js can still recognise the error. - `serializeData` and `deserializeData` (optional): If you set up a [data transformer](https://trpc.io/docs/server/data-transformers.md) in the previous step, set this option to make sure the data is serialized correctly when hydrating the query client over the server-client boundary. ### 4. Create a tRPC client for Client Components The `trpc/client.tsx` is the entrypoint when consuming your tRPC API from client components. In here, import the **type definition** of your tRPC router and create typesafe hooks using `createTRPCContext`. We'll also export our context provider from this file. ```tsx title="trpc/client.tsx" 'use client'; // ^-- to make sure we can mount the Provider from a server component import type { QueryClient } from '@tanstack/react-query'; import { QueryClientProvider } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { createTRPCContext } from '@trpc/tanstack-react-query'; import { useState } from 'react'; import { makeQueryClient } from './query-client'; import type { AppRouter } from './routers/_app'; export const { TRPCProvider, useTRPC } = createTRPCContext(); let browserQueryClient: QueryClient; function getQueryClient() { if (typeof window === 'undefined') { // Server: always make a new query client return makeQueryClient(); } // Browser: make a new query client if we don't already have one // This is very important, so we don't re-make a new client if React // suspends during the initial render. This may not be needed if we // have a suspense boundary BELOW the creation of the query client if (!browserQueryClient) browserQueryClient = makeQueryClient(); return browserQueryClient; } function getUrl() { const base = (() => { if (typeof window !== 'undefined') return ''; if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; return 'http://localhost:3000'; })(); return `${base}/api/trpc`; } export function TRPCReactProvider( props: Readonly<{ children: React.ReactNode; }>, ) { // NOTE: Avoid useState when initializing the query client if you don't // have a suspense boundary between this and the code that may // suspend because React will throw away the client on the initial // render if it suspends and there is no boundary const queryClient = getQueryClient(); const [trpcClient] = useState(() => createTRPCClient({ links: [ httpBatchLink({ // transformer: superjson, <-- if you use a data transformer url: getUrl(), }), ], }), ); return ( {props.children} ); } ``` Mount the provider in the root of your application (e.g. `app/layout.tsx` when using Next.js). ### 5. Create a tRPC caller for Server Components To prefetch queries from server components, we create a proxy from our router. You can also pass in a client if your router is on a separate server. ```tsx title="trpc/server.tsx" import 'server-only'; // <-- ensure this file cannot be imported from the client import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import { createTRPCClient, httpLink } from '@trpc/client'; import { cache } from 'react'; import { createTRPCContext } from './init'; import { makeQueryClient } from './query-client'; import { appRouter } from './routers/_app'; import type { AppRouter } from './routers/_app'; // IMPORTANT: Create a stable getter for the query client that // will return the same client during the same request. export const getQueryClient = cache(makeQueryClient); export const trpc = createTRPCOptionsProxy({ ctx: createTRPCContext, router: appRouter, queryClient: getQueryClient, }); // If your router is on a separate server, pass a client: createTRPCOptionsProxy({ client: createTRPCClient({ links: [httpLink({ url: '...' })], }), queryClient: getQueryClient, }); ``` ## Using your API > [!TIP] > To avoid repeating the procedure and input in client components, load the queries with `loadHandles` and pass the returned handles down. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). Now you can use your tRPC API in your app. While you can use the React Query hooks in client components just like you would in any other React app, we can take advantage of the RSC capabilities by prefetching queries in a server component high up the tree. You may be familiar with this concept as "render as you fetch" commonly implemented as loaders. This means the request fires as soon as possible but without suspending until the data is needed by using the `useSuspenseQuery` hook. This approach leverages Next.js App Router's streaming capabilities, initiating the query on the server and streaming data to the client as it becomes available. It optimizes both the time to first byte in the browser and the data fetch time, resulting in faster page loads. Read a prefetch you don't `await` with `useSuspenseQuery` ([Leveraging Suspense](#leveraging-suspense)): with `useQuery`, the server can render the loading state while the browser already has the data, and React reports a hydration mismatch. For a component on `useQuery`, like the one below, `await` the `prefetchQuery` call instead. This ensures the query on the client always has data on first render, but it comes with a tradeoff - the page will load more slowly since the server must complete the query before sending HTML to the client. ```tsx title="app/page.tsx" import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import { getQueryClient, trpc } from '../trpc/server'; import { ClientGreeting } from './client-greeting'; export default async function Home() { const queryClient = getQueryClient(); await queryClient.prefetchQuery( trpc.hello.queryOptions({ /** input */ }), ); return (
...
{/** ... */}
); } ``` ```tsx title="app/client-greeting.tsx" 'use client'; // <-- hooks can only be used in client components import { useQuery } from '@tanstack/react-query'; import { useTRPC } from '../trpc/client'; export function ClientGreeting() { const trpc = useTRPC(); const greetingQuery = useQuery(trpc.hello.queryOptions({ text: 'world' })); switch (greetingQuery.status) { case 'pending': return
Loading...
; case 'error': return
Error: {greetingQuery.error.message}
; case 'success': return
{greetingQuery.data.greeting}
; } } ``` > [!TIP] > You can also create `prefetch` and `HydrateClient` helper functions to make it a bit more concise and reusable: > > ```tsx twoslash title="trpc/server.tsx" > // @jsx: react-jsx > // @filename: trpc/query-client.ts > import { QueryClient } from '@tanstack/react-query'; > export function makeQueryClient() { return new QueryClient(); } > > // @filename: trpc/server.tsx > import { cache } from 'react'; > import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; > import type { TRPCQueryOptions } from '@trpc/tanstack-react-query'; > import { makeQueryClient } from './query-client'; > const getQueryClient = cache(makeQueryClient); > // ---cut--- > export function HydrateClient(props: { children: React.ReactNode }) { > const queryClient = getQueryClient(); > return ( > > {props.children} > > ); > } > > export function prefetch>>( > queryOptions: T, > ) { > const queryClient = getQueryClient(); > if (queryOptions.queryKey[1]?.type === 'infinite') { > void queryClient.prefetchInfiniteQuery(queryOptions as any); > } else { > void queryClient.prefetchQuery(queryOptions); > } > } > ``` > > `prefetch` doesn't await the query, so read it with `useSuspenseQuery` ([Leveraging Suspense](#leveraging-suspense)). Then you can use it like this: > > ```tsx twoslash > // @jsx: react-jsx > // @filename: trpc/init.ts > import { initTRPC } from '@trpc/server'; > const t = initTRPC.create(); > export const createTRPCContext = async () => ({ userId: 'user_123' }); > export const createTRPCRouter = t.router; > export const baseProcedure = t.procedure; > > // @filename: trpc/query-client.ts > import { QueryClient } from '@tanstack/react-query'; > export function makeQueryClient() { return new QueryClient(); } > > // @filename: trpc/routers/_app.ts > import { initTRPC } from '@trpc/server'; > import { z } from 'zod'; > const t = initTRPC.create(); > export const appRouter = t.router({ > hello: t.procedure.input(z.object({ text: z.string().optional() }).optional()).query((opts) => ({ > greeting: `hello ${opts.input?.text ?? 'world'}`, > })), > }); > export type AppRouter = typeof appRouter; > > // @filename: trpc/server.tsx > import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; > import type { TRPCQueryOptions } from '@trpc/tanstack-react-query'; > import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'; > import { cache } from 'react'; > import { createTRPCContext } from './init'; > import { makeQueryClient } from './query-client'; > import { appRouter } from './routers/_app'; > export const getQueryClient = cache(makeQueryClient); > export const trpc = createTRPCOptionsProxy({ ctx: createTRPCContext, router: appRouter, queryClient: getQueryClient }); > export function HydrateClient(props: { children: React.ReactNode }) { > const queryClient = getQueryClient(); > return {props.children}; > } > export function prefetch>>(queryOptions: T) { > const queryClient = getQueryClient(); > void queryClient.prefetchQuery(queryOptions); > } > > // @filename: app/client-greeting.tsx > export function ClientGreeting() { return null; } > > // @filename: app/page.tsx > // ---cut--- > import { HydrateClient, prefetch, trpc } from '../trpc/server'; > import { ClientGreeting } from './client-greeting'; > > function Home() { > prefetch( > trpc.hello.queryOptions({ > /** input */ > }), > ); > > return ( > >
...
> {/** ... */} > >
> ); > } > ``` > > This `HydrateClient` sends every query in the cache each time it renders, so nested ones send the same queries again. `unstable_createHydrateClient(getQueryClient)` creates one that sends each query once per request. See [`HydrateClient`](https://trpc.io/docs/client/tanstack-react-query/handles.md#hydrate-client). ### Leveraging Suspense You may prefer handling loading and error states using Suspense and Error Boundaries. You can do this by using the `useSuspenseQuery` hook. ```tsx title="app/page.tsx" import { HydrateClient, prefetch, trpc } from '../trpc/server'; import { Suspense } from 'react'; import { ErrorBoundary } from 'react-error-boundary'; import { ClientGreeting } from './client-greeting'; export default async function Home() { prefetch(trpc.hello.queryOptions()); return (
...
{/** ... */} Something went wrong}> Loading...}>
); } ``` ```tsx title="app/client-greeting.tsx" 'use client'; import { useSuspenseQuery } from '@tanstack/react-query'; import { useTRPC } from '../trpc/client'; export function ClientGreeting() { const trpc = useTRPC(); const greetingQuery = useSuspenseQuery(trpc.hello.queryOptions()); return
{greetingQuery.data.greeting}
; } ``` ### Getting data in a server component If you need access to the data in a server component, we recommend creating a server caller and using it directly. Please note that this method is detached from your query client and does not store the data in the cache. This means that you cannot use the data in a server component and expect it to be available in the client. This is intentional and explained in more detail in the [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#data-ownership-and-revalidation) guide. ```tsx title="trpc/server.tsx" // ... export const caller = appRouter.createCaller(createTRPCContext); ``` ```tsx title="app/page.tsx" import { caller } from '../trpc/server'; export default async function Home() { const greeting = await caller.hello(); return
{greeting.greeting}
; } ``` If you **really** need to use the data both on the server as well as inside client components and understand the tradeoffs explained in the [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#data-ownership-and-revalidation) guide, you can use `fetchQuery` instead of `prefetch` to have the data both on the server as well as hydrating it down to the client: ```tsx title="app/page.tsx" import { getQueryClient, HydrateClient, trpc } from '../trpc/server'; import { ClientGreeting } from './client-greeting'; export default async function Home() { const queryClient = getQueryClient(); const greeting = await queryClient.fetchQuery(trpc.hello.queryOptions()); // Do something with greeting on the server return (
...
{/** ... */}
); } ``` --- Source: https://trpc.io/docs/client/tanstack-react-query/tanstack-start # Set up with TanStack Start > This guide shows how to use tRPC with [TanStack Start](https://tanstack.com/start): route loaders start queries, and components read them through [handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). > [!NOTE] Info > We have prefixed the handle APIs with `unstable_` as they're new, but you're safe to use them! [Read more](https://trpc.io/docs/faq.md#unstable). tRPC adds no router integration of its own. Data crosses from the server to the browser through TanStack's [SSR query integration](https://tanstack.com/router/latest/docs/integrations/query), with your tRPC data transformer. The [SSE chat example](https://github.com/trpc/trpc/tree/main/examples/tanstack-start-sse-chat) is a complete TanStack Start app that uses handles in its loaders. ## 1. Install deps ```sh npm install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query @tanstack/react-router-ssr-query superjson zod ``` ## 2. Create a query client factory Use your tRPC transformer to serialize query data, and set a `staleTime` above 0 so the browser doesn't refetch right after hydration: ```ts title="src/lib/query-client.ts" import { QueryClient } from '@tanstack/react-query'; import superjson from 'superjson'; export function createQueryClient() { return new QueryClient({ defaultOptions: { queries: { staleTime: 30 * 1000 }, dehydrate: { serializeData: superjson.serialize }, hydrate: { deserializeData: superjson.deserialize }, }, }); } ``` ## 3. Create an isomorphic tRPC client During server rendering, call procedures in the same process with `localLink`. In the browser, call them over HTTP: ```ts title="src/lib/trpc.ts" import { createIsomorphicFn } from '@tanstack/react-start'; import { getRequest } from '@tanstack/react-start/server'; import { createTRPCClient, httpBatchStreamLink, localLink, type TRPCLink, } from '@trpc/client'; import { createTRPCContext, type TRPCOptionsProxy } from '@trpc/tanstack-react-query'; import superjson from 'superjson'; import { createContext } from '~/server/context'; import { appRouter, type AppRouter } from '~/server/routers/_app'; export const { TRPCProvider, useTRPC } = createTRPCContext(); export type TRPC = TRPCOptionsProxy; const getLinks = createIsomorphicFn() .server((): TRPCLink[] => [ localLink({ router: appRouter, createContext: () => createContext({ req: getRequest() }), transformer: superjson, }), ]) .client((): TRPCLink[] => [ httpBatchStreamLink({ url: '/api/trpc', transformer: superjson }), ]); export const makeTRPCClient = () => createTRPCClient({ links: getLinks() }); ``` The browser's link calls `/api/trpc`. Serve it from a [server route](https://tanstack.com/start/latest/docs/framework/react/guide/server-routes) with the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md): ```ts title="src/routes/api/trpc.$.ts" import { createFileRoute } from '@tanstack/react-router'; import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createContext } from '~/server/context'; import { appRouter } from '~/server/routers/_app'; const handler = ({ request }: { request: Request }) => fetchRequestHandler({ endpoint: '/api/trpc', req: request, router: appRouter, createContext, }); export const Route = createFileRoute('/api/trpc/$')({ server: { handlers: { GET: handler, POST: handler } }, }); ``` ## 4. Put the proxy in the router context Create one proxy per router with `createTRPCOptionsProxy`, and pass it to loaders through the router context: ```tsx title="src/router.tsx" import { createRouter } from '@tanstack/react-router'; import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import { createQueryClient } from '~/lib/query-client'; import { makeTRPCClient, TRPCProvider } from '~/lib/trpc'; import type { AppRouter } from '~/server/routers/_app'; import { routeTree } from './routeTree.gen'; export function getRouter() { const queryClient = createQueryClient(); const trpcClient = makeTRPCClient(); const trpc = createTRPCOptionsProxy({ client: trpcClient, queryClient, }); const router = createRouter({ routeTree, context: { queryClient, trpc }, defaultPreload: 'intent', // Let the query cache decide what's fresh: loaders always run, and fresh data is reused defaultPreloadStaleTime: 0, Wrap: (props) => ( {props.children} ), }); setupRouterSsrQueryIntegration({ router, queryClient }); return router; } ``` Type the root route's context with `createRootRouteWithContext<{ queryClient: QueryClient; trpc: TRPCOptionsProxy }>()`. ## 5. Load handles in loaders A loader lists its queries as entries, loads them with `loadHandles`, and returns the handles as loader data. For each entry, choose whether the loader waits for it. [Loading handles](https://trpc.io/docs/client/tanstack-react-query/handles.md#starting-a-query) compares the options. Every input should come from the route's params or search params: see [Start every query from the URL](#url-as-input). - On the first visit, the loader runs on the server, and the data is sent with the page. - On later navigations, the loader runs in the browser against the tab's cache. Fresh data is reused; stale data renders at once and refetches. ### Without waiting: prefetch entries {#loader-prefetch} The load resolves at once, and the route renders before the data arrives: ```tsx title="src/routes/posts.$id.comments.tsx" import { createFileRoute } from '@tanstack/react-router'; import { loadHandles, prefetchInfiniteEntry } from '@trpc/tanstack-react-query/unstable-handles'; import { Suspense } from 'react'; import { Comments } from '~/components/comments'; export const Route = createFileRoute('/posts/$id/comments')({ loader: async ({ context: { trpc }, params }) => { const [handles] = await loadHandles(trpc, { comments: prefetchInfiniteEntry( trpc.post.comments, { postId: params.id, limit: 20 }, { getNextPageParam: (last) => last.nextCursor }, ), }); return handles; }, component: CommentsPage, }); function CommentsPage() { const loaderData = Route.useLoaderData(); return ( Loading comments…

}>
); } ``` - **Wrap the reader in `Suspense`.** `Comments` suspends until the data arrives. Without your own boundary, the suspension reaches the nearest boundary above it: the route's `pendingComponent`, or a parent route's. That can blank much more of the page than you want. - The load never rejects for these queries. If a request fails, `Comments` throws, and the route's `errorComponent` (or the router's default) shows the error. - **Pass `getNextPageParam` to infinite queries.** The loader runs again on client navigations, and if the cached pages are stale, it refetches every page the user loaded. That [needs `getNextPageParam`](https://trpc.io/docs/client/tanstack-react-query/handles.md#infinite-queries) from page two on. ### Waiting: ensure entries {#loader-ensure} The loader waits, so the route renders with the data in place: ```tsx title="src/routes/posts.$id.tsx" import { createFileRoute, notFound } from '@tanstack/react-router'; import { ensureEntry, isTRPCEntryError, loadHandles, } from '@trpc/tanstack-react-query/unstable-handles'; import { Post } from '~/components/post'; export const Route = createFileRoute('/posts/$id')({ loader: async ({ context: { trpc }, params }) => { const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id: params.id }), }).catch((cause) => { if (isTRPCEntryError(cause, trpc.post.byId) && cause.code === 'NOT_FOUND') { throw notFound(); } throw cause; }); return handles; }, component: PostPage, }); function PostPage() { const loaderData = Route.useLoaderData(); return ; } ``` - The data is in the cache before the route renders, so `Post` shows the post at once. If the cache loses the post later, `Post` suspends and shows the nearest `Suspense` fallback, or the route's `pendingComponent`: see [When the cache loses the data](https://trpc.io/docs/client/tanstack-react-query/handles.md#cache-loses-data). - The navigation waits for the loader. On a slow request, the router shows the route's `pendingComponent`, if it has one. - The loader can act on errors, as here with `notFound()`. - The handle carries no data. To use the data in the loader, for example for the route's `head`, read it from the load's `data`: `const [handles, data] = await loadHandles(trpc, …)`, and return what you need. See [Using the data in a loader](https://trpc.io/docs/client/tanstack-react-query/handles.md#loader-data). To wait for some queries and stream others in the same loader, list them all in one load: see [Waiting for some, streaming others](https://trpc.io/docs/client/tanstack-react-query/handles.md#combining-both). ## 6. Read handles in components Components read handles with `fromHandle` and `useTRPC()`. They're the same components you would write for the [Next.js App Router](https://trpc.io/docs/client/tanstack-react-query/handles.md#nextjs-app-router), minus `'use client'`: ```tsx title="src/components/post.tsx" import { useSuspenseQuery } from '@tanstack/react-query'; import { fromHandle } from '@trpc/tanstack-react-query/unstable-handles'; import type { inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles'; import { useTRPC, type TRPC } from '~/lib/trpc'; export function Post(props: { post: inferQueryHandle }) { const trpc = useTRPC(); const postQuery = useSuspenseQuery(fromHandle(trpc, props.post)); return

{postQuery.data.title}

; } ``` ``` route loader β”œβ”€ prefetchEntry(trpc.post.byId, { id }) β†’ post handle β†’ └─ prefetchInfiniteEntry(trpc.post.comments, …) β†’ comments handle β†’ ``` ## Start every query from the URL {#url-as-input} A loader only sees the URL, so give it everything a page's queries need: path params for what the page is about, and search params for filters, sort and page. With `validateSearch` and `loaderDeps`, the loader starts the right query on every navigation, before the route renders: ```tsx title="src/routes/posts.tsx" import { useSuspenseQuery } from '@tanstack/react-query'; import { createFileRoute } from '@tanstack/react-router'; import { loadHandles, prefetchEntry, fromHandle } from '@trpc/tanstack-react-query/unstable-handles'; import { z } from 'zod'; import { useTRPC } from '../lib/trpc'; export const Route = createFileRoute('/posts')({ validateSearch: z.object({ sort: z.enum(['new', 'top']).default('new'), page: z.number().int().positive().default(1), }), loaderDeps: ({ search }) => search, loader: async ({ context: { trpc }, deps }) => { const [handles] = await loadHandles(trpc, { posts: prefetchEntry(trpc.post.list, deps), }); return handles; }, component: PostsPage, }); function PostsPage() { const trpc = useTRPC(); const loaderData = Route.useLoaderData(); const postsQuery = useSuspenseQuery( fromHandle(trpc, loaderData.posts), ); return (
    {postsQuery.data.map((post) => (
  • {post.title}
  • ))}
); } ``` A link to `/posts?sort=top` starts the query for the top posts as the navigation begins. The back button brings back the last sort, and a shared link opens the same view. Keep the sort in `useState` and you lose all three, since the loader can't see component state. ``` /posts?sort=top&page=2 β†’ prefetchEntry(trpc.post.list, { sort: 'top', page: 2 }) ``` If a query can't take its input from the URL, for example because it needs an id from another query's result, reshape the procedure: see [If the URL isn't enough, reshape the procedure](https://trpc.io/docs/client/tanstack-react-query/handles.md#reshape-procedures). ## Handles in `beforeLoad` {#before-load} `beforeLoad` can return handles too, for example to start a query in a parent route and read it in child routes. TanStack Router checks that values returned from `beforeLoad` are serializable, and handles pass that check as they are: their query keys and inputs are typed from the procedure.
Escape hatch: loading a dependent query before render (TanStack Router) `beforeLoad` runs before the loader, so it can wait for the post and hand its data to the loader through the route context. The loader then starts more by the post's author from `post.authorId`: ```tsx title="src/routes/posts.$id.tsx" import { createFileRoute } from '@tanstack/react-router'; import { ensureInfiniteEntry, fetchEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; import { Comments } from '~/components/comments'; import { MoreByAuthor } from '~/components/more-by-author'; import { Post } from '~/components/post'; export const Route = createFileRoute('/posts/$id')({ beforeLoad: async ({ context: { trpc }, params }) => { const [handles, data] = await loadHandles(trpc, { // Fresh, since the loader builds another query's input from it post: fetchEntry(trpc.post.byId, { id: params.id }), comments: prefetchInfiniteEntry( trpc.post.comments, { postId: params.id }, { getNextPageParam: (last) => last.nextCursor }, ), }); return { postHandles: handles, post: data.post }; }, loader: async ({ context: { trpc, postHandles, post } }) => { // Starts only after beforeLoad has the post const [handles] = await loadHandles(trpc, { moreByAuthor: ensureInfiniteEntry( trpc.post.byAuthor, { authorId: post.authorId }, { getNextPageParam: (last) => last.nextCursor }, ), }); return { ...postHandles, ...handles }; }, component: PostPage, }); function PostPage() { const loaderData = Route.useLoaderData(); return ( <> ); } ``` This serialises the loads: more by the author can't start until the post has arrived. Prefer one `loadHandles` that starts both from the URL, or [read the dependent query in the component](https://trpc.io/docs/client/tanstack-react-query/handles.md#waterfall-in-a-component), which fetches it in render instead. Reach for `beforeLoad` only when the dependent data must be in the cache before the page renders.
## Don't return handles from server functions {#server-functions} A server function runs with its own `QueryClient`, which never reaches the page. Return data from server functions, and load handles in loaders. In development, tRPC warns when it renders a handle whose data never reached the page's `QueryClient`. --- Source: https://trpc.io/docs/client/tanstack-react-query/handles # Prefetching with handles > Handles help you avoid request waterfalls. The loader, or server component, **reads the URL once**, starts every query the page needs, and passes each component a reference to its query as a prop. - A **handle** is a query's key and input. It holds no data. - The component reads the query from it, fully typed, without naming the procedure or repeating its input. - The client reads exactly the query the server started. With plain `queryOptions`, an input that differs by a typo misses the prefetch and fetches again, silently. > [!NOTE] Info > The handle APIs are plain functions from `@trpc/tanstack-react-query/unstable-handles`. The `unstable-` in the path means they're new and may change, but you're safe to use them! [Read more](https://trpc.io/docs/faq.md#unstable). ## In short {#gist} Load the handles where the page starts, and read each one in a component, which never names the procedure or repeats its input:
```tsx title="src/routes/posts.$id.tsx" import { useSuspenseQuery } from '@tanstack/react-query'; import { createFileRoute } from '@tanstack/react-router'; import { ensureEntry, fromHandle, loadHandles, } from '@trpc/tanstack-react-query/unstable-handles'; import { useTRPC } from '~/lib/trpc'; export const Route = createFileRoute('/posts/$id')({ loader: async ({ context: { trpc }, params }) => { const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id: params.id }), }); return handles; }, component: PostPage, }); function PostPage() { const handles = Route.useLoaderData(); const trpc = useTRPC(); const postQuery = useSuspenseQuery(fromHandle(trpc, handles.post)); return

{postQuery.data.title}

; } ```
The page, a server component, loads the handles: ```tsx title="app/posts/[id]/page.tsx" import { ensureEntry, loadHandles } from '@trpc/tanstack-react-query/unstable-handles'; import { HydrateClient, trpc } from '~/trpc/server'; import { Post } from './post'; export default async function PostPage(props: { params: Promise<{ id: string }> }) { const { id } = await props.params; const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }), }); return ( ); } ``` A client component, in its own file, reads one: ```tsx title="app/posts/[id]/post.tsx" 'use client'; import { useSuspenseQuery } from '@tanstack/react-query'; import { fromHandle, type inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles'; import { useTRPC, type TRPC } from '~/trpc/client'; export function Post(props: { post: inferQueryHandle }) { const trpc = useTRPC(); const postQuery = useSuspenseQuery(fromHandle(trpc, props.post)); return

{postQuery.data.title}

; } ```
- The handle carries the procedure and its input, typed. - The data reaches the browser's cache through TanStack Query's dehydrate and hydrate: see [Frameworks](#frameworks). - Mutations don't change. To refetch a handle's query after one, invalidate `{ queryKey: handle.queryKey, exact: true }`. ## Loading handles {#starting-a-query} `loadHandles(trpc, entries)` starts every entry, then resolves to `[handles, data]`: ```ts import { ensureEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; const [handles, data] = await loadHandles(trpc, { // Waits for the post, unless the cache has it post: ensureEntry(trpc.post.byId, { id }), // Doesn't wait comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }), }); handles.post; // (property) post: TRPCQueryHandle<{ // input: { // id: string; // }; // output: Post; // transformer: false; // errorShape: DefaultErrorShape; // featureFlags: { // keyPrefix: false; // }; // }> data.post; // (property) post: Post // The comments may have no data yet, so they aren't on `data` data.comments; ``` - Building an entry starts nothing. The load starts every entry before it waits for any, so their order doesn't matter. - `handles` has a handle for each entry. Return it from the loader, or pass it on as props. - In a client component, don't call `loadHandles` during render: each render would start the entries again. Server components can. A client component that renders before anything loaded its query reads it with `useSuspenseQuery(trpc.x.queryOptions(input))`. #### Using the data in a loader {#loader-data} `data` has the data of the entries the load waited for. Use it for the page title, a redirect or a not-found check. Return `handles`, not `data`, so the data doesn't cross to the browser twice. #### Waiting for some, streaming others {#combining-both} List every query in one load, whether the page waits for it or not. They all start together. A second load waits for everything the first one waited for, so use one only for [dependent queries](#dependent-queries). Each entry chooses whether the page waits for its query: | | `prefetchEntry` | `ensureEntry` | `fetchEntry` | | ---------------------- | --------------------------------- | --------------------------------------------- | --------------------- | | Page waits for data | No | Yes | Yes | | In `data` | No | Yes | Yes | | With stale data | Refetches in the background | Resolves at once, refetches in the background | Waits for the refetch | | Reader's first render | Loading state, or cached data | The data | The data | | When the request fails | The reader gets the error | The load rejects, unless it had cached data | The load rejects | Load handles where the code can wait: | Your app | Where | Proxy | | ------------------------------ | -------------------------- | --------------------------------------- | | TanStack Start, TanStack Router | Route loaders | The proxy in your router context | | Next.js App Router | Server components | The server proxy from `trpc/server.tsx` | | A SPA without loaders | Event handlers, such as a link's hover | `useTRPC()` | #### Conditional queries {#conditional-queries} Put TanStack Query's `skipToken` in place of an entry to start nothing for it. Here, a post page loads its comments only when the URL opens the comments tab, `/posts/1?tab=comments`: ```tsx import { skipToken } from '@tanstack/react-query'; import { ensureEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; import { z } from 'zod'; export const postRoute = createRoute({ getParentRoute: () => rootRoute, path: '/posts/$id', validateSearch: z.object({ tab: z.enum(['post', 'comments']).default('post'), }), loaderDeps: ({ search }) => ({ tab: search.tab }), loader: async ({ context: { trpc }, params: { id }, deps }) => { const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }), comments: deps.tab === 'comments' ? prefetchInfiniteEntry(trpc.post.comments, { postId: id }) : skipToken, }); handles.comments; // (property) comments: TRPCInfiniteQueryHandle<{ // input: { // postId: string; // limit?: number | undefined; // cursor?: number | null | undefined; // }; // output: { // items: { // id: string; // text: string; // }[]; // nextCursor: number | null; // }; // transformer: false; // errorShape: DefaultErrorShape; // featureFlags: { // keyPrefix: false; // }; // }> | undefined return handles; }, }); ``` - Its handle is `undefined`, so render the reader only when there's a handle: `{handles.comments && }`. - It has no key in `handles`, `data` or `loadHandlesSettled`'s results, so the handles still serialize as Next.js props. - Take the condition from what the loader knows: the URL, as here, the session, or another load's data. See [Start every query from the URL](#url-as-input) and [Dependent queries](#dependent-queries). #### TanStack Query equivalents {#tanstack-equivalents} Each entry is one TanStack Query call: | tRPC | TanStack Query | | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `prefetchEntry(trpc.x, input, opts)` | `void queryClient.prefetchQuery(trpc.x.queryOptions(input, opts))` | | `ensureEntry(trpc.x, input, opts)` | `await queryClient.ensureQueryData({ ...trpc.x.queryOptions(input, opts), revalidateIfStale: true })` | | `fetchEntry(trpc.x, input, opts)` | `await queryClient.fetchQuery(trpc.x.queryOptions(input, opts))` | | `prefetchInfiniteEntry`, `ensureInfiniteEntry`, `fetchInfiniteEntry` | `prefetchInfiniteQuery`, `ensureInfiniteQueryData` (with `revalidateIfStale: true`), `fetchInfiniteQuery` | | `fromHandle(trpc, handle, opts)` | `trpc.x.queryOptions(handle.input, opts)`, with `x` taken from the handle | The `queryClient` is the one the proxy was created with. The entry names follow the TanStack Query method each one calls. Options: - `input` is optional when the procedure's is: `prefetchEntry(trpc.viewer)`. - `opts` takes `staleTime`, `gcTime`, `retry`, `retryDelay`, `meta` and `trpc` request options. They apply to the load's request; readers use the options passed to `fromHandle`. ### `prefetchEntry`: don't wait {#prefetch} - The page renders at once, and the data streams in. - The reader shows cached data, or suspends. Give it its own ``, or the nearest boundary above shows its fallback, which may be the whole page. - It never makes the load reject. The reader gets the error: see [Errors](#errors). - Use it for slow queries, content below the fold and side panels. ### `ensureEntry`: wait {#ensure} - The load waits until the cache has data, so the reader renders it at once. - With cached data, even stale, it resolves at once and refetches in the background. - It rejects only if the cache had no data and the request fails. - Use it for data the page can't render without, or needs before rendering. ### `fetchEntry`: wait for fresh data {#fetch} - Like `ensureEntry`, but with stale data it waits for the refetch. - Use it when the loader reads the data and needs it fresh, such as for a redirect. - In a browser loader, prefer `ensureEntry`: a fetch entry holds up the navigation until the refetch is done. - TanStack Router shows a visited page with its last loader data while the loader reruns. To wait, set `defaultStaleReloadMode`, or a loader's [`staleReloadMode`](https://tanstack.com/router/latest/docs/guide/data-loading#choosing-background-vs-blocking-stale-reloads), to `'blocking'`. - In server components, ensure and fetch behave the same: the request's `QueryClient` starts empty. ## Start every query from the URL {#url-as-input} A loader runs before anything renders, and all it has is the URL: params, search params and, on the server, the session. If every input comes from those, every request starts with the navigation. - **Path params** name the thing: `/posts/$slug`. - **Search params** hold filters, sort and page. Keep them out of component state: a loader can't see it, the back button doesn't restore it, and a shared link loses it. ``` /posts?sort=top&page=2 β†’ prefetchEntry(trpc.post.list, { sort: 'top', page: 2 }) ``` With handles, they all start together. Without, each starts once the component above it renders: ``` With handles Without |-> post.byId |-> post.byId |-> post.comments |-> post.comments |-> post.byAuthor |-> post.byAuthor ``` ### If the URL isn't enough, reshape the procedure {#reshape-procedures} A procedure that takes an id from another query forces a waterfall on every page that calls it. Fix the procedure, not the page: - **Take what the URL has.** Accept the slug and look up the id on the server. - **Return the joined data.** Return the post with its author, not an author id. The server sits next to the database, so the lookup costs a query there, not a round trip from the browser. **Before:** the comments and the author need ids that only the post has. ```ts title="The loader for /posts/$slug" async function loader(params: { slug: string }) { const [first, { post }] = await loadHandles(trpc, { post: ensureEntry(trpc.post.bySlug, { slug: params.slug }), }); // Nothing below can start until the post has arrived const [second] = await loadHandles(trpc, { comments: prefetchInfiniteEntry(trpc.post.comments, { postId: post.id, }), author: prefetchEntry(trpc.author.byId, { id: post.authorId }), }); return { ...first, ...second }; } ``` ``` post.bySlug |-------| post.comments |-------| author.byId |-------| ``` **After:** `post.comments` takes the slug, and `post.bySlug` returns the author: ```ts title="server/routers/_app.ts" import { z } from 'zod'; import { db } from './db'; import { t } from './trpc'; export const appRouter = t.router({ post: t.router({ bySlug: t.procedure .input(z.object({ slug: z.string() })) .query(async ({ input }) => { const post = await db.post.bySlug(input.slug); return { ...post, author: await db.author.byId(post.authorId) }; }), comments: t.procedure .input( z.object({ slug: z.string(), cursor: z.number().nullish() }), ) .query(async ({ input }) => { const post = await db.post.bySlug(input.slug); return db.comment.list({ postId: post.id, cursor: input.cursor ?? null, }); }), }), }); ``` ```ts title="The loader for /posts/$slug" async function loader(params: { slug: string }) { // Both start from the URL, together const [handles] = await loadHandles(trpc, { comments: prefetchInfiniteEntry(trpc.post.comments, { slug: params.slug, }), post: ensureEntry(trpc.post.bySlug, { slug: params.slug }), }); return handles; } ``` ``` post.bySlug |-------| post.comments |-------| ``` ## Reading a handle {#reading-a-handle} `fromHandle(trpc, handle, opts?)` returns `trpc..queryOptions(handle.input, opts)`, or `infiniteQueryOptions` for an infinite handle. Pass it to any TanStack Query hook: ```tsx const trpc = useTRPC(); const postQuery = useSuspenseQuery(fromHandle(trpc, props.post)); const titleQuery = useQuery(fromHandle(trpc, props.post, { select: (post) => post.title })); const [aQuery, bQuery] = useSuspenseQueries({ queries: [fromHandle(trpc, props.a), fromHandle(trpc, props.b)], }); ``` - Only `loadHandles` makes handles. A hand-written object doesn't type-check, and `fromHandle` throws on it. - `handle.input` is the typed input. An infinite handle's leaves out `cursor` and `direction`. - Reads share cache entries with `trpc..queryOptions(input)`. - `handle.queryKey` carries no data type, so the handle stays serializable. For a typed key, use `fromHandle(trpc, handle).queryKey` or `trpc.post.byId.queryKey(handle.input)`. #### Typing props {#typing-props} Type props with `inferQueryHandle`, or `inferInfiniteQueryHandle` for an infinite handle. Export `type TRPC = TRPCOptionsProxy` from `trpc/client.tsx` once. #### Reading with `useQuery` {#use-query} With `useQuery`, no `Suspense` boundary is needed: - It renders `status: 'pending'` until the data arrives, and `'success'` at once after an ensure or fetch entry. - With server rendering, read a prefetch entry's handle with `useSuspenseQuery`. Otherwise the server can render the loading state while the browser has the data, a hydration mismatch ([TanStack/query#9399](https://github.com/TanStack/query/issues/9399)). To change the input in the component, for a search term the URL can't hold, call the procedure and start from the handle's input: ```tsx const [term, setTerm] = useState(props.comments.input.term); const commentsQuery = useSuspenseInfiniteQuery( trpc.post.comments.infiniteQueryOptions( { ...props.comments.input, term: useDeferredValue(term) }, { getNextPageParam: (last) => last.nextCursor }, ), ); ``` - While the input matches the handle's, it reads the loader's cache entry. - Render ``, so a new post resets the term. - For sort and filters, use a [search param](#url-as-input) instead. ## When the cache loses the data {#cache-loses-data} A handle carries no data, and the cache can lose it even after an ensure entry: - `resetQueries()` clears it and refetches at once. - `removeQueries()` and `clear()`, such as on logout, drop it. The reader loads it again when it next renders. - After `gcTime` unused, TanStack Query drops it. - `invalidateQueries()` keeps it and refetches in the background, so nothing shows a loading state. So give every reader a loading state: a `Suspense` boundary, or a `'pending'` case. ## Infinite queries {#infinite-queries} For procedures with a `cursor` input, use `prefetchInfiniteEntry`, `ensureInfiniteEntry` and `fetchInfiniteEntry`. They load one page, or more with `pages`: ```ts const [handles, data] = await loadHandles(trpc, { comments: ensureInfiniteEntry( trpc.post.comments, { postId: id, limit: 20 }, { pages: 3, getNextPageParam: (last) => last.nextCursor }, ), }); data.comments.pages; // (property) InfiniteData<{ items: { id: string; text: string; }[]; nextCursor: number | null; }, number | null>.pages: { // items: { // id: string; // text: string; // }[]; // nextCursor: number | null; // }[] ``` - `pages` is how many pages the load fetches, also when it refetches stale pages: the cache then keeps only that many. To refetch every page the reader loaded, leave it out. - Functions can't cross to the client, so pass `getNextPageParam` again when you read: ```ts fromHandle(trpc, props.comments, { getNextPageParam: (last) => last.nextCursor }) ``` - Also pass it to entries in loaders that run in the browser. Refetching stale pages needs it from page two on. - Type props with `inferInfiniteQueryHandle`. ## Dependent queries {#dependent-queries} A query whose input comes from another query's result is a waterfall. Each step costs a round trip. First try to [reshape the procedure](#reshape-procedures). If you can't, there are two ways, and both pay the round trip. #### In a loader {#waterfall-in-a-loader} Load the first query, then build the second load from its `data`: ```ts const [first, { post }] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }), comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }), }); const [second] = await loadHandles(trpc, { moreByAuthor: prefetchInfiniteEntry(trpc.post.byAuthor, { authorId: post.authorId, }), }); const handles = { ...first, ...second }; ``` #### In a component {#waterfall-in-a-component} Read it in the component that gets the input: ```tsx const postsQuery = useSuspenseInfiniteQuery( trpc.post.byAuthor.infiniteQueryOptions( { authorId }, { getNextPageParam: (last) => last.nextCursor }, ), ); ``` - In TanStack Router, `beforeLoad` can wait for the first query before the loader runs: see [TanStack Start](https://trpc.io/docs/client/tanstack-react-query/tanstack-start.md#before-load). ## Frameworks {#frameworks} Each framework loads the handles where the page starts and passes them to the components that read them. Set tRPC up with the framework's guide first.
#### On a page {#tanstack-start} After the [TanStack Start setup](https://trpc.io/docs/client/tanstack-react-query/tanstack-start.md), the route's loader loads the handles and its component passes them on: ```tsx title="src/routes/posts.$id.tsx" import { createFileRoute } from '@tanstack/react-router'; import { ensureEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; import { Suspense } from 'react'; import { Comments } from '~/components/comments'; import { Post } from '~/components/post'; export const Route = createFileRoute('/posts/$id')({ loader: async ({ context: { trpc }, params }) => { const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id: params.id }), comments: prefetchInfiniteEntry(trpc.post.comments, { postId: params.id }), }); return handles; }, component: PostPage, }); function PostPage() { const handles = Route.useLoaderData(); return ( <> Loading comments…

}>
); } ```
#### On a page {#nextjs-app-router} After the [Next.js App Router setup](https://trpc.io/docs/client/nextjs/app-router-setup.md), export `HydrateClient = unstable_createHydrateClient(getQueryClient)` from `trpc/server.tsx`. The page, a server component, loads the handles and passes them to client components: ```tsx title="app/posts/[id]/page.tsx" import { ensureEntry, loadHandles, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; import { Suspense } from 'react'; import { HydrateClient, trpc } from '~/trpc/server'; import { Comments } from './comments'; import { Post } from './post'; export default async function PostPage(props: { params: Promise<{ id: string }> }) { const { id } = await props.params; const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }), comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }), }); return ( Loading comments…

}>
); } ``` ```tsx title="app/posts/[id]/post.tsx" 'use client'; import { useSuspenseQuery } from '@tanstack/react-query'; import { fromHandle, type inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles'; import { useTRPC, type TRPC } from '~/trpc/client'; export function Post(props: { post: inferQueryHandle }) { const trpc = useTRPC(); const postQuery = useSuspenseQuery(fromHandle(trpc, props.post)); return

{postQuery.data.title}

; } ``` #### `HydrateClient` {#hydrate-client} - It sends the request's queries to the browser, pending ones too, which stream in as they settle. - It sends each query once per request, so a nested server component can load more handles and render its own. A query is sent again only when the server has newer data. - It works only in server components, and for `queryClient.prefetchQuery` too. - Handle inputs cross through React's serialization, not your transformer. Keep them to JSON values and `Date`s. - For a 404, use an ensure entry and call `notFound()`: see [Errors](#errors). #### Metadata, static and ISR pages {#nextjs-static} - `generateMetadata` gets the page's query client. Fetch there, and the page's ensure entry reuses the data. - A page whose tRPC context reads `headers()` renders on every request. `loadHandles` lets Next.js see that, so the build marks the page dynamic. - To prerender the page and revalidate it, load it with a proxy whose context reads no request data, `trpcStatic` from [Static and ISR pages](https://trpc.io/docs/client/nextjs/static-pages.md#static-pages): ```tsx title="app/posts/[id]/page.tsx" import { ensureEntry, loadHandles } from '@trpc/tanstack-react-query/unstable-handles'; import { getQueryClient, HydrateClient, trpcStatic } from '~/trpc/server'; import { Post } from './post'; type Props = { params: Promise<{ id: string }> }; export const revalidate = 60; export function generateStaticParams() { return [{ id: '1' }]; } export async function generateMetadata(props: Props) { const { id } = await props.params; const post = await getQueryClient().fetchQuery( trpcStatic.post.byId.queryOptions({ id }), ); return { title: post.title }; } export default async function PostPage(props: Props) { const { id } = await props.params; const [handles] = await loadHandles(trpcStatic, { post: ensureEntry(trpcStatic.post.byId, { id }), }); return ( ); } ```
## Errors {#errors} #### With ensure and fetch entries {#errors-ensure} When an entry the load waits for fails, `loadHandles` rejects with a `TRPCEntryError`. `isTRPCEntryError(error, trpc.post.byId)` checks which procedure failed and types `error.cause`: ```ts import { ensureEntry, ensureInfiniteEntry, isTRPCEntryError, loadHandles, } from '@trpc/tanstack-react-query/unstable-handles'; async function loader(id: string) { const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }), comments: ensureInfiniteEntry(trpc.post.comments, { postId: id }), }).catch((error: unknown) => { if (isTRPCEntryError(error, trpc.post.byId) && error.code === 'NOT_FOUND') { notFound(); } if (isTRPCEntryError(error, trpc.post.comments)) { reportError(error.cause); // (parameter) error: TRPCEntryError<{ // input: { // postId: string; // limit?: number | undefined; // cursor?: number | null | undefined; // }; // output: { // items: { // id: string; // text: string; // }[]; // nextCursor: number | null; // }; // transformer: false; // errorShape: DefaultErrorShape; // featureFlags: { // keyPrefix: false; // }; // }> } throw error; }); return handles; } ``` - `error.key` is the entry's key, `error.path` the procedure, `error.code` the tRPC code. - The load rejects on the first failure, without waiting for the others. - An error with a `digest`, such as the one Next.js's `headers()` throws in a static render, is rethrown as it is, also by `loadHandlesSettled`, so Next.js still sees it. A procedure's errors arrive as a `TRPCError`, as with `fetchQuery`. #### Errors as values {#errors-as-values} `loadHandlesSettled` never rejects for a failed entry. It returns each waited-for entry's result as a value: ```ts import { ensureEntry, loadHandlesSettled, prefetchInfiniteEntry, } from '@trpc/tanstack-react-query/unstable-handles'; const [handles, results] = await loadHandlesSettled(trpc, { post: ensureEntry(trpc.post.byId, { id }), comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }), }); if (results.post.status === 'error') { if (results.post.error.code === 'NOT_FOUND') { notFound(); } throw results.post.error; } results.post.data.title; // (property) data: Post ``` #### With prefetch entries {#errors-prefetch} A prefetch entry never makes the load reject. The reader gets the query's own error: `useQuery` returns `status: 'error'`, and `useSuspenseQuery` throws to the nearest error boundary, unless the cache has data to keep showing. To report these in one place, use your `QueryCache`'s [`onError`](https://tanstack.com/query/latest/docs/reference/QueryCache). ## Invalidation {#invalidation-and-staleness} Handles use normal tRPC query keys. Pass any of these to `invalidateQueries`: - `{ queryKey: handle.queryKey, exact: true }`: the handle's own query. Without `exact`, it also matches inputs that extend the handle's. - `trpc.post.pathFilter()`: every query under `post`. - `trpc.post.byId.queryFilter(input)`, or `infiniteQueryFilter` for an infinite handle. To update data in place, use `queryClient.setQueryData(trpc.post.byId.queryKey(handle.input), …)`. Hydrated data keeps the server's fetch time. Set a `staleTime` above 0, as the setup guides do, or the client refetches right after hydration. ## Testing {#testing} Load handles over a test `QueryClient`, seeded with fixture data: ```tsx title="post.test.tsx" import { QueryClient } from '@tanstack/react-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import { loadHandles, prefetchEntry } from '@trpc/tanstack-react-query/unstable-handles'; import { appRouter } from './router'; const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } }, }); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient }); queryClient.setQueryData(trpc.post.byId.queryKey({ id: '1' }), { id: '1', title: 'Hello', }); const [{ post }] = await loadHandles(trpc, { post: prefetchEntry(trpc.post.byId, { id: '1' }), }); ``` - Render the component under `QueryClientProvider` and `TRPCProvider` with the same `queryClient`. - Leave out `setQueryData` to run the real procedure. ## FAQ {#faq} #### Are handles safe to send to the browser? {#handles-safe} Yes. A handle names a query the browser could call anyway, and every refetch runs validation and auth on the server again. A handle does carry its input to the browser, as hydrated query keys already do. Only use inputs you'd show the client. #### Where don't handles work? {#where-handles-dont-work} - **Server functions and server actions:** their `QueryClient` never hydrates the page, so return data instead. - **Outside hydration:** a reader rendered on the server outside `HydrateClient` or `HydrationBoundary` fetches its query again. In development, tRPC warns once per query. - **URLs and storage:** a handle there gains nothing over its input. #### Why functions, not methods on `trpc`? {#why-functions} Methods on `trpc` return plain TanStack Query options. Handles are helpers on top, and apps that don't use them don't load their code. #### Why one load call, not one per query? {#why-one-load} So a loader can't make a waterfall by the order of its lines. --- Source: https://trpc.io/docs/client/react # React Query Integration (Classic, deprecated) > The classic React Query integration, which only gets bug fixes and will be removed in the next major version of tRPC > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). tRPC offers a first class integration with React. Under the hood this is simply a wrapper around the very popular [@tanstack/react-query](https://tanstack.com/query/latest), so we recommend that you familiarize yourself with React Query, as their docs go into much greater depth on its usage. If you are using Next.js we recommend using [our integration with that](https://trpc.io/docs/client/nextjs.md) instead.
❓ Do I have to use an integration? No! The integration is fully optional. You can use `@tanstack/react-query` using just a [vanilla tRPC client](https://trpc.io/docs/client/vanilla.md), although then you'll have to manually manage query keys and do not get the same level of DX as when using the integration package. ```ts title="utils/trpc.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppRouter } from '../server'; export const trpc = createTRPCClient({ links: [httpBatchLink({ url: 'YOUR_API_URL' })], }); ``` ```tsx title="components/PostList.tsx" import { useQuery } from '@tanstack/react-query'; import { trpc } from '../utils/trpc'; function PostList() { const { data } = useQuery({ queryKey: ['posts'], queryFn: () => trpc.post.list.query(), }); data; // Post[] // ... } ```
### The tRPC React Query Integration This library enables usage directly within React components. ```tsx title="pages/IndexPage.tsx" import { trpc } from '../utils/trpc'; export default function IndexPage() { const helloQuery = trpc.hello.useQuery({ name: 'Bob' }); const goodbyeMutation = trpc.goodbye.useMutation(); return (

{helloQuery.data?.greeting}

); } ``` ### Differences to vanilla React Query The wrapper abstracts some aspects of React Query for you: - Query Keys - these are generated and managed by tRPC on your behalf, based on the procedure inputs you provide - If you need the query key which tRPC calculates, you can use [getQueryKey](https://trpc.io/docs/client/react/getQueryKey.md) - Type safe by default - the types you provide in your tRPC Backend also drive the types of your React Query client, providing safety throughout your React app --- Source: https://trpc.io/docs/client/react/setup # Set up the React Query Integration > How to use and setup tRPC in React > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query/setup.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). ### 1. Install dependencies The following dependencies should be installed. ```package-install @trpc/server @trpc/client @trpc/react-query @tanstack/react-query ``` ### 2. Import your `AppRouter` Import your `AppRouter` type into the client application. This type holds the shape of your entire API. ```ts title="utils/trpc.ts" import type { AppRouter } from '../server/router'; ``` > [!TIP] > By using `import type` you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, [see the Typescript docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export). ### 3. Create tRPC hooks Create a set of strongly-typed React hooks from your `AppRouter` type signature with `createTRPCReact`. ```ts title="utils/trpc.ts" import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from '../server/router'; export const trpc = createTRPCReact(); ``` ### 4. Add tRPC providers Create a tRPC client, and wrap your application in the tRPC Provider, as below. You will also need to set up and connect React Query, which [they document in more depth](https://tanstack.com/query/latest/docs/framework/react/quick-start). > [!TIP] > If you already use React Query in your application, you **should** re-use the `QueryClient` and `QueryClientProvider` you already have. ```tsx title="App.tsx" import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { httpBatchLink } from '@trpc/client'; import React, { useState } from 'react'; import { trpc } from './utils/trpc'; export function App() { const [queryClient] = useState(() => new QueryClient()); const [trpcClient] = useState(() => trpc.createClient({ links: [ httpBatchLink({ url: 'http://localhost:3000/trpc', // You can pass any HTTP headers you wish here async headers() { return { authorization: getAuthCookie(), }; }, }), ], }), ); return ( {/* Your app here */} ); } ``` > [!NOTE] > The reason for using `useState` in the creation of the `queryClient` and the `TRPCClient`, as opposed to declaring them outside of the component, is to ensure that each request gets a unique client when using SSR. If you use client side rendering then you can move them if you wish. ### 5. Fetch data You can now use the tRPC React Query integration to call queries and mutations on your API. ```tsx title="pages/IndexPage.tsx" import { trpc } from '../utils/trpc'; export default function IndexPage() { const userQuery = trpc.getUser.useQuery({ id: 'id_bilbo' }); const userCreator = trpc.createUser.useMutation(); return (

{userQuery.data?.name}

); } ``` --- Source: https://trpc.io/docs/client/react/server-components # Set up with React Server Components > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query/server-components.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). > [!TIP] > **Using Next.js?** See the dedicated [Next.js App Router setup guide](https://trpc.io/docs/client/nextjs/app-router-setup.md) for the recommended approach. This guide is an overview of how one may use tRPC with a React Server Components (RSC) framework such as Next.js App Router. Be aware that RSC on its own solves a lot of the same problems tRPC was designed to solve, so you may not need tRPC at all. There is also not a one-size-fits-all way to integrate tRPC with RSCs, so see this guide as a starting point and adjust it to your needs and preferences. > [!NOTE] Info > If you're looking for how to use tRPC with Server Actions, see the [Server Actions guide](https://trpc.io/docs/client/nextjs/server-actions.md). > [!WARNING] Caution > Please read React Query's [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) docs before proceeding to understand the different types of server rendering > and what footguns to avoid. ## Add tRPC to existing projects ### 1. Install deps ```package-install @trpc/server @trpc/client @trpc/react-query @tanstack/react-query@latest zod client-only server-only ``` ### 2. Create a tRPC router Initialize your tRPC backend in `trpc/init.ts` using the `initTRPC` function, and create your first router. We're going to make a simple "hello world" router and procedure here - but for deeper information on creating your tRPC API you should refer to the [Quickstart guide](https://trpc.io/docs/quickstart.md) and [Backend usage docs](https://trpc.io/docs/server/overview.md) for tRPC information. > [!NOTE] Info > The file names used here are not enforced by tRPC. You may use any file structure you wish.
View sample backend ```ts title="trpc/init.ts" import { initTRPC } from '@trpc/server'; import { cache } from 'react'; export const createTRPCContext = cache(async () => { /** * @see: https://trpc.io/docs/server/context */ return { userId: 'user_123' }; }); // Avoid exporting the entire t-object // since it's not very descriptive. // For instance, the use of a t variable // is common in i18n libraries. const t = initTRPC.create({ /** * @see https://trpc.io/docs/server/data-transformers */ // transformer: superjson, }); // Base router and procedure helpers export const createTRPCRouter = t.router; export const createCallerFactory = t.createCallerFactory; export const baseProcedure = t.procedure; ```
```ts title="trpc/routers/_app.ts" import { z } from 'zod'; import { baseProcedure, createTRPCRouter } from '../init'; export const appRouter = createTRPCRouter({ hello: baseProcedure .input( z.object({ text: z.string(), }), ) .query((opts) => { return { greeting: `hello ${opts.input.text}`, }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ```
> [!NOTE] > The backend adapter depends on your framework and how it sets up API routes. The following example sets up GET and POST routes at `/api/trpc/*` using the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) in Next.js. ```ts title="app/api/trpc/[trpc]/route.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createTRPCContext } from '../../../../trpc/init'; import { appRouter } from '../../../../trpc/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: createTRPCContext, }); export { handler as GET, handler as POST }; ```
### 3. Create a Query Client factory Create a shared file `trpc/query-client.ts` that exports a function that creates a `QueryClient` instance. ```ts title="trpc/query-client.ts" import { defaultShouldDehydrateQuery, QueryClient, } from '@tanstack/react-query'; import superjson from 'superjson'; export function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { staleTime: 30 * 1000, }, dehydrate: { // serializeData: superjson.serialize, shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', }, hydrate: { // deserializeData: superjson.deserialize, }, }, }); } ``` We're setting a few default options here: - `staleTime`: With SSR, we usually want to set some default staleTime above 0 to avoid refetching immediately on the client. - `shouldDehydrateQuery`: This is a function that determines whether a query should be dehydrated or not. Since the RSC transport protocol supports hydrating promises over the network, we extend the `defaultShouldDehydrateQuery` function to also include queries that are still pending. This will allow us to start prefetching in a server component high up the tree, then consuming that promise in a client component further down. - `serializeData` and `deserializeData` (optional): If you set up a [data transformer](https://trpc.io/docs/server/data-transformers.md) in the previous step, set this option to make sure the data is serialized correctly when hydrating the query client over the server-client boundary. ### 4. Create a tRPC client for Client Components The `trpc/client.tsx` is the entrypoint when consuming your tRPC API from client components. In here, import the **type definition** of your tRPC router and create typesafe hooks using `createTRPCReact`. We'll also export our context provider from this file. ```tsx title="trpc/client.tsx" 'use client'; // ^-- to make sure we can mount the Provider from a server component import type { QueryClient } from '@tanstack/react-query'; import { QueryClientProvider } from '@tanstack/react-query'; import { httpBatchLink } from '@trpc/client'; import { createTRPCReact } from '@trpc/react-query'; import React, { useState } from 'react'; import { makeQueryClient } from './query-client'; import type { AppRouter } from './routers/_app'; export const trpc = createTRPCReact(); let clientQueryClientSingleton: QueryClient; function getQueryClient() { if (typeof window === 'undefined') { // Server: always make a new query client return makeQueryClient(); } // Browser: use singleton pattern to keep the same query client return (clientQueryClientSingleton ??= makeQueryClient()); } function getUrl() { const base = (() => { if (typeof window !== 'undefined') return ''; if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; return 'http://localhost:3000'; })(); return `${base}/api/trpc`; } export function TRPCProvider( props: Readonly<{ children: React.ReactNode; }>, ) { // NOTE: Avoid useState when initializing the query client if you don't // have a suspense boundary between this and the code that may // suspend because React will throw away the client on the initial // render if it suspends and there is no boundary const queryClient = getQueryClient(); const [trpcClient] = useState(() => trpc.createClient({ links: [ httpBatchLink({ // transformer: superjson, <-- if you use a data transformer url: getUrl(), }), ], }), ); return ( {props.children} ); } ``` Mount the provider in the root of your application (e.g. `app/layout.tsx` when using Next.js). ### 5. Create a tRPC caller for Server Components To prefetch queries from server components, we use a tRPC caller. The `@trpc/react-query/rsc` module exports a thin wrapper around [`createCaller`](https://trpc.io/docs/server/server-side-calls.md) that integrates with your React Query client. ```tsx title="trpc/server.tsx" import 'server-only'; // <-- ensure this file cannot be imported from the client import { createHydrationHelpers } from '@trpc/react-query/rsc'; import { cache } from 'react'; import { createCallerFactory, createTRPCContext } from './init'; import { makeQueryClient } from './query-client'; import { appRouter } from './routers/_app'; // IMPORTANT: Create a stable getter for the query client that // will return the same client during the same request. export const getQueryClient = cache(makeQueryClient); const caller = createCallerFactory(appRouter)(createTRPCContext); export const { trpc, HydrateClient } = createHydrationHelpers( caller, getQueryClient, ); ``` ## Using your API Now you can use your tRPC API in your app. While you can use the React Query hooks in client components just like you would in any other React app, we can take advantage of the RSC capabilities by prefetching queries in a server component high up the tree. You may be familiar with this concept as "render as you fetch" commonly implemented as loaders. This means the request fires as soon as possible but without suspending until the data is needed by using the `useSuspenseQuery` hook. Read a prefetch you don't `await` with `useSuspenseQuery` ([Leveraging Suspense](#leveraging-suspense)): with `useQuery`, the server can render the loading state while the browser already has the data, and React reports a hydration mismatch. For a component on `useQuery`, like the one below, `await` the `prefetch` call instead. ```tsx title="app/page.tsx" import { trpc, HydrateClient } from '../trpc/server'; import { ClientGreeting } from './client-greeting'; export default async function Home() { await trpc.hello.prefetch(); return (
...
{/** ... */}
); } ``` ```tsx title="app/client-greeting.tsx" 'use client'; // <-- hooks can only be used in client components import { trpc } from '../trpc/client'; export function ClientGreeting() { const greeting = trpc.hello.useQuery(); if (!greeting.data) return
Loading...
; return
{greeting.data.greeting}
; } ``` ### Leveraging Suspense You may prefer handling loading and error states using Suspense and Error Boundaries. You can do this by using the `useSuspenseQuery` hook. ```tsx title="app/page.tsx" import { trpc, HydrateClient } from '../trpc/server'; import { Suspense } from 'react'; import { ErrorBoundary } from 'react-error-boundary'; import { ClientGreeting } from './client-greeting'; export default async function Home() { void trpc.hello.prefetch(); return (
...
{/** ... */} Something went wrong}> Loading...}>
); } ``` ```tsx title="app/client-greeting.tsx" 'use client'; import { trpc } from '../trpc/client'; export function ClientGreeting() { const [data] = trpc.hello.useSuspenseQuery(); return
{data.greeting}
; } ``` ### Getting data in a server component If you need access to the data in a server component, you can invoke the procedure directly instead of using `.prefetch()`, just like you use [the normal server caller](https://trpc.io/docs/server/server-side-calls.md). Please note that this method is detached from your query client and does not store the data in the cache. This means that you cannot use the data in a server component and expect it to be available in the client. This is intentional and explained in more detail in the [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#data-ownership-and-revalidation) guide. ```tsx title="app/page.tsx" import { trpc } from '../trpc/server'; export default async function Home() { // Use the caller directly without using `.prefetch()` const greeting = await trpc.hello(); return
{greeting.greeting}
; } ``` --- Source: https://trpc.io/docs/client/react/infer-types # Inferring Types > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). In addition to the type inference made available by `@trpc/server` ([see here](https://trpc.io/docs/client/vanilla/infer-types.md)) this integration also provides some inference helpers for usage purely in React. ## Infer React Query options based on your router When creating custom hooks around tRPC procedures, it's sometimes necessary to have the types of the options inferred from the router. You can do so via the `inferReactQueryProcedureOptions` helper exported from `@trpc/react-query`. ```ts title="trpc.ts" import { createTRPCReact, type inferReactQueryProcedureOptions, } from '@trpc/react-query'; import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server'; import type { AppRouter } from './server'; // infer the types for your router export type ReactQueryOptions = inferReactQueryProcedureOptions; export type RouterInputs = inferRouterInputs; export type RouterOutputs = inferRouterOutputs; export const trpc = createTRPCReact(); ``` ```ts title="usePostCreate.ts" import { trpc, type ReactQueryOptions, type RouterInputs, type RouterOutputs, } from './trpc'; type PostCreateOptions = ReactQueryOptions['post']['create']; function usePostCreate(options?: PostCreateOptions) { const utils = trpc.useUtils(); return trpc.post.create.useMutation({ ...options, onSuccess(post, variables, onMutateResult, context) { // invalidate all queries on the post router // when a new post is created utils.post.invalidate(); options?.onSuccess?.(post, variables, onMutateResult, context); }, }); } ``` ```ts title="usePostById.ts" import { ReactQueryOptions, RouterInputs, trpc } from './trpc'; type PostByIdOptions = ReactQueryOptions['post']['byId']; type PostByIdInput = RouterInputs['post']['byId']; function usePostById(input: PostByIdInput, options?: PostByIdOptions) { return trpc.post.byId.useQuery(input, options); } ``` ## Infer abstract types from a "Router Factory" If you write a factory which creates a similar router interface several times in your application, you may wish to share client code between usages of the factory. `@trpc/react-query/shared` exports several types which can be used to generate abstract types for a router factory, and build common React components which are passed the router as a prop. ```tsx title="api/factory.ts" import { z } from 'zod'; import { t, publicProcedure } from './trpc'; // @trpc/react-query/shared exports several **Like types which can be used to generate abstract types import { RouterLike, UtilsLike } from '@trpc/react-query/shared'; const ThingRequest = z.object({ name: z.string() }); const Thing = z.object({ id: z.string(), name: z.string() }); const ThingQuery = z.object({ filter: z.string().optional() }); const ThingArray = z.array(Thing); // Factory function written by you, however you need, // so long as you can infer the resulting type of t.router() later export function createMyRouter() { return t.router({ createThing: publicProcedure .input(ThingRequest) .output(Thing) .mutation(({ input }) => ({ id: '1', ...input })), listThings: publicProcedure .input(ThingQuery) .output(ThingArray) .query(() => []), }) } // Infer the type of your router, and then generate the abstract types for use in the client type MyRouterType = ReturnType export type MyRouterLike = RouterLike export type MyRouterUtilsLike = UtilsLike ``` ```tsx title="api/server.ts" export type AppRouter = typeof appRouter; // Export your MyRouter types to the client export type { MyRouterLike, MyRouterUtilsLike } from './factory'; ``` ```tsx title="frontend/usePostCreate.ts" import type { MyRouterLike, MyRouterUtilsLike } from './factory'; type MyGenericComponentProps = { route: MyRouterLike; utils: MyRouterUtilsLike; }; function MyGenericComponent(props: MyGenericComponentProps) { const { route } = props; const thing = route.listThings.useQuery({ filter: 'qwerty', }); const mutation = route.doThing.useMutation({ onSuccess() { props.utils.listThings.invalidate(); }, }); function handleClick() { mutation.mutate({ name: 'Thing 1', }); } return null; /* ui */ } function MyPageComponent() { const utils = useUtils(); return ( ); } function MyOtherPageComponent() { const utils = useUtils(); return ( ); } ``` A more complete working example [can be found here](https://github.com/trpc/trpc/blob/main/packages/react-query/test/polymorphism.test.tsx) --- Source: https://trpc.io/docs/client/react/useQuery # useQuery() > Fetch data with the classic trpc.procedure.useQuery() hook, its tRPC-specific options and streaming > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). `useQuery` is the primary hook for data fetching, it works similarly to `@tanstack/react-query`'s `useQuery`, but with some `trpc` specific options and additional features like streaming. > [!NOTE] > For in-depth information about options and usage patterns, refer to the TanStack Query docs on [queries](https://tanstack.com/query/v5/docs/framework/react/guides/queries). ## Signature ```tsx declare function useQuery( input: TInput | SkipToken, opts?: UseTRPCQueryOptions, ): void; interface UseTRPCQueryOptions extends UseQueryOptions { trpc: { ssr?: boolean; abortOnUnmount?: boolean; context?: Record; } } ``` Since `UseTRPCQueryOptions` extends `@tanstack/react-query`'s `UseQueryOptions`, you can use any of their options here such as `enabled`, `refetchOnWindowFocus`, etc. We also have some `trpc` specific options that let you opt in or out of certain behaviors on a per-procedure level: - **`trpc.ssr`:** If you have `ssr: true` in `createTRPCNext` (deprecated, see [Moving from `createTRPCNext`](https://trpc.io/docs/client/nextjs/pages-router/setup.md#moving-from-createtrpcnext)), you can set this to false to disable ssr for this particular query. _Note that this does not work the other way around, i.e., you can not enable ssr on a procedure if your global config is set to false._ - **`trpc.abortOnUnmount`:** Override the global `abortOnUnmount` of `createTRPCReact` or `createTRPCNext`, and opt in or out of aborting queries on unmount. - **`trpc.context`:** Add extra meta data that could be used in [Links](https://trpc.io/docs/client/links.md). > [!TIP] > If you need to set any options but don't want to pass any input, you can pass `undefined` instead. You'll notice that you get autocompletion on the `input` based on what you have set in your `input` schema on your backend. ## Example usage
Backend code ```tsx title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ // Create procedure at path 'hello' hello: t.procedure // using zod schema to validate and infer input values .input( z .object({ text: z.string().nullish(), }) .nullish(), ) .query((opts) => { return { greeting: `hello ${opts.input?.text ?? 'world'}`, }; }), }); export type AppRouter = typeof appRouter; ```
```tsx title="components/MyComponent.tsx" import { trpc } from '../utils/trpc'; export function MyComponent() { // input is optional, so we don't have to pass second argument const helloNoArgs = trpc.hello.useQuery(); const helloWithArgs = trpc.hello.useQuery({ text: 'client' }); return (

Hello World Example

  • helloNoArgs ({helloNoArgs.status}):{' '}
    {JSON.stringify(helloNoArgs.data, null, 2)}
  • helloWithArgs ({helloWithArgs.status}):{' '}
    {JSON.stringify(helloWithArgs.data, null, 2)}
); } ``` ## Streaming responses using async generators {#streaming} > [!NOTE] Info > Since v11 we now support streaming queries when using the [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md#generators). When returning an async generator in a query, you will: - Get the results of the iterator in the `data`-property **as an array** which updates as the response comes in - The `status` will be `success` as soon as the first chunk is received. - The `fetchStatus` property which will be `fetching` until the last chunk is received. ### Example ```tsx title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; const t = initTRPC.create(); const appRouter = t.router({ iterable: t.procedure.query(async function* () { for (let i = 0; i < 3; i++) { await new Promise((resolve) => setTimeout(resolve, 500)); yield i; } }), }); export type AppRouter = typeof appRouter; ``` ```tsx title="components/MyComponent.tsx" import React, { Fragment } from 'react'; import { trpc } from '../utils/trpc'; export function MyComponent() { const result = trpc.iterable.useQuery(); return (
{result.data?.map((chunk, index) => ( {chunk} ))}
); } ``` `result` properties while streaming: | `status` | `fetchStatus` | `data` | | ----------- | ------------- | ----------- | | `'pending'` | `'fetching'` | `undefined` | | `'success'` | `'fetching'` | `[]` | | `'success'` | `'fetching'` | `[0]` | | `'success'` | `'fetching'` | `[0, 1]` | | `'success'` | `'fetching'` | `[0, 1, 2]` | | `'success'` | `'idle'` | `[0, 1, 2]` | --- Source: https://trpc.io/docs/client/react/useMutation # useMutation() > Call mutations with the classic trpc.procedure.useMutation() hook > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). > [!NOTE] > The hooks provided by `@trpc/react-query` are a thin wrapper around @tanstack/react-query. For in-depth information about options and usage patterns, refer to their docs on [mutations](https://tanstack.com/query/v5/docs/framework/react/guides/mutations). ### Example
Backend code ```tsx title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ // Create procedure at path 'login' // The syntax is identical to creating queries login: t.procedure // using zod schema to validate and infer input values .input( z.object({ name: z.string(), }), ) .mutation((opts) => { // Here some login stuff would happen return { user: { name: opts.input.name, role: 'ADMIN' as const, }, }; }), }); export type AppRouter = typeof appRouter; ```
```tsx import { trpc } from '../utils/trpc'; export function MyComponent() { const mutation = trpc.login.useMutation(); const handleLogin = () => { const name = 'John Doe'; mutation.mutate({ name }); }; return (

Login Form

{mutation.error &&

Something went wrong! {mutation.error.message}

}
); } ``` --- Source: https://trpc.io/docs/client/react/useInfiniteQuery # useInfiniteQuery() > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). > [!NOTE] Info > > - Your procedure needs to accept a `cursor` input of any type (`string`, `number`, etc) to expose this hook. > - For more details on infinite queries read the [react-query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useInfiniteQuery) > - In this example we're using Prisma - see their docs on [cursor-based pagination](https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination) ## Example Procedure ```tsx title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ infinitePosts: t.procedure .input( z.object({ limit: z.number().min(1).max(100).nullish(), cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type direction: z.enum(['forward', 'backward']), // optional, useful for bi-directional query }), ) .query(async (opts) => { const { input } = opts; const limit = input.limit ?? 50; const { cursor } = input; const items = await prisma.post.findMany({ take: limit + 1, // get an extra item at the end which we'll use as next cursor where: { title: { contains: 'Prisma' /* Optional filter */, }, }, cursor: cursor ? { myCursor: cursor } : undefined, orderBy: { myCursor: 'asc', }, }); let nextCursor: typeof cursor | undefined = undefined; if (items.length > limit) { const nextItem = items.pop(); nextCursor = nextItem!.myCursor; } return { items, nextCursor, }; }), }); ``` ## Example React Component ```tsx title="components/MyComponent.tsx" import { trpc } from '../utils/trpc'; export function MyComponent() { const myQuery = trpc.infinitePosts.useInfiniteQuery( { limit: 10, }, { getNextPageParam: (lastPage) => lastPage.nextCursor, // initialCursor: 1, // <-- optional you can pass an initialCursor }, ); // [...] } ``` ## Helpers ### `getInfiniteData()` This helper gets the currently cached data from an existing infinite query ```tsx title="components/MyComponent.tsx" import { trpc } from '../utils/trpc'; export function MyComponent() { const utils = trpc.useUtils(); const myMutation = trpc.infinitePosts.add.useMutation({ async onMutate(opts) { await utils.infinitePosts.list.cancel(); const allPosts = utils.infinitePosts.list.getInfiniteData({ limit: 10 }); // [...] }, }); } ``` ### `setInfiniteData()` This helper allows you to update a query's cached data ```tsx title="components/MyComponent.tsx" import { trpc } from '../utils/trpc'; export function MyComponent() { const utils = trpc.useUtils(); const myMutation = trpc.infinitePosts.delete.useMutation({ async onMutate(opts) { await utils.infinitePosts.list.cancel(); utils.infinitePosts.list.setInfiniteData({ limit: 10 }, (data) => { if (!data) { return { pages: [], pageParams: [], }; } return { ...data, pages: data.pages.map((page) => ({ ...page, items: page.items.filter((item) => item.status === 'published'), })), }; }); }, }); // [...] } ``` --- Source: https://trpc.io/docs/client/react/useSubscription # useSubscription() > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). The `useSubscription` hook can be used to subscribe to a [subscription](https://trpc.io/docs/server/subscriptions.md) procedure on the server. ## Signature ### Options > [!TIP] > > - If you need to set any options but don't want to pass any input, you can pass `undefined` instead. > - If you pass `skipToken` from `@tanstack/react-query`, the subscription will be paused. > - Have a look at our [SSE example](https://github.com/trpc/examples-tanstack-start-sse-chat) for a complete example of how to use subscriptions ```tsx interface UseTRPCSubscriptionOptions { /** * Called when the subscription is started. */ onStarted?: () => void; /** * Called when new data is received from the subscription. */ onData?: (data: TOutput) => void; /** * Called when an **unrecoverable error** occurs and the subscription is stopped. */ onError?: (error: TError) => void; /** * Called when the subscription is completed on the server. * The state will transition to `'idle'` with `data: undefined`. */ onComplete?: () => void; /** * @deprecated Use a `skipToken` from `@tanstack/react-query` instead. * This will be removed in v12. */ enabled?: boolean; } ``` ### Return type The return type is a discriminated union on `status`: ```ts type TRPCSubscriptionResult = | TRPCSubscriptionIdleResult | TRPCSubscriptionConnectingResult | TRPCSubscriptionPendingResult | TRPCSubscriptionErrorResult; interface TRPCSubscriptionIdleResult { /** Subscription is disabled or has ended */ status: 'idle'; data: undefined; error: null; reset: () => void; } interface TRPCSubscriptionConnectingResult { /** Trying to establish a connection (may have a previous error from a reconnection attempt) */ status: 'connecting'; data: TOutput | undefined; error: TError | null; reset: () => void; } interface TRPCSubscriptionPendingResult { /** Connected to the server, receiving data */ status: 'pending'; data: TOutput | undefined; error: null; reset: () => void; } interface TRPCSubscriptionErrorResult { /** An unrecoverable error occurred and the subscription is stopped */ status: 'error'; data: TOutput | undefined; error: TError; reset: () => void; } ``` ## Example Procedure ```tsx title="server/routers/_app.ts" import EventEmitter, { on } from 'events'; import { initTRPC } from '@trpc/server'; export const t = initTRPC.create(); type Post = { id: string; title: string }; const ee = new EventEmitter(); export const appRouter = t.router({ onPostAdd: t.procedure.subscription(async function* (opts) { for await (const [data] of on(ee, 'add', { signal: opts.signal, })) { const post = data as Post; yield post; } }), }); export type AppRouter = typeof appRouter; ``` ## Example React Component ```tsx title="components/PostFeed.tsx" import { trpc } from '../utils/trpc'; type Post = { id: string; title: string }; export function PostFeed() { const [posts, setPosts] = React.useState([]); const subscription = trpc.onPostAdd.useSubscription(undefined, { onData: (post) => { setPosts((prev) => [...prev, post]); }, }); return (

Live Feed

{subscription.status === 'connecting' &&

Connecting...

} {subscription.status === 'error' && (

Error: {subscription.error.message}

)}
    {posts.map((post) => (
  • {post.title}
  • ))}
); } ``` --- Source: https://trpc.io/docs/client/react/useUtils # useUtils > Invalidate, refetch, prefetch and update cached query data with the classic trpc.useUtils() helpers > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). `useUtils` is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via `@trpc/react-query`. These helpers are actually thin wrappers around `@tanstack/react-query`'s [`queryClient`](https://tanstack.com/query/v5/docs/reference/QueryClient) methods. If you want more in-depth information about options and usage patterns for `useUtils` helpers than what we provide here, we will link to their respective `@tanstack/react-query` docs so you can refer to them accordingly. > [!NOTE] > > This hook was called `useContext()` until `10.41.0` (and is still aliased for the foreseeable future) ## Usage `useUtils` returns an object with all the available queries you have in your routers. You use it the same way as your `trpc` client object. Once you reach a query, you'll have access to the query helpers. For example, let's say you have a `post` router with an `all` query: ```ts title="server.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; const t = initTRPC.create(); const appRouter = t.router({ post: t.router({ all: t.procedure.query(() => { return { posts: [ { id: 1, title: 'everlong' }, { id: 2, title: 'After Dark' }, ], }; }), }), }); export type AppRouter = typeof appRouter; ``` Now in our component, when we navigate the object `useUtils` gives us and reach the `post.all` query, we'll get access to our query helpers! ```tsx title="MyComponent.tsx" import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from './server'; const trpc = createTRPCReact(); function MyComponent() { const utils = trpc.useUtils(); utils.post.all.f; } ``` ## Helpers These are the helpers you'll get access to via `useUtils`. The table below will help you know which tRPC helper wraps which `@tanstack/react-query` helper method. Each react-query method will link to its respective docs/guide: | tRPC helper wrapper | `@tanstack/react-query` helper method | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `fetch` | [`queryClient.fetchQuery`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientfetchquery) | | `prefetch` | [`queryClient.prefetchQuery`](https://tanstack.com/query/v5/docs/framework/react/guides/prefetching) | | `fetchInfinite` | [`queryClient.fetchInfiniteQuery`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientfetchinfinitequery) | | `prefetchInfinite` | [`queryClient.prefetchInfiniteQuery`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientprefetchinfinitequery) | | `ensureData` | [`queryClient.ensureData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientensurequerydata) | | `invalidate` | [`queryClient.invalidateQueries`](https://tanstack.com/query/v5/docs/framework/react/guides/query-invalidation) | | `refetch` | [`queryClient.refetchQueries`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientrefetchqueries) | | `cancel` | [`queryClient.cancelQueries`](https://tanstack.com/query/v5/docs/framework/react/guides/query-cancellation) | | `setData` | [`queryClient.setQueryData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata) | | `setQueriesData` | [`queryClient.setQueriesData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetqueriesdata) | | `getData` | [`queryClient.getQueryData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata) | | `setInfiniteData` | [`queryClient.setInfiniteQueryData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata) | | `getInfiniteData` | [`queryClient.getInfiniteData`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata) | | `setMutationDefaults` | [`queryClient.setMutationDefaults`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetmutationdefaults) | | `getMutationDefaults` | [`queryClient.getMutationDefaults`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetmutationdefaults) | | `isMutating` | [`queryClient.isMutating`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientismutating) | | `reset` | [`queryClient.resetQueries`](https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientresetqueries) | ### ❓ The function I want isn't here! `@tanstack/react-query` has a lot of functions that we haven't put in the tRPC context yet. If you need a function that isn't here, feel free to [open a feature request](https://github.com/trpc/trpc/issues/new/choose) requesting it. In the meantime, you can import and use the function directly from `@tanstack/react-query`. We also provide a [getQueryKey](https://trpc.io/docs/client/react/getQueryKey.md) which you can use to get the correct queryKey on the filters when using these functions. ## Proxy client In addition to the above react-query helpers, the context also exposes your tRPC proxy client. This lets you call your procedures with `async`/`await` without needing to create an additional vanilla client. ```tsx import { useState } from 'react'; import { trpc } from './utils/trpc'; function MyComponent() { const [apiKey, setApiKey] = useState(''); const utils = trpc.useUtils(); return (
{ const apiKey = await utils.client.apiKey.create.mutate(); setApiKey(apiKey); }} > {/* form content */}
); } ``` ## Query Invalidation You invalidate queries via the `invalidate` helper. `invalidate` is actually a special helper given that, unlike the other helpers, it's available at every level of the router map. This means you can either run `invalidate` on a single query, a whole router, or every router if you want. We get more in detail in the sections below. ### Invalidating a single query You can invalidate a query relating to a single procedure and even filter based on the input passed to it to prevent unnecessary calls to the back end. #### Example code ```tsx import { trpc } from './utils/trpc'; function MyComponent() { const utils = trpc.useUtils(); const mutation = trpc.post.edit.useMutation({ onSuccess(input) { utils.post.all.invalidate(); utils.post.byId.invalidate({ id: input.id }); // Will not invalidate queries for other id's }, }); // [...] } ``` ### Invalidating across whole routers It is also possible to invalidate queries across an entire router rather than just one query. #### Example code
Backend code ```tsx title="server/routers/_app.ts" import { initTRPC } from '@trpc/server'; import { z } from 'zod'; export const t = initTRPC.create(); export const appRouter = t.router({ // sub Post router post: t.router({ all: t.procedure.query(() => { return { posts: [ { id: 1, title: 'everlong' }, { id: 2, title: 'After Dark' }, ], }; }), byId: t.procedure .input( z.object({ id: z.string(), }), ) .query(({ input }) => { return { post: { id: input?.id, title: 'Look me up!' }, }; }), edit: t.procedure .input(z.object({ id: z.number(), title: z.string() })) .mutation(({ input }) => { return { post: { id: input.id, title: input.title } }; }), }), // separate user router user: t.router({ all: t.procedure.query(() => { return { users: [{ name: 'Dave Grohl' }, { name: 'Haruki Murakami' }] }; }), }), }); ```
```tsx import { trpc } from './utils/trpc'; function MyComponent() { const utils = trpc.useUtils(); const invalidateAllQueriesAcrossAllRouters = () => { // 1️⃣ // All queries on all routers will be invalidated utils.invalidate(); }; const invalidateAllPostQueries = () => { // 2️⃣ // All post queries will be invalidated utils.post.invalidate(); }; const invalidatePostById = () => { // 3️⃣ // All queries in the post router with input {id:1} invalidated utils.post.byId.invalidate({ id: 1 }); }; // Example queries trpc.user.all.useQuery(); // Would only be validated by 1️⃣ only. trpc.post.all.useQuery(); // Would be invalidated by 1️⃣ & 2️⃣ trpc.post.byId.useQuery({ id: 1 }); // Would be invalidated by 1️⃣, 2️⃣ and 3️⃣ trpc.post.byId.useQuery({ id: 2 }); // would be invalidated by 1️⃣ and 2️⃣ but NOT 3️⃣! // [...] } ``` ### Invalidate full cache on every mutation Keeping track of exactly what queries a mutation should invalidate is hard, therefore, it can be a pragmatic solution to invalidate the _full cache_ as a side-effect on any mutation. Since we have request batching, this invalidation will simply refetch all queries on the page you're looking at in one single request. We have added a feature to help with this: ```ts import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from '../server'; export const trpc = createTRPCReact({ overrides: { useMutation: { /** * This function is called whenever a `.useMutation` succeeds **/ async onSuccess(opts) { /** * @note that order here matters: * The order here allows route changes in `onSuccess` without * having a flash of content change whilst redirecting. **/ // Calls the `onSuccess` defined in the `useQuery()`-options: await opts.originalFn(); // Invalidate all queries in the react-query cache: await opts.queryClient.invalidateQueries(); }, }, }, }); ``` ## Additional Options Aside from the query helpers, the object `useUtils` returns also contains the following properties: ```ts interface ProxyTRPCContextProps { /** * The `TRPCClient` */ client: TRPCClient; /** * The SSR context when server-side rendering * @default null */ ssrContext?: TSSRContext | null; /** * State of SSR hydration. * - `false` if not using SSR. * - `prepass` when doing a prepass to fetch queries' data * - `mounting` before TRPCProvider has been rendered on the client * - `mounted` when the TRPCProvider has been rendered on the client * @default false */ ssrState?: SSRState; /** * Abort loading query calls when unmounting a component - usually when navigating to a new page * @default false */ abortOnUnmount?: boolean; } ``` --- Source: https://trpc.io/docs/client/react/createTRPCQueryUtils # createTRPCQueryUtils > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). The use case for `createTRPCQueryUtils` is when you need to use the helpers outside of a React Component, for example in `react-router`'s loaders. Similar to `useUtils`, `createTRPCQueryUtils` is a function that gives you access to helpers that let you manage the cached data of the queries you execute via `@trpc/react-query`. These helpers are actually thin wrappers around `@tanstack/react-query`'s [`queryClient`](https://tanstack.com/query/v5/docs/reference/QueryClient) methods. If you want more in-depth information about options and usage patterns for `useUtils` helpers than what we provide here, we will link to their respective `@tanstack/react-query` docs so you can refer to them accordingly. The difference between `useUtils` and `createTRPCQueryUtils` is that `useUtils` is a react hook that uses `useQueryClient` under the hood. This means that it is able to work better within React Components. If you need access to the client directly, you can use the `client` object that you passed to `createTRPCQueryUtils` during creation. > [!WARNING] Caution > > You should avoid using `createTRPCQueryUtils` in React Components. Instead, use `useUtils` which is a React hook that implements `useCallback` and `useQueryClient` under the hood. ## Usage `createTRPCQueryUtils` returns an object with all the available queries you have in your routers. You use it the same way as your `trpc` client object. Once you reach a query, you'll have access to the query helpers. For example, let's say you have a `post` router with an `all` query: Now in our route loader, when we navigate the object `createTRPCQueryUtils` gives us and reach the `post.all` query, we'll get access to our query helpers! ```tsx title="MyPage.tsx" import { QueryClient } from '@tanstack/react-query'; import { createTRPCQueryUtils, createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from './server'; const trpc = createTRPCReact(); const trpcClient = trpc.createClient({ links: [] }); const queryClient = new QueryClient(); const clientUtils = createTRPCQueryUtils({ queryClient, client: trpcClient }); // This is a react-router loader export async function loader() { const allPostsData = await clientUtils.post.all.ensureData(); // Fetches data if it doesn't exist in the cache return { allPostsData, }; } // This is a react component export function Component() { const loaderData = useLoaderData() as Awaited>; const allPostQuery = trpc.post.all.useQuery(undefined, { initialData: loaderData.allPostsData, // Uses the data from the loader }); return (
{allPostQuery.data.posts.map((post) => (
{post.title}
))}
); } ``` > [!NOTE] > > If you were using Remix Run or SSR you wouldn't re-use the same `queryClient` for every request. Instead, you would create a new `queryClient` for every request so that there's no cross-request data leakage. ## Helpers Much like `useUtils`, `createTRPCQueryUtils` gives you access to same set of helpers, including `queryOptions` and `infiniteQueryOptions`. The only difference is that you need to pass in the `queryClient` and `client` objects. You can see them on the [useUtils](https://trpc.io/docs/client/react/useUtils.md#helpers)-page. --- Source: https://trpc.io/docs/client/react/useQueries # useQueries() > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). The `useQueries` hook can be used to fetch a variable number of queries at the same time using only one hook call. The main use case for such a hook is to be able to fetch a number of queries, usually of the same type. For example if you fetch a list of todo ids, you can then map over them in a useQueries hook calling a byId endpoint that would fetch the details of each todo. > [!NOTE] > While fetching multiple types in a `useQueries` hook is possible, there is not much of an advantage compared to using multiple `useQuery` calls unless you use the `suspense` option as that `useQueries` can trigger suspense in parallel while multiple `useQuery` calls would waterfall. ## Usage The useQueries hook is the same as that of [@tanstack/query useQueries](https://tanstack.com/query/v5/docs/framework/react/reference/useQueries). The only difference is that instead of passing an object with a `queries` array, you pass a callback function that receives a `t` proxy and returns an array of queries. > [!TIP] > When you're using the [`httpBatchLink`](https://trpc.io/docs/client/links/httpBatchLink.md) or [`wsLink`](https://trpc.io/docs/client/links/wsLink.md), the below will end up being only 1 HTTP call to your server. Additionally, if the underlying procedure is using something like Prisma's `findUnique()` it will [automatically batch](https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance#solving-n1-in-graphql-with-findunique-and-prismas-dataloader) & do exactly 1 database query as a well. ```tsx import { trpc } from './utils/trpc'; const Component = (props: { postIds: string[] }) => { const postQueries = trpc.useQueries((t) => props.postIds.map((id) => t.post.byId({ id })), ); return <>{/* [...] */}; }; ``` ### Providing options to individual queries You can also pass in any normal query options to the second parameter of any of the query calls in the array such as `enabled`, `suspense`, `refetchOnWindowFocus`...etc. For a complete overview of all the available options, see the [tanstack useQuery](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) documentation. ```tsx import { trpc } from './utils/trpc'; const Component = () => { const [post, greeting] = trpc.useQueries((t) => [ t.post.byId({ id: '1' }, { enabled: false }), t.greeting({ text: 'world' }), ]); const onButtonClick = () => { post.refetch(); }; return (

{post.data && post.data.title}

{greeting.data?.message}

); }; ``` ### Context You can also pass in an optional React Query context to override the default. ```tsx const [post, greeting] = trpc.useQueries( (t) => [t.post.byId({ id: '1' }), t.greeting({ text: 'world' })], myCustomContext, ); ``` --- Source: https://trpc.io/docs/client/react/suspense # Suspense > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). > [!NOTE] Info > > - Ensure you're on the latest version of React > - If you use suspense with [tRPC's _automatic_ SSR in Next.js](https://trpc.io/docs/client/nextjs/pages-router/ssr.md), the full page will crash on the server if a query fails, even if you have an `` ## Usage > [!TIP] > > `useSuspenseQuery` & `useSuspenseInfiniteQuery` both return a `[data, query]`-_tuple_, to make it easy to directly use your data and renaming the variable to something descriptive ### `useSuspenseQuery()` ```tsx import { trpc } from '../utils/trpc'; function PostView() { const [post, postQuery] = trpc.post.byId.useSuspenseQuery({ id: '1' }); // const post: { // id: string; // title: string; // } return <>{/* ... */}; } ``` ### `useSuspenseInfiniteQuery()` ```tsx import { trpc } from '../utils/trpc'; import type { PostPage } from '../server'; function PostView() { const [{ pages }, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery( {}, { getNextPageParam(lastPage: PostPage) { return lastPage.nextCursor; }, initialCursor: '', }, ); const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } = allPostsQuery; return <>{/* ... */}; } ``` ### `useSuspenseQueries()` Suspense equivalent of [`useQueries()`](https://trpc.io/docs/client/react/useQueries.md). ```tsx import { trpc } from '../utils/trpc'; const Component = (props: { postIds: string[] }) => { const [posts, postQueries] = trpc.useSuspenseQueries((t) => props.postIds.map((id) => t.post.byId({ id })), ); return <>{/* [...] */}; }; ``` ## Prefetching The performance of suspense queries can be improved by prefetching the query data before the Suspense component is rendered (this is sometimes called ["render-as-you-fetch"](https://tanstack.com/query/v5/docs/framework/react/guides/suspense#fetch-on-render-vs-render-as-you-fetch)). > [!NOTE] > > - Prefetching and the render-as-you-fetch model are very dependent on the framework and router you are using. We recommend reading your frameworks router docs along with the [@tanstack/react-query docs](https://tanstack.com/query/v5/docs/react/guides/prefetching) to understand how to implement these patterns. > - If you are using Next.js please look at the docs on [Server-Side Helpers](https://trpc.io/docs/client/nextjs/pages-router/server-side-helpers.md) to implement server-side prefetching. ### Route-level prefetching ```tsx import { createTRPCQueryUtils } from '@trpc/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { QueryClient } from '@tanstack/react-query'; import type { AppRouter } from './server'; const queryClient = new QueryClient(); const trpcClient = createTRPCClient({ links: [httpBatchLink({ url: 'http://localhost:3000' })] }); const utils = createTRPCQueryUtils({ queryClient, client: trpcClient }); // tanstack router/ react router loader const loader = async (params: { id: string }) => utils.post.byId.ensureData({ id: params.id }); ``` ### Component-level prefetching with `usePrefetchQuery` ```tsx import React, { Suspense } from 'react'; import { trpc } from '../utils/trpc'; function PostView(props: { postId: string }) { return <>; } function PostViewPage(props: { postId: string }) { trpc.post.byId.usePrefetchQuery({ id: props.postId }); return ( ); } ``` ### Component-level prefetching with `usePrefetchInfiniteQuery` ```tsx import React, { Suspense } from 'react'; import { trpc } from '../utils/trpc'; import type { PostPage } from '../server'; function PostView(props: { postId: string }) { return <>; } function PostViewPage(props: { postId: string }) { trpc.post.all.usePrefetchInfiniteQuery( {}, { getNextPageParam(lastPage: PostPage) { return lastPage.nextCursor; }, initialCursor: '', }, ); return ( ); } ``` --- Source: https://trpc.io/docs/client/react/getQueryKey # getQueryKey > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). We provide a getQueryKey helper that accepts a `router` or `procedure` so that you can easily provide the native function the correct query key. ```tsx // Queries declare function getQueryKey( procedure: AnyQueryProcedure, input?: DeepPartial, type?: QueryType, /** @default 'any' */ ): TRPCQueryKey; // Routers declare function getQueryKey( router: AnyRouter, ): TRPCQueryKey; type QueryType = "query" | "infinite" | "any"; // for useQuery β”€β”€β”˜ β”‚ β”‚ // for useInfiniteQuery β”€β”€β”€β”€β”˜ β”‚ // will match all β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` > [!NOTE] > > The query type `any` will match all queries in the cache only if the `react query` method where it's used uses fuzzy matching. See [TanStack/query#5111 (comment)](https://github.com/TanStack/query/issues/5111#issuecomment-1464864361) for more context. ```tsx import { useIsFetching, useQueryClient } from '@tanstack/react-query'; import { getQueryKey } from '@trpc/react-query'; import { trpc } from './utils/trpc'; function MyComponent() { const queryClient = useQueryClient(); const posts = trpc.post.list.useQuery(); // See if a query is fetching const postListKey = getQueryKey(trpc.post.list, undefined, 'query'); const isFetching = useIsFetching({ queryKey: postListKey }); // Set some query defaults for an entire router const postKey = getQueryKey(trpc.post); queryClient.setQueryDefaults(postKey, { staleTime: 30 * 60 * 1000 }); // ... } ``` ## Mutations Similarly to queries, we provide a getMutationKey for mutations. The underlying function is the same as getQueryKey (in fact, you could technically use getQueryKey for mutations as well), the only difference is in semantics. ```tsx import { getMutationKey } from '@trpc/react-query'; const mutationKey = getMutationKey(trpc.user.create); ``` --- Source: https://trpc.io/docs/client/react/aborting-procedure-calls # Aborting Procedure Calls > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). By default, tRPC does not cancel requests via React Query. If you want to opt into this behavior, you can provide `abortOnUnmount` in your configuration. > [!NOTE] > @tanstack/react-query only supports aborting queries. ### Globally ```ts title="client.ts" import { createTRPCReact } from '@trpc/react-query'; import type { AppRouter } from './server'; export const trpc = createTRPCReact({ abortOnUnmount: true, }); ``` ### Per-request You may also override this behavior at the query level. ```tsx title="pages/post/[id].tsx" import { trpc } from '../utils/trpc'; function PostViewPage() { const { query } = useRouter(); const postQuery = trpc.post.byId.useQuery( { id: query.id }, { trpc: { abortOnUnmount: true } } ); // ... } ``` --- Source: https://trpc.io/docs/client/react/disabling-queries # Disabling Queries > > [!WARNING] Deprecated > The classic React Query integration (`@trpc/react-query`) only gets bug fixes, and will be removed in the next major version of tRPC. New projects should use the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). To move an existing project, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md). To disable queries, you can pass `skipToken` as the first argument to `useQuery`, `useInfiniteQuery`, and `useSubscription`. This will prevent the query from being executed. ### Typesafe conditional queries using `skipToken` ```tsx import React, { useState } from 'react'; import { skipToken } from '@tanstack/react-query'; import { trpc } from './utils/trpc'; export function MyComponent() { const [name, setName] = useState(); const result = trpc.getUserByName.useQuery(name ? { name: name } : skipToken); return (
{result.data?.name}
); } ``` --- Source: https://trpc.io/docs/client/nextjs # Next.js Integration > ## tRPC + Next.js Next.js makes it easy to build a client and server together in one codebase. tRPC makes it easy to share types between them, ensuring typesafety for your application's data fetching. tRPC provides first-class support for both the **App Router** and the **Pages Router**. Choose the guide that matches your project: ## App Router The recommended approach for new Next.js projects. Uses React Server Components, the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md), and [`@trpc/tanstack-react-query`](https://trpc.io/docs/client/tanstack-react-query.md). Key features: - **Server Components** - Prefetch data on the server and stream it to the client - **Streaming** - Leverage Next.js streaming for optimal loading performance - **Suspense** - Use `useSuspenseQuery` with Suspense boundaries for loading states **[Get started with App Router →](https://trpc.io/docs/client/nextjs/app-router-setup.md)** ## Pages Router Uses the [Next.js adapter](https://trpc.io/docs/server/adapters/nextjs.md) for the API, and the same client as the App Router: [`@trpc/tanstack-react-query`](https://trpc.io/docs/client/tanstack-react-query.md). Key features: - **Server-side rendering** - Prefetch a page's queries in `getServerSideProps` and render them into the first HTML. Read more about [SSR](https://trpc.io/docs/client/nextjs/pages-router/ssr.md). - **Static site generation** - Prefetch queries in `getStaticProps` and generate static HTML files. Read more about [SSG](https://trpc.io/docs/client/nextjs/pages-router/ssg.md). > [!WARNING] Deprecated > `createTRPCNext`, `withTRPC` and `ssr: true` from `@trpc/next` are deprecated. They're built on the [classic React Query integration](https://trpc.io/docs/client/react.md) (`@trpc/react-query`), which only gets bug fixes and will be removed in the next major version of tRPC. See [Moving from `createTRPCNext`](https://trpc.io/docs/client/nextjs/pages-router/setup.md#moving-from-createtrpcnext). The experimental App Router helpers in `@trpc/next/app-dir` aren't affected. **[Get started with Pages Router →](https://trpc.io/docs/client/nextjs/pages-router/setup.md)** ## Choosing between App Router and Pages Router | | App Router | Pages Router | | ------------------- | -------------------------------------------- | --------------------------------------------------------------- | | **Recommended for** | New projects | Existing Pages Router projects | | **Data fetching** | Server Components, `prefetchQuery` | `prefetchQuery` in `getServerSideProps` or `getStaticProps` | | **Server adapter** | [Fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) | [Next.js adapter](https://trpc.io/docs/server/adapters/nextjs.md) | | **Client package** | `@trpc/tanstack-react-query` | `@trpc/tanstack-react-query` | | **Provider setup** | `TRPCProvider` in the root layout | `TRPCProvider` and `HydrationBoundary` in `_app` | > [!TIP] > If you're starting a new project, we recommend the App Router. If you have an existing Pages Router project, tRPC works well with it and is fully supported. --- Source: https://trpc.io/docs/client/nextjs/app-router-setup # Set up with Next.js App Router > > [!NOTE] > We recommend reading TanStack React Query's [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) docs to understand the different types of server rendering > and footguns to avoid. ## Recommended file structure ```graphql . β”œβ”€β”€ src β”‚ β”œβ”€β”€ app β”‚ β”‚ β”œβ”€β”€ api β”‚ β”‚ β”‚ └── trpc β”‚ β”‚ β”‚ └── [trpc] β”‚ β”‚ β”‚ └── route.ts # <-- tRPC HTTP handler β”‚ β”‚ β”œβ”€β”€ layout.tsx # <-- mount TRPCReactProvider β”‚ β”‚ └── page.tsx # <-- server component β”‚ β”œβ”€β”€ trpc β”‚ β”‚ β”œβ”€β”€ init.ts # <-- tRPC server init & context β”‚ β”‚ β”œβ”€β”€ routers β”‚ β”‚ β”‚ β”œβ”€β”€ _app.ts # <-- main app router β”‚ β”‚ β”‚ β”œβ”€β”€ post.ts # <-- sub routers β”‚ β”‚ β”‚ └── [..] β”‚ β”‚ β”œβ”€β”€ client.tsx # <-- client hooks & provider β”‚ β”‚ β”œβ”€β”€ query-client.ts # <-- shared QueryClient factory β”‚ β”‚ └── server.tsx # <-- server-side caller β”‚ └── [..] └── [..] ``` ## Add tRPC to an existing Next.js App Router project ### 1. Install deps ```package-install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query@latest zod client-only server-only ``` ### 2. Create a tRPC router Initialize your tRPC backend in `trpc/init.ts` using the `initTRPC` function, and create your first router. We're going to make a simple "hello world" router and procedure here β€” for deeper information on creating your tRPC API, refer to the [Quickstart guide](https://trpc.io/docs/quickstart.md) and [Backend usage docs](https://trpc.io/docs/server/overview.md). ```ts title="trpc/init.ts" import { initTRPC } from '@trpc/server'; /** * This context creator accepts `headers` so it can be reused in both * the RSC server caller (where you pass `next/headers`) and the * API route handler (where you pass the request headers). */ export const createTRPCContext = async (opts: { headers: Headers }) => { // const user = await auth(opts.headers); return { userId: 'user_123' }; }; // Avoid exporting the entire t-object // since it's not very descriptive. // For instance, the use of a t variable // is common in i18n libraries. const t = initTRPC .context>>() .create({ /** * @see https://trpc.io/docs/server/data-transformers */ // transformer: superjson, }); // Base router and procedure helpers export const createTRPCRouter = t.router; export const createCallerFactory = t.createCallerFactory; export const baseProcedure = t.procedure; ```
```ts title="trpc/routers/_app.ts" import { z } from 'zod'; import { baseProcedure, createTRPCRouter } from '../init'; export const appRouter = createTRPCRouter({ hello: baseProcedure .input( z.object({ text: z.string(), }), ) .query((opts) => { return { greeting: `hello ${opts.input.text}`, }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ``` ### 3. Create the API route handler With the App Router, use the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) to handle tRPC requests. Create a route handler that exports both `GET` and `POST`: ```ts title="app/api/trpc/[trpc]/route.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { createTRPCContext } from './trpc/init'; import { appRouter } from './trpc/routers/_app'; const handler = (req: Request) => fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: () => createTRPCContext({ headers: req.headers }), }); export { handler as GET, handler as POST }; ``` > [!NOTE] > App Router uses the [fetch adapter](https://trpc.io/docs/server/adapters/fetch.md) (via `fetchRequestHandler`) rather than the Next.js-specific adapter used by the Pages Router. This is because App Router route handlers are based on the Web standard `Request` and `Response` objects. ### 4. Create a Query Client factory Create a shared file `trpc/query-client.ts` that exports a function that creates a `QueryClient` instance. ```ts title="trpc/query-client.ts" import { defaultShouldDehydrateQuery, QueryClient, } from '@tanstack/react-query'; import superjson from 'superjson'; export function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { staleTime: 30 * 1000, }, dehydrate: { // serializeData: superjson.serialize, shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', shouldRedactErrors: (error) => { // Next.js detects dynamic pages by catching the errors we throw, so // we must not redact them here. Next.js redacts with a better digest // of its own. return false; }, }, hydrate: { // deserializeData: superjson.deserialize, }, }, }); } ``` We're setting a few default options here: - `staleTime`: With SSR, we usually want to set some default staleTime above 0 to avoid refetching immediately on the client. - `shouldDehydrateQuery`: This is a function that determines whether a query should be dehydrated or not. Since the RSC transport protocol supports hydrating promises over the network, we extend the `defaultShouldDehydrateQuery` function to also include queries that are still pending. This will allow us to start prefetching in a server component high up the tree, then consuming that promise in a client component further down. - `shouldRedactErrors`: Next.js detects dynamic rendering by looking for the `digest` on an error thrown during the render. Because `shouldDehydrateQuery` also dehydrates queries that are still pending, a query that is pending during the build can reject afterwards, and its error gets dehydrated and redacted before Next.js sees the `digest`. The build then fails. Returning `false` here keeps the `digest` intact so Next.js can still recognise the error. - `serializeData` and `deserializeData` (optional): If you set up a [data transformer](https://trpc.io/docs/server/data-transformers.md) in the previous step, set this option to make sure the data is serialized correctly when hydrating the query client over the server-client boundary. ### 5. Create a tRPC client for Client Components The `trpc/client.tsx` is the entrypoint when consuming your tRPC API from client components. In here, import the **type definition** of your tRPC router and create typesafe hooks using `createTRPCContext`. We'll also export our context provider from this file. ```tsx title="trpc/client.tsx" 'use client'; // ^-- to make sure we can mount the Provider from a server component import type { QueryClient } from '@tanstack/react-query'; import { QueryClientProvider } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { createTRPCContext } from '@trpc/tanstack-react-query'; import { useState } from 'react'; import { makeQueryClient } from './query-client'; import type { AppRouter } from './routers/_app'; export const { TRPCProvider, useTRPC } = createTRPCContext(); let browserQueryClient: QueryClient; function getQueryClient() { if (typeof window === 'undefined') { // Server: always make a new query client return makeQueryClient(); } // Browser: make a new query client if we don't already have one // This is very important, so we don't re-make a new client if React // suspends during the initial render. This may not be needed if we // have a suspense boundary BELOW the creation of the query client if (!browserQueryClient) browserQueryClient = makeQueryClient(); return browserQueryClient; } function getUrl() { const base = (() => { if (typeof window !== 'undefined') return ''; if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; return 'http://localhost:3000'; })(); return `${base}/api/trpc`; } export function TRPCReactProvider( props: Readonly<{ children: React.ReactNode; }>, ) { // NOTE: Avoid useState when initializing the query client if you don't // have a suspense boundary between this and the code that may // suspend because React will throw away the client on the initial // render if it suspends and there is no boundary const queryClient = getQueryClient(); const [trpcClient] = useState(() => createTRPCClient({ links: [ httpBatchLink({ // transformer: superjson, <-- if you use a data transformer url: getUrl(), }), ], }), ); return ( {props.children} ); } ``` Mount the provider in the root layout of your application: ```tsx title="app/layout.tsx" import { TRPCReactProvider } from '~/trpc/client'; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ``` ### 6. Create a tRPC caller for Server Components To prefetch queries from server components, we create a proxy from our router. You can also pass in a client if your router is on a separate server. We'll also add a `HydrateClient` component that hands the prefetched queries to client components, a `prefetch` helper, and a `caller` for [getting data in a Server Component](#getting-data-in-a-server-component). ```tsx title="trpc/server.tsx" import 'server-only'; // <-- ensure this file cannot be imported from the client import { createTRPCOptionsProxy, unstable_createHydrateClient, } from '@trpc/tanstack-react-query'; import type { TRPCQueryOptions } from '@trpc/tanstack-react-query'; import { headers } from 'next/headers'; import { cache } from 'react'; import { createTRPCContext } from './init'; import { makeQueryClient } from './query-client'; import { appRouter } from './routers/_app'; // IMPORTANT: Create a stable getter for the query client that // will return the same client during the same request. export const getQueryClient = cache(makeQueryClient); const createContext = async () => createTRPCContext({ headers: await headers() }); export const trpc = createTRPCOptionsProxy({ ctx: createContext, router: appRouter, queryClient: getQueryClient, }); // If your router is on a separate server, pass a client instead: // createTRPCOptionsProxy({ // client: createTRPCClient({ links: [httpLink({ url: '...' })] }), // queryClient: getQueryClient, // }); // Sends the request's queries to client components, pending ones too export const HydrateClient = unstable_createHydrateClient(getQueryClient); export function prefetch>>( queryOptions: T, ) { const queryClient = getQueryClient(); if (queryOptions.queryKey[1]?.type === 'infinite') { void queryClient.prefetchInfiniteQuery(queryOptions as any); } else { void queryClient.prefetchQuery(queryOptions); } } export const caller = appRouter.createCaller(createContext); ``` ### 7. Make API requests You're all set! You can now prefetch queries in server components and consume them in client components. > [!TIP] > To avoid repeating the procedure and input in client components, load the queries with `loadHandles` and pass the returned handles down. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md#nextjs-app-router). #### Prefetching in a Server Component `prefetch` starts the query without awaiting it, and `HydrateClient` sends it to the client still pending, so Next.js streams the result in when it resolves. Read a prefetch you don't `await` with `useSuspenseQuery` ([Leveraging Suspense](#leveraging-suspense)): with `useQuery`, the server can render the loading state while the browser already has the data, and React reports a hydration mismatch. For a component on `useQuery`, like the one below, wait for the data instead: `await getQueryClient().prefetchQuery(…)`. ```tsx title="app/page.tsx" import { getQueryClient, HydrateClient, trpc } from '~/trpc/server'; import { ClientGreeting } from './client-greeting'; export default async function Home() { await getQueryClient().prefetchQuery(trpc.hello.queryOptions({ text: 'world' })); return ( ); } ``` #### Using data in a Client Component ```tsx title="app/client-greeting.tsx" 'use client'; // <-- hooks can only be used in client components import { useQuery } from '@tanstack/react-query'; import { useTRPC } from '~/trpc/client'; export function ClientGreeting() { const trpc = useTRPC(); const greetingQuery = useQuery(trpc.hello.queryOptions({ text: 'world' })); switch (greetingQuery.status) { case 'pending': return
Loading...
; case 'error': return
Error: {greetingQuery.error.message}
; case 'success': return
{greetingQuery.data.greeting}
; } } ``` ## Leveraging Suspense You may prefer handling loading and error states using Suspense and Error Boundaries. You can do this by using the `useSuspenseQuery` hook. ```tsx title="app/page.tsx" import { HydrateClient, prefetch, trpc } from '~/trpc/server'; import { Suspense } from 'react'; import { ErrorBoundary } from 'react-error-boundary'; import { ClientGreeting } from './client-greeting'; export default async function Home() { prefetch(trpc.hello.queryOptions({ text: 'world' })); return ( Something went wrong}> Loading...}> ); } ``` ```tsx title="app/client-greeting.tsx" 'use client'; import { useSuspenseQuery } from '@tanstack/react-query'; import { useTRPC } from '~/trpc/client'; export function ClientGreeting() { const trpc = useTRPC(); const greetingQuery = useSuspenseQuery(trpc.hello.queryOptions({ text: 'world' })); return
{greetingQuery.data.greeting}
; } ``` ## Getting data in a Server Component If you need access to the data in a server component, we recommend using the server `caller` from [`trpc/server.tsx`](#6-create-a-trpc-caller-for-server-components) directly. Please note that this method is detached from your query client and does not store the data in the cache. This means that you cannot use the data in a server component and expect it to be available in the client. This is intentional and explained in more detail in the [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#data-ownership-and-revalidation) guide. ```tsx title="app/page.tsx" import { caller } from '~/trpc/server'; export default async function Home() { const greeting = await caller.hello({ text: 'world' }); // const greeting: { // greeting: string; // } return
{greeting.greeting}
; } ``` If you **really** need to use the data both on the server as well as inside client components and understand the tradeoffs explained in the [Advanced Server Rendering](https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr#data-ownership-and-revalidation) guide, you can use `fetchQuery` instead of `prefetch` to have the data both on the server as well as hydrating it down to the client: ```tsx title="app/page.tsx" import { getQueryClient, HydrateClient, trpc } from '~/trpc/server'; import { ClientGreeting } from './client-greeting'; export default async function Home() { const queryClient = getQueryClient(); const greeting = await queryClient.fetchQuery(trpc.hello.queryOptions({ text: 'world' })); // Do something with greeting on the server return ( ); } ``` ## Common mistakes - **Exporting only `POST` from the route handler.** Queries are sent as `GET` (unless the link sets `methodOverride: 'POST'`) and mutations as `POST`, so a missing export answers `405 Method Not Allowed`. - **Importing `trpc/server.tsx` into a client component.** `server-only` makes that a build error. Client components (`'use client'`) use `useTRPC()` from `trpc/client.tsx`. - **Prefetching with a different input than the client uses.** The input is part of the query key, so the client misses the prefetched data and fetches again. - **Prefetching inside `HydrateClient`.** It dehydrates the cache when it renders, so it only sends queries prefetched before that. A nested server component that prefetches needs its own `HydrateClient`. - **Sharing one `QueryClient` across requests.** On the server, only use the per-request `getQueryClient()` from `cache()`. - **Confusing the two `createTRPCContext`s.** The one in `trpc/init.ts` creates the context your procedures get; the one from `@trpc/tanstack-react-query` creates the React provider and hooks. ## Next steps - Learn about [Server Actions](https://trpc.io/docs/client/nextjs/server-actions.md) for defining tRPC-powered server actions - Share data with `generateMetadata`, and keep pages static or ISR, in [Static pages and metadata](https://trpc.io/docs/client/nextjs/static-pages.md) - Learn about [queries, mutations and invalidation](https://trpc.io/docs/client/tanstack-react-query/usage.md) in client components - Explore [server-side calls](https://trpc.io/docs/server/server-side-calls.md) for more advanced server-side patterns --- Source: https://trpc.io/docs/client/nextjs/server-actions # Server Actions > Define Next.js Server Actions as tRPC procedures with experimental_caller, so they get input validation, middlewares and metadata Server Actions allow you to define functions on the server and call them directly from client components, with the network layer abstracted away by the framework. By defining your server actions using tRPC procedures, you get all of tRPC's built-in features: input validation, authentication and authorization through middlewares, output validation, data transformers, and more. > [!NOTE] Info > The Server Actions integration uses the `experimental_` prefix and is still under active development. The API may change in future releases. ## Setting up Server Action procedures ### 1. Define a base procedure with `experimental_caller` Use `experimental_caller` on a procedure builder together with `experimental_nextAppDirCaller` to create procedures that can be invoked as plain functions (server actions). The `pathExtractor` option lets you identify procedures by metadata, which is useful for logging and observability since server actions don't have a router path like `user.byId`. ```ts title="server/trpc.ts" import { initTRPC, TRPCError } from '@trpc/server'; import { experimental_nextAppDirCaller } from '@trpc/server/adapters/next-app-dir'; interface Meta { span: string; } export const t = initTRPC.meta().create(); export const serverActionProcedure = t.procedure.experimental_caller( experimental_nextAppDirCaller({ pathExtractor: ({ meta }) => (meta as Meta)?.span ?? '', }), ); ``` ### 2. Add context via middleware Since server actions don't go through an HTTP adapter, there's no `createContext` to inject context. Instead, use a middleware to provide context such as session data: ```ts title="server/trpc.ts" import { initTRPC, TRPCError } from '@trpc/server'; import { experimental_nextAppDirCaller } from '@trpc/server/adapters/next-app-dir'; import { currentUser } from '../auth'; interface Meta { span: string; } export const t = initTRPC.meta().create(); export const serverActionProcedure = t.procedure .experimental_caller( experimental_nextAppDirCaller({ pathExtractor: ({ meta }) => (meta as Meta)?.span ?? '', }), ) .use(async (opts) => { const user = await currentUser(); return opts.next({ ctx: { user } }); }); ``` ### 3. Create a protected action procedure Add an authorization middleware to create a reusable base for actions that require authentication: ```ts title="server/trpc.ts" export const protectedAction = serverActionProcedure.use((opts) => { if (!opts.ctx.user) { throw new TRPCError({ code: 'UNAUTHORIZED', }); } return opts.next({ ctx: { ...opts.ctx, user: opts.ctx.user, // ensures type is non-nullable }, }); }); ``` ## Defining a server action Create a file with the `"use server"` directive and define your action using the procedure builder: ```ts title="app/_actions.ts" 'use server'; import { z } from 'zod'; import { protectedAction } from '../server/trpc'; export const createPost = protectedAction .input( z.object({ title: z.string(), }), ) .mutation(async (opts) => { // opts.ctx.user is typed as non-nullable // opts.input is typed as { title: string } // Create the post... }); ``` Because of `experimental_caller`, the procedure is now a plain async function that can be used as a server action. ## Calling from client components Import the server action and use it in a client component. Server actions work with both the `action` attribute for progressive enhancement and programmatic calls via `onSubmit`: ```tsx title="app/post-form.tsx" 'use client'; import { createPost } from '../_actions'; export function PostForm() { return (
{ e.preventDefault(); const title = new FormData(e.currentTarget).get('title') as string; await createPost({ title }); }} >
); } ``` ## Adding observability with metadata Use the `.meta()` method to tag actions for logging or tracing. The `span` property from the metadata is passed to `pathExtractor`, so it can be used by observability tools: ```ts title="app/_actions.ts" 'use server'; import { z } from 'zod'; import { protectedAction } from '../server/trpc'; export const createPost = protectedAction .meta({ span: 'create-post' }) .input( z.object({ title: z.string(), }), ) .mutation(async (opts) => { // ... }); ``` ## When to use Server Actions vs mutations Server Actions are not a replacement for all tRPC mutations. Consider the tradeoffs: - **Use Server Actions** when you want progressive enhancement (forms that work without JavaScript), or when the action doesn't need to update client-side React Query cache. - **Use `useMutation`** when you need to update the client-side cache, show optimistic updates, or manage complex loading/error states in the UI. You can incrementally adopt server actions alongside your existing tRPC API - there's no need to rewrite your entire API. --- Source: https://trpc.io/docs/client/nextjs/static-pages # Static pages and metadata > Share data between generateMetadata and the page, and prerender or revalidate (ISR) App Router pages with a context that reads no request data This page builds on the [App Router setup](https://trpc.io/docs/client/nextjs/app-router-setup.md). ## Data for `generateMetadata` {#generate-metadata} `generateMetadata` and the page render in the same request, so `getQueryClient()` returns the same query client in both. Fetch in `generateMetadata`, and the page's prefetch of the same query reuses the data instead of calling the procedure again: ```tsx title="app/page.tsx" import { getQueryClient, HydrateClient, trpc } from '~/trpc/server'; import { ClientGreeting } from './client-greeting'; export async function generateMetadata() { const greeting = await getQueryClient().fetchQuery( trpc.hello.queryOptions({ text: 'world' }), ); return { title: greeting.greeting }; } export default async function Home() { // Fresh within `staleTime`, so this reuses what `generateMetadata` fetched await getQueryClient().prefetchQuery(trpc.hello.queryOptions({ text: 'world' })); return ( ); } ``` ## Static and ISR pages {#static-pages} The context in [`trpc/server.tsx`](https://trpc.io/docs/client/nextjs/app-router-setup.md#6-create-a-trpc-caller-for-server-components) reads `headers()`, so a page that loads data through `trpc` renders on every request, whatever its `revalidate` or `generateStaticParams`. Next.js finds out during the build: `headers()` throws an error with a `digest` that tells Next.js to render the page on demand. To prerender a page and revalidate it (ISR), load its data with a second proxy whose context reads no request data: ```ts title="trpc/server.tsx" // For static and ISR pages: a context without the request's headers export const trpcStatic = createTRPCOptionsProxy({ ctx: () => createTRPCContext({ headers: new Headers() }), router: appRouter, queryClient: getQueryClient, }); ``` ```tsx title="app/greeting/[text]/page.tsx" import { getQueryClient, HydrateClient, trpcStatic } from '~/trpc/server'; import { ClientGreeting } from './client-greeting'; // Render the page again at most once a minute export const revalidate = 60; // Prerender these at build time; others render on their first visit export function generateStaticParams() { return [{ text: 'world' }]; } export default async function Page(props: { params: Promise<{ text: string }> }) { const { text } = await props.params; // `fetchQuery` throws if the procedure fails, unlike `prefetchQuery`: the build // fails, and a failed revalidation keeps serving the last good page await getQueryClient().fetchQuery(trpcStatic.hello.queryOptions({ text })); return ( ); } ``` ```tsx title="app/greeting/[text]/client-greeting.tsx" 'use client'; import { useSuspenseQuery } from '@tanstack/react-query'; import { useTRPC } from '~/trpc/client'; export function ClientGreeting(props: { text: string }) { const trpc = useTRPC(); const greetingQuery = useSuspenseQuery(trpc.hello.queryOptions({ text: props.text })); return
{greetingQuery.data.greeting}
; } ``` - Procedures get a context built without the request's headers, so anything your context reads from them, such as the signed-in user, is missing. Only public data belongs on these pages. - Don't use `trpc` and `trpcStatic` on the same page: they share the query client and the query keys. - The route's layouts must not read request data either. - `generateStaticParams` runs at build time, outside any request. If it reads its params from a procedure, use `trpcStatic` there too. --- Source: https://trpc.io/docs/client/nextjs/pages-router/setup # Set up with Next.js Pages Router > > [!WARNING] Caution > This guide is for the **Next.js Pages Router**. If you are using the **Next.js App Router**, see the [App Router setup guide](https://trpc.io/docs/client/nextjs/app-router-setup.md) instead. The Pages Router uses the same client as the App Router: the [TanStack React Query integration](https://trpc.io/docs/client/tanstack-react-query.md) (`@trpc/tanstack-react-query`). You mount its provider in `_app`, and prefetch a page's queries in `getServerSideProps` or `getStaticProps` when you want them in the first HTML. > [!WARNING] Deprecated > `createTRPCNext`, `withTRPC` and `ssr: true` from `@trpc/next` are deprecated. They're built on the [classic React Query integration](https://trpc.io/docs/client/react.md), which only gets bug fixes and will be removed in the next major version of tRPC. To move an existing app, see [Moving from `createTRPCNext`](#moving-from-createtrpcnext). ## Recommended file structure We recommend a file structure like this one, although it is not enforced by tRPC. The rest of this page will take you through the process of adding tRPC in to this structure. ```graphql . β”œβ”€β”€ prisma # <-- if prisma is added β”‚ └── [..] β”œβ”€β”€ src β”‚ β”œβ”€β”€ pages β”‚ β”‚ β”œβ”€β”€ _app.tsx # <-- mount the providers here β”‚ β”‚ β”œβ”€β”€ api β”‚ β”‚ β”‚ └── trpc β”‚ β”‚ β”‚ └── [trpc].ts # <-- tRPC HTTP handler β”‚ β”‚ └── [..] β”‚ β”œβ”€β”€ server β”‚ β”‚ β”œβ”€β”€ routers β”‚ β”‚ β”‚ β”œβ”€β”€ _app.ts # <-- main app router β”‚ β”‚ β”‚ β”œβ”€β”€ post.ts # <-- sub routers β”‚ β”‚ β”‚ └── [..] β”‚ β”‚ β”œβ”€β”€ context.ts # <-- create app context β”‚ β”‚ └── trpc.ts # <-- procedure helpers β”‚ └── utils β”‚ β”œβ”€β”€ query-client.ts # <-- shared QueryClient factory β”‚ └── trpc.ts # <-- your typesafe tRPC hooks └── [..] ``` ## Add tRPC to existing Next.js project ### 1. Install deps ```package-install @trpc/server @trpc/client @trpc/tanstack-react-query @tanstack/react-query@latest zod ``` ### 2. Enable strict mode If you want to use Zod for input validation, make sure you have enabled strict mode in your `tsconfig.json`: ```diff title="tsconfig.json" "compilerOptions": { + "strict": true } ``` If strict mode is too harsh, you'll at least want to enable `strictNullChecks`: ```diff title="tsconfig.json" "compilerOptions": { + "strictNullChecks": true } ``` ### 3. Create a tRPC router Initialize your tRPC backend in `src/server/trpc.ts` using the `initTRPC` function, and create your first router. We're going to make a simple "hello world" router and procedure here - but for deeper information on creating your tRPC API you should refer to: - the [Quickstart guide](https://trpc.io/docs/quickstart.md) and [Backend usage docs](https://trpc.io/docs/server/overview.md) for tRPC information - the [Next.js Adapter docs](https://trpc.io/docs/server/adapters/nextjs.md) for mounting tRPC within your Next.js server.
View sample backend ```ts title="server/trpc.ts" import { initTRPC } from '@trpc/server'; // Avoid exporting the entire t-object // since it's not very descriptive. // For instance, the use of a t variable // is common in i18n libraries. const t = initTRPC.create(); // Base router and procedure helpers export const router = t.router; export const procedure = t.procedure; ```
```ts title="server/routers/_app.ts" import { z } from 'zod'; import { procedure, router } from '../trpc'; export const appRouter = router({ hello: procedure .input( z.object({ text: z.string(), }), ) .query((opts) => { return { greeting: `hello ${opts.input.text}`, }; }), }); // export type definition of API export type AppRouter = typeof appRouter; ```
```ts title="pages/api/trpc/[trpc].ts" import * as trpcNext from '@trpc/server/adapters/next'; import { appRouter } from '../../../server/routers/_app'; // export API handler // @link https://trpc.io/docs/server/adapters export default trpcNext.createNextApiHandler({ router: appRouter, createContext: () => ({}), }); ```
> [!NOTE] > The backend above is using the [recommended file structure](#recommended-file-structure), but you can keep it simple and put everything in [an API handler directly](https://github.com/trpc/trpc/blob/db643ba428f4eaf75fcfeef13a53d29f446ee567/examples/next-minimal-starter/src/pages/api/trpc/%5Btrpc%5D.ts) if you prefer. ### 4. Create a Query Client factory Create `utils/query-client.ts`. Both `_app` and the pages that prefetch on the server use it. ```ts title="utils/query-client.ts" import { QueryClient } from '@tanstack/react-query'; export function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { // keep server-rendered data fresh for a while, so the // client doesn't fetch it again as soon as the page loads staleTime: 30 * 1000, }, }, }); } ``` ### 5. Create tRPC hooks Use `createTRPCContext` to create a provider and a `useTRPC` hook from your API's type signature. ```ts title="utils/trpc.ts" import { createTRPCContext } from '@trpc/tanstack-react-query'; import type { AppRouter } from '../server/routers/_app'; export const { TRPCProvider, useTRPC } = createTRPCContext(); ``` ### 6. Configure `_app.tsx` Create the query client and the tRPC client once per app, and wrap every page in the providers. `HydrationBoundary` puts the queries a page prefetched on the server, which it returns as `trpcState`, into the cache. ```tsx title="pages/_app.tsx" import type { DehydratedState } from '@tanstack/react-query'; import { HydrationBoundary, QueryClientProvider } from '@tanstack/react-query'; import { createTRPCClient, httpBatchLink } from '@trpc/client'; import type { AppProps } from 'next/app'; import { useState } from 'react'; import type { AppRouter } from '../server/routers/_app'; import { makeQueryClient } from '../utils/query-client'; import { TRPCProvider } from '../utils/trpc'; export default function App({ Component, pageProps, }: AppProps<{ trpcState?: DehydratedState }>) { const [queryClient] = useState(makeQueryClient); const [trpcClient] = useState(() => createTRPCClient({ links: [ httpBatchLink({ // transformer: superjson, <-- if you use a data transformer url: '/api/trpc', }), ], }), ); return ( ); } ``` The client only calls the API from the browser, so a relative URL is enough. On the server, pages call your procedures directly, as [Server-Side Rendering](https://trpc.io/docs/client/nextjs/pages-router/ssr.md) shows. ### 7. Make an API request You're all set! Get the options for a query from `useTRPC()`, and pass them to TanStack React Query's hooks. For more, see [TanStack React Query usage](https://trpc.io/docs/client/tanstack-react-query/usage.md). ```tsx title="pages/index.tsx" import { useQuery } from '@tanstack/react-query'; import { useTRPC } from '../utils/trpc'; export default function IndexPage() { const trpc = useTRPC(); const helloQuery = useQuery(trpc.hello.queryOptions({ text: 'client' })); switch (helloQuery.status) { case 'pending': return

Loading...

; case 'error': return

Error: {helloQuery.error.message}

; case 'success': return

{helloQuery.data.greeting}

; } } ``` This page fetches in the browser. To put the data in the first HTML, prefetch it in [`getServerSideProps`](https://trpc.io/docs/client/nextjs/pages-router/ssr.md) or [`getStaticProps`](https://trpc.io/docs/client/nextjs/pages-router/ssg.md). ## Using a data transformer Next.js sends page props as JSON, and checks that they are. So without a transformer, the queries you prefetch can only hold JSON values, in their inputs as well as their results: a `Date` or an `undefined` field makes `getServerSideProps` fail. If your router uses a [data transformer](https://trpc.io/docs/server/data-transformers.md) such as superjson, run the whole prefetched cache through it. In `getServerSideProps` or `getStaticProps`, return `trpcState: superjson.serialize(dehydrate(queryClient))`, as the [SSG example](https://trpc.io/docs/client/nextjs/pages-router/ssg.md#fetch-data-in-getstaticprops) does. Then read it back with a hook: ```ts title="utils/use-trpc-state.ts" import type { DehydratedState } from '@tanstack/react-query'; import { useMemo } from 'react'; import superjson from 'superjson'; export type TRPCState = ReturnType; export function useTRPCState(trpcState: TRPCState | undefined) { return useMemo( () => trpcState && superjson.deserialize(trpcState), [trpcState], ); } ``` In the `_app` from [step 6](#6-configure-_apptsx), change three things: - Type the props as `AppProps<{ trpcState?: TRPCState }>`. - Pass `transformer: superjson` to `httpBatchLink`. - Call `const trpcState = useTRPCState(pageProps.trpcState)`, and pass `trpcState` to `HydrationBoundary` instead of `pageProps.trpcState`. ## Moving from `createTRPCNext` `createTRPCNext` combined the classic React Query hooks with a higher-order component for `_app`. Here's what replaces each part: | `@trpc/next` | `@trpc/tanstack-react-query` | | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `createTRPCNext({ config })` | `createTRPCContext()`, plus a `createTRPCClient` with your links in `_app` | | `trpc.withTRPC(MyApp)` | `QueryClientProvider`, `TRPCProvider` and `HydrationBoundary` in `_app`, as in [step 6](#6-configure-_apptsx) | | `trpc.post.byId.useQuery(input)` | `useQuery(trpc.post.byId.queryOptions(input))`, with `trpc` from `useTRPC()` | | `trpc.useUtils()` | `useQueryClient()` with `trpc.post.byId.queryKey()` or `queryFilter()` | | `ssr: true` and `ssrPrepass` | No direct replacement. Prefetch each page's queries in [`getServerSideProps`](https://trpc.io/docs/client/nextjs/pages-router/ssr.md) | | `responseMeta` | Set the status and headers in [`getServerSideProps`](https://trpc.io/docs/client/nextjs/pages-router/ssr.md#set-the-status-and-cache-headers) | | `config({ ctx })` forwarding the request headers | Pass a context built from `context.req` to `createTRPCOptionsProxy` in `getServerSideProps` | | `createServerSideHelpers` (`@trpc/react-query/server`) | `createTRPCOptionsProxy` with a query client, then `dehydrate(queryClient)`. See [Server-Side Helpers](https://trpc.io/docs/client/nextjs/pages-router/server-side-helpers.md) | | `abortOnUnmount` in `config` | `trpc: { abortOnUnmount: true }` on each query. See [Aborting Procedure Calls](https://trpc.io/docs/client/nextjs/pages-router/aborting-procedure-calls.md) | | `queryClientConfig` | The options you pass to `new QueryClient()` in `makeQueryClient` | The [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md) covers the hooks in detail. Its [codemod](https://trpc.io/docs/client/tanstack-react-query/migrating.md#codemod-migration) moves the setup, `_app` and the hooks for you. `ssr: true` rendered the page over and over until no query was fetching. With `getServerSideProps`, you pick which queries run on the server, and Next.js keeps [Automatic Static Optimization](https://nextjs.org/docs/pages/building-your-application/rendering/automatic-static-optimization) for pages that don't need them. ## Common mistakes - **Sharing one `QueryClient` across requests.** Make it in `_app` with `useState`, and make a new one in each `getServerSideProps` or `getStaticProps`. A query client at module scope would hand one user's data to the next. - **Returning the dehydrated state under another key.** `_app` reads `pageProps.trpcState`, so return `{ props: { trpcState: dehydrate(queryClient) } }`. Otherwise the client fetches every query again. - **Prefetching with a different input than the page uses.** The input is part of the query key, so the page misses the prefetched data and fetches again. - **Prefetching values JSON can't hold.** Next.js sends page props as JSON, so a `Date` or an `undefined` field in a query's input or result makes the page fail. Run the prefetched cache through a [data transformer](#using-a-data-transformer). - **Mixing in App Router setup.** `HydrateClient` and `server-only` are for the App Router. In the Pages Router, prefetch in `getServerSideProps` or `getStaticProps` instead. ## Next steps Browse the rest of the docs to learn more about things like [authorization](https://trpc.io/docs/server/authorization.md), [middlewares](https://trpc.io/docs/server/middlewares.md), and [error handling](https://trpc.io/docs/server/error-handling.md). You can also find information about [queries, mutations and invalidation](https://trpc.io/docs/client/tanstack-react-query/usage.md) in the TanStack React Query docs. --- Source: https://trpc.io/docs/client/nextjs/pages-router/ssr # Server-Side Rendering > Prefetch a page's tRPC queries in getServerSideProps with createTRPCOptionsProxy, build the context from the request, and set the status and cache headers To render a page's data on the server, prefetch its queries in `getServerSideProps`. Next.js then renders the page with the data in the cache, so it's in the first HTML, and the client doesn't fetch it again. This page builds on the [Pages Router setup](https://trpc.io/docs/client/nextjs/pages-router/setup.md). > [!WARNING] Deprecated > `ssr: true` and `ssrPrepass` from `@trpc/next` are deprecated, along with `createTRPCNext`. They rendered every page over and over until no query was fetching. Nothing does that for you now: prefetch each page's queries in `getServerSideProps` instead. You choose what runs on the server, and pages without `getServerSideProps` stay static. ## Prefetch in `getServerSideProps` In `getServerSideProps`, make a query client and a tRPC proxy that calls your router directly, with no HTTP request. Prefetch the queries the page needs, and return the cache as `trpcState`. `_app`'s `HydrationBoundary` puts it into the client's cache. ```tsx title="pages/posts/[id].tsx" import { dehydrate, useQuery } from '@tanstack/react-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { GetServerSidePropsContext, InferGetServerSidePropsType, } from 'next'; import { createContext } from '../../server/context'; import { appRouter } from '../../server/routers/_app'; import { makeQueryClient } from '../../utils/query-client'; import { useTRPC } from '../../utils/trpc'; export async function getServerSideProps( context: GetServerSidePropsContext<{ id: string }>, ) { const id = context.params?.id as string; const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: await createContext({ headers: context.req.headers }), queryClient, }); await queryClient.prefetchQuery(trpc.post.byId.queryOptions({ id })); return { props: { trpcState: dehydrate(queryClient), id, }, }; } export default function PostPage( props: InferGetServerSidePropsType, ) { const trpc = useTRPC(); const postQuery = useQuery(trpc.post.byId.queryOptions({ id: props.id })); switch (postQuery.status) { case 'pending': return

Loading...

; case 'error': return

Error: {postQuery.error.message}

; case 'success': return (

{postQuery.data.title}

{postQuery.data.text}

); } } ``` The page reads the query as it would without prefetching, so `status` is `'success'` on the first render. Use the same input in both places: it's part of the query key. > [!TIP] > To stop the two inputs from drifting apart, return a **handle** instead of the `id`. With `loadHandles` from `@trpc/tanstack-react-query/unstable-handles`, `const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, { id }) })` waits for the data like `prefetchQuery`. The server's cache starts empty on each request, so it also rejects like `fetchQuery` if the query fails. Return `props: { trpcState: dehydrate(queryClient), ...handles }`, and the page reads it with `useQuery(fromHandle(trpc, props.post))`. A handle is plain JSON when its input is. If the input has a `Date` or another value your transformer handles, run the handles through the transformer too, as [Using a data transformer](https://trpc.io/docs/client/nextjs/pages-router/setup.md#using-a-data-transformer) does for the dehydrated state. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). `prefetchQuery` never throws, and the cache only sends queries that succeeded, so a failed query fetches again in the browser. To act on an error on the server, use `fetchQuery`, which returns the data or throws. See [Set the status and cache headers](#set-the-status-and-cache-headers). ### Build the context from the request The proxy calls your procedures in the same process, so there's no URL to set and no headers to forward. Build the context from `context.req` instead, as the API handler does. Sharing one `createContext` that only needs the headers keeps the two the same: ```ts title="server/context.ts" import type { IncomingHttpHeaders } from 'node:http'; import { getUserFromCookie } from './auth'; export async function createContext(opts: { headers: IncomingHttpHeaders }) { // verify the session here: headers come from the client, so don't // trust a user ID that's simply sent in one const user = await getUserFromCookie(opts.headers.cookie); return { user }; } ``` ```ts title="pages/api/trpc/[trpc].ts" import * as trpcNext from '@trpc/server/adapters/next'; import { createContext } from '../../../server/context'; import { appRouter } from '../../../server/routers/_app'; export default trpcNext.createNextApiHandler({ router: appRouter, createContext: (opts) => createContext({ headers: opts.req.headers }), }); ```
If your API runs on another server Pass a tRPC client to `createTRPCOptionsProxy` instead of the router. The request now goes over HTTP, so it needs the API's full URL, and you forward the headers the API needs, such as the cookie: ```ts title="pages/posts/[id].tsx" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { GetServerSidePropsContext } from 'next'; import type { AppRouter } from '../../server/routers/_app'; import { makeQueryClient } from '../../utils/query-client'; export async function getServerSideProps(context: GetServerSidePropsContext) { const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ client: createTRPCClient({ links: [ httpBatchLink({ url: 'https://api.example.com/trpc', headers: () => ({ cookie: context.req.headers.cookie }), }), ], }), queryClient, }); // prefetch and dehydrate as above } ```
## Set the status and cache headers `getServerSideProps` gets the response as `context.res`, so you set headers on it directly. To send a 404 when a post doesn't exist, use `fetchQuery`, catch the `TRPCError`, and return `notFound`: ```tsx title="pages/posts/[id].tsx" import { dehydrate } from '@tanstack/react-query'; import { TRPCError } from '@trpc/server'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { GetServerSidePropsContext } from 'next'; import { appRouter } from '../../server/routers/_app'; import { makeQueryClient } from '../../utils/query-client'; export async function getServerSideProps( context: GetServerSidePropsContext<{ id: string }>, ) { const id = context.params?.id as string; const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient, }); try { await queryClient.fetchQuery(trpc.post.byId.queryOptions({ id })); } catch (cause) { if (cause instanceof TRPCError && cause.code === 'NOT_FOUND') { return { notFound: true }; } throw cause; } // cache the page for 1 day, and revalidate it once a second at most const ONE_DAY_IN_SECONDS = 60 * 60 * 24; context.res.setHeader( 'cache-control', `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`, ); return { props: { trpcState: dehydrate(queryClient), id, }, }; } ``` Only cache pages that look the same for everyone. If the page depends on the user's cookie, leave out the `cache-control` header. See also the general [Response Caching](https://trpc.io/docs/server/caching.md) docs. ### API Response Caching with Next.js Adapter You can also use `responseMeta` on the Next.js API handler to cache API responses directly: ```tsx title="pages/api/trpc/[trpc].ts" import { initTRPC } from '@trpc/server'; import * as trpcNext from '@trpc/server/adapters/next'; export const createContext = async ({ req, res, }: trpcNext.CreateNextContextOptions) => { return { req, res, }; }; type Context = Awaited>; export const t = initTRPC.context().create(); export const appRouter = t.router({ public: t.router({ slowQueryCached: t.procedure.query(async (opts) => { await new Promise((resolve) => setTimeout(resolve, 5000)); return { lastUpdated: new Date().toJSON(), }; }), }), }); export type AppRouter = typeof appRouter; export default trpcNext.createNextApiHandler({ router: appRouter, createContext, responseMeta(opts) { const { ctx, paths, errors, type } = opts; // assuming you have all your public routes with the keyword `public` in them const allPublic = paths && paths.every((path) => path.includes('public')); // checking that no procedures errored const allOk = errors.length === 0; // checking we're doing a query request const isQuery = type === 'query'; if (ctx?.res && allPublic && allOk && isQuery) { // cache request for 1 day + revalidate once every second const ONE_DAY_IN_SECONDS = 60 * 60 * 24; return { headers: new Headers([ [ 'cache-control', `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`, ], ]), }; } return {}; }, }); ``` ## FAQ ### Q: Why does the client still fetch data the server prefetched? TanStack React Query refetches stale data when a component mounts, when the window regains focus, and when the network reconnects. The query client from the [setup](https://trpc.io/docs/client/nextjs/pages-router/setup.md#4-create-a-query-client-factory) keeps data fresh for 30 seconds with `staleTime`, so the first render uses what the server sent. Raise `staleTime` to fetch less, or see [SSG](https://trpc.io/docs/client/nextjs/pages-router/ssg.md#stop-the-client-from-refetching) to turn refetching off. ### Q: Can I use `useSuspenseQuery`? Yes, for queries the page prefetched. A query that isn't in the cache suspends during the server render too, and the server can't reach your API's relative URL. Prefetch it in `getServerSideProps`, or use `useQuery`, which only fetches in the browser. --- Source: https://trpc.io/docs/client/nextjs/pages-router/ssg # Static Site Generation > Prefetch tRPC queries in getStaticProps with createTRPCOptionsProxy and dehydrate, and stop the client from refetching them To build a page's data into static HTML, prefetch its queries in `getStaticProps`. It works like [prefetching in `getServerSideProps`](https://trpc.io/docs/client/nextjs/pages-router/ssr.md), except that it runs at build time, or when Next.js revalidates the page, so there's no request. This page builds on the [Pages Router setup](https://trpc.io/docs/client/nextjs/pages-router/setup.md). ## Fetch data in `getStaticProps` Make a query client and a tRPC proxy that calls your router directly, prefetch the queries, and return the cache as `trpcState`. There's no request to build the context from, so pass one that doesn't need it. This example uses superjson, so the post's `createdAt` reaches the page as a `Date`. It needs the matching `_app` from [Using a data transformer](https://trpc.io/docs/client/nextjs/pages-router/setup.md#using-a-data-transformer). ```tsx title="pages/posts/[id].tsx" import { dehydrate, useQuery } from '@tanstack/react-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { GetStaticPaths, GetStaticPropsContext, InferGetStaticPropsType, } from 'next'; import { prisma } from '../../server/context'; import superjson from 'superjson'; import { appRouter } from '../../server/routers/_app'; import { makeQueryClient } from '../../utils/query-client'; import { useTRPC } from '../../utils/trpc'; export async function getStaticProps( context: GetStaticPropsContext<{ id: string }>, ) { const id = context.params?.id as string; const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient, }); await queryClient.prefetchQuery(trpc.post.byId.queryOptions({ id })); return { props: { trpcState: superjson.serialize(dehydrate(queryClient)), id, }, revalidate: 1, }; } export const getStaticPaths: GetStaticPaths = async () => { const posts = await prisma.post.findMany({ select: { id: true, }, }); return { paths: posts.map((post) => ({ params: { id: post.id, }, })), // https://nextjs.org/docs/pages/api-reference/functions/get-static-paths#fallback-blocking fallback: 'blocking', }; }; export default function PostViewPage( props: InferGetStaticPropsType, ) { const trpc = useTRPC(); const postQuery = useQuery(trpc.post.byId.queryOptions({ id: props.id })); switch (postQuery.status) { case 'pending': return

Loading...

; case 'error': return

Error: {postQuery.error.message}

; case 'success': { const post = postQuery.data; return (

{post.title}

Created {post.createdAt.toLocaleDateString('en-us')}

{post.text}

); } } } ``` ## Stop the client from refetching TanStack React Query refetches stale data on the client when a component mounts, when the window regains focus, and when the network reconnects. If you only want the data from `getStaticProps`, for instance because your API is rate-limited, turn that off. Per query: ```tsx import { useQuery } from '@tanstack/react-query'; import { useTRPC } from './utils/trpc'; function Example() { const trpc = useTRPC(); const exampleQuery = useQuery( trpc.example.queryOptions(undefined, { refetchOnMount: false, refetchOnWindowFocus: false, refetchOnReconnect: false, }), ); } ``` Or for every query, in the query client: ```ts title="utils/query-client.ts" import { QueryClient } from '@tanstack/react-query'; export function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { refetchOnMount: false, refetchOnWindowFocus: false, refetchOnReconnect: false, }, }, }); } ``` Be careful with the second one if your app mixes static and dynamic queries. --- Source: https://trpc.io/docs/client/nextjs/pages-router/server-side-helpers # Server-Side Helpers > Prefetch or fetch tRPC queries in getServerSideProps and getStaticProps with createTRPCOptionsProxy and a query client, then pass them to the page as trpcState To run queries on the server in `getServerSideProps` or `getStaticProps`, make a query client and pass it to `createTRPCOptionsProxy` from `@trpc/tanstack-react-query`. The proxy gives you the same `queryOptions` as `useTRPC()` in a component. You prefetch them into the query client, then send its cache to the page, so the page doesn't have to fetch them again. > [!WARNING] Deprecated > `createServerSideHelpers` from `@trpc/react-query/server` belongs to the [classic React Query integration](https://trpc.io/docs/client/react.md), which only gets bug fixes and will be removed in the next major version of tRPC. Use `createTRPCOptionsProxy` instead, as below. ## Create the proxy There are two ways to create it, depending on where your router runs. ### 1. Internal router Use this when your router is in the same Next.js app. The proxy calls your procedures directly, with no HTTP request, as [server-side calls](https://trpc.io/docs/server/server-side-calls.md) do. So pass it a context: build it from `context.req` in `getServerSideProps`, as [SSR](https://trpc.io/docs/client/nextjs/pages-router/ssr.md#build-the-context-from-the-request) shows. In `getStaticProps` there's no request, so the context can't need one. The ["inner" and "outer" context](https://trpc.io/docs/server/context.md) pattern helps here. ```ts import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import { createContext } from './server/context'; import { appRouter } from './server/routers/_app'; import { makeQueryClient } from './utils/query-client'; export async function getStaticProps() { const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: await createContext(), queryClient, }); // ... } ``` ### 2. External router Use this when your API runs on another server. Pass a tRPC client instead of the router: ```ts import { createTRPCClient, httpBatchLink } from '@trpc/client'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { AppRouter } from './server/router'; import { makeQueryClient } from './utils/query-client'; export async function getStaticProps() { const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ client: createTRPCClient({ links: [ httpBatchLink({ url: 'http://localhost:3000/api/trpc', }), ], }), queryClient, }); // ... } ``` Make the query client and the proxy inside `getServerSideProps` or `getStaticProps`, so each call gets new ones. A query client at module scope would share one user's data with the next. ## Prefetch, fetch and dehydrate Run the queries with the query client's methods: - `queryClient.prefetchQuery(trpc.post.byId.queryOptions(input))` puts the result in the cache. It never throws and returns nothing. - `queryClient.fetchQuery(trpc.post.byId.queryOptions(input))` also caches the result, but returns it, and throws if the query fails. - `prefetchInfiniteQuery` and `fetchInfiniteQuery` do the same with `trpc.post.list.infiniteQueryOptions(input)`. Use `prefetchQuery` for data the page shows, and `fetchQuery` when you need the result on the server, for instance to return `notFound`. Then send the cache to the page with `dehydrate`: ```ts // In getServerSideProps / getStaticProps: const props = { // `_app` reads this key trpcState: dehydrate(queryClient), }; ``` These are TanStack React Query's own functions. See [their docs](https://tanstack.com/query/v5/docs/framework/react/guides/prefetching) for more. > [!TIP] > `loadHandles` from `@trpc/tanstack-react-query/unstable-handles` can also start queries with this proxy and return **handles** to them: `const [handles] = await loadHandles(trpc, { post: ensureEntry(trpc.post.byId, input) })`. Spread the handles into `props` next to `trpcState`, and the page reads one with `useQuery(fromHandle(trpc, props.post))`, so it can't ask for a different input than the server used. A handle is plain JSON when its input is. If the input has a `Date` or another value your transformer handles, run the handles through the transformer too, as you do the dehydrated state. See [Prefetching with handles](https://trpc.io/docs/client/tanstack-react-query/handles.md). Coming from `createServerSideHelpers`, `helpers.post.byId.prefetch(input)` is now `queryClient.prefetchQuery(trpc.post.byId.queryOptions(input))`, `fetch` is `fetchQuery`, and `helpers.dehydrate()` is `dehydrate(queryClient)`. If you passed a `transformer` to the helpers, run the dehydrated state through it yourself, as [Using a data transformer](https://trpc.io/docs/client/nextjs/pages-router/setup.md#using-a-data-transformer) shows. ## Next.js example ```tsx title="pages/posts/[id].tsx" import { dehydrate, useQuery } from '@tanstack/react-query'; import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query'; import type { GetServerSidePropsContext, InferGetServerSidePropsType, } from 'next'; import { appRouter } from '../../server/routers/_app'; import { makeQueryClient } from '../../utils/query-client'; import { useTRPC } from '../../utils/trpc'; export async function getServerSideProps( context: GetServerSidePropsContext<{ id: string }>, ) { const id = context.params?.id as string; const queryClient = makeQueryClient(); const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient, }); await queryClient.prefetchQuery(trpc.post.byId.queryOptions({ id })); return { props: { trpcState: dehydrate(queryClient), id, }, }; } export default function PostViewPage( props: InferGetServerSidePropsType, ) { const trpc = useTRPC(); const postQuery = useQuery(trpc.post.byId.queryOptions({ id: props.id })); switch (postQuery.status) { case 'pending': return

Loading...

; case 'error': return

Error: {postQuery.error.message}

; case 'success': return (

{postQuery.data.title}

{postQuery.data.text}

); } } ``` --- Source: https://trpc.io/docs/client/nextjs/pages-router/aborting-procedure-calls # Aborting Procedure Calls > Cancel in-flight requests when a component unmounts with the abortOnUnmount option on a query By default, tRPC doesn't cancel a request when the component that made it unmounts. To cancel it, set `abortOnUnmount` in the `trpc` option of the query: ```tsx title="pages/posts/[id].tsx" import { skipToken, useQuery } from '@tanstack/react-query'; import { useRouter } from 'next/router'; import { useTRPC } from '../../utils/trpc'; export default function PostViewPage() { const router = useRouter(); // `query.id` is undefined until the router is ready const id = router.query.id; const trpc = useTRPC(); const postQuery = useQuery( trpc.post.byId.queryOptions(typeof id === 'string' ? { id } : skipToken, { trpc: { abortOnUnmount: true }, }), ); switch (postQuery.status) { case 'pending': return

Loading...

; case 'error': return

Error: {postQuery.error.message}

; case 'success': return

{postQuery.data.title}

; } } ``` There's no global switch: `createTRPCContext()` takes no options, so set it on each query that needs it. It works for `queryOptions` and `infiniteQueryOptions`, since TanStack React Query only cancels queries. With `httpBatchLink` or `httpBatchStreamLink`, the HTTP request only stops once every query in its batch is cancelled. Cancelling one query alone just drops its result. To stop the request for a single query, send it through `httpLink`, for instance with a [`splitLink`](https://trpc.io/docs/client/links/splitLink.md). > [!NOTE] > `createTRPCNext`'s `abortOnUnmount` in `config` set this for every query. Like the rest of `createTRPCNext`, it's deprecated. See [Moving from `createTRPCNext`](https://trpc.io/docs/client/nextjs/pages-router/setup.md#moving-from-createtrpcnext). --- Source: https://trpc.io/docs/client/nextjs/starter-projects # Starter Projects > Get started quickly with one of the example projects! Copy the snippet from _Quick start with `create-next-app`_ in the below list to clone the project. ## App Router
Description Links
Minimal Next.js App Router starter with @trpc/tanstack-react-query: a server-component prefetch, a query and a subscription.

Quick start with create-next-app npx create-next-app --example https://github.com/trpc/examples-next-minimal-starter trpc-minimal-starter
## Pages Router
Description URL Links
Next.js starter with Prisma, E2E testing, & ESLint.

Quick start with create-next-app yarn create next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter
nextjs.trpc.io
zART-stack example (zero-API, TypeScript, React).
Monorepo setup with React Native, Next.js, & Prisma

Quick start with git clone git clone git@github.com:KATT/zart.git
n/a
Next.js TodoMVC-example with SSG & Prisma.

Quick start with create-next-app yarn create next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-todomvc trpc-todo
todomvc.trpc.io
--- Source: https://trpc.io/docs/openapi # OpenAPI (alpha) > > [!WARNING] Caution > This package is in alpha. APIs may change without notice. > > It requires TypeScript 7.1-beta or later to be installed. To use typescript <7.0, you will need to either install `@trpc/openapi@11.28.2-alpha` The `@trpc/openapi` package generates an OpenAPI 3.1 specification from your tRPC router. Use the spec to: - Generate a typed API client in any language - Call tRPC endpoints via HTTP tools like Postman or Insomnia - Enable AI agent integrations such as MCP servers ## Install ```bash pnpm add @trpc/openapi ``` > [!NOTE] > `@trpc/openapi` is currently versioned like 11.x.x-alpha, and should work with any recent tRPC v11 version, but as always we recommend aligning the version numbers ## Adapting your tRPC setup The generator works with your existing router β€” no annotations or decorators required. A few things to be aware of: - **No output types needed** β€” unlike other OpenAPI tools, `.output()` schemas are optional. The generator infers return types from your implementation automatically. - **Transformers** β€” if your server uses a [data transformer](https://trpc.io/docs/server/data-transformers.md), your OpenAPI clients must use the same one. See [Transformers](#transformers) for setup and cross-language options. - **Subscriptions** β€” currently excluded from the generated spec. SSE support is planned. - **Descriptions** β€” Zod `.describe()` calls and JSDoc comments on types, routers, and procedures, all become `description` fields in the spec. ## Generate the spec ### CLI ```bash pnpm exec trpc-openapi ./src/server/router.ts ``` | Option | Default | Description | | --------------------- | -------------- | -------------------------------------------------------------------- | | `-e, --export ` | `AppRouter` | Name of the exported router type | | `-o, --output ` | `openapi.json` | Output file path | | `--title ` | `tRPC API` | OpenAPI `info.title` | | `--version ` | `0.0.0` | OpenAPI `info.version` | | `--server-url ` | | Base URL (including any prefix), e.g. `https://api.example.com/trpc` | ```bash pnpm exec trpc-openapi ./src/server/router.ts -o api.json --title "My API" --version 1.0.0 --server-url https://api.example.com/trpc ``` ### Programmatic ```ts title="scripts/generate-openapi.ts" import { generateOpenAPIDocument } from '@trpc/openapi'; const doc = await generateOpenAPIDocument('./src/server/router.ts', { exportName: 'AppRouter', title: 'My API', version: '1.0.0', servers: [{ url: 'https://api.example.com/trpc' }], }); ``` The generator builds the spec by statically analysing your router's TypeScript types. It also tries to import the router file to pick up Zod `.describe()` text, and carries on from the types alone if that import fails. Because of that, point it at a module that only defines the router, not one that starts your server. ## Generate a client from the spec Any OpenAPI client generator should work, but the most tested integration is with [Hey API](https://heyapi.dev/openapi-ts/get-started). A generated client will produce typed SDK functions matching your tRPC procedures: - **Queries** β†’ `GET /procedure.path` - **Mutations** β†’ `POST /procedure.path` - **Subscriptions** are ignored (SSE coming soon) ### Hey API (TypeScript) [Hey API Documentation](https://heyapi.dev/) ```bash pnpm add @trpc/openapi @hey-api/openapi-ts@next ``` Out of the box, an OpenAPI-generated client won't know about your transformer setup or how to encode query parameters. The `@trpc/openapi/heyapi` package provides a `configureTRPCHeyApiClient` helper that bridges this gap β€” it configures request serialisation, response parsing, and error deserialization so the generated SDK works correctly with tRPC endpoints. #### Without a transformer You can generate your client using Hey API's CLI or programmatic API in this case ```bash pnpm exec openapi-ts -i openapi.json -o ./generated ``` Next a little configuration is required at runtime: ```ts title="src/usage.ts" import { configureTRPCHeyApiClient } from '@trpc/openapi/heyapi'; import { client } from './generated/client.gen'; import { Sdk } from './generated/sdk.gen'; configureTRPCHeyApiClient(client, { baseUrl: 'http://localhost:3000', }); const sdk = new Sdk({ client }); const result = await sdk.greeting({ query: { input: { name: 'World' } } }); const user = await sdk.user.create({ body: { name: 'Bob', age: 30 } }); ``` #### With a transformer (superjson, devalue, etc.) > [!WARNING] > If your backend uses a [data transformer](https://trpc.io/docs/server/data-transformers.md) like `superjson`, you **must** pass it to the client config. Without this, Dates, Maps, Sets, and other non-JSON types may be silently wrong. First generate your client code using Hey API's programmatic API, this way you can use `createTRPCHeyApiTypeResolvers` to ensure your emitted types are correct: ```ts title="src/client.ts" import { createClient } from '@hey-api/openapi-ts'; import { createTRPCHeyApiTypeResolvers } from '@trpc/openapi/heyapi'; const openApiJson = './path/to/openapi.json' const outputDir = './generated' await createClient({ input: openApiJson, output: outputDir, plugins: [ { name: '@hey-api/typescript', // Important: this ensures that your emitted types like Dates are correct '~resolvers': createTRPCHeyApiTypeResolvers(), }, { name: '@hey-api/sdk', operations: { strategy: 'single' }, }, ], }); ``` At runtime configure the generated client with your transformer, you can then pass native types directly and get them back deserialised: ```ts title="src/usage.ts" import { configureTRPCHeyApiClient } from '@trpc/openapi/heyapi'; import superjson from 'superjson'; import { client } from './generated/client.gen'; import { Sdk } from './generated/sdk.gen'; configureTRPCHeyApiClient(client, { baseUrl: 'http://localhost:3000', // Important, this transformer must match your tRPC API's transformer: transformer: superjson, }); const sdk = new Sdk({ client }); const event = await sdk.getEvent({ query: { input: { id: 'evt_1', at: new Date('2025-06-15T10:00:00Z') } }, }); // event.data.result.data.at is a Date object βœ… const created = await sdk.createEvent({ body: { name: 'Conference', at: new Date('2025-09-01T09:00:00Z') }, }); ``` #### Reading results and errors The SDK returns tRPC's [response envelope](https://trpc.io/docs/rpc.md#http-response-specification), so a procedure's return value is under `result.data`. A failed call resolves with `error` set to the tRPC error envelope instead of throwing: ```ts title="src/usage.ts" import { configureTRPCHeyApiClient } from '@trpc/openapi/heyapi'; import { client } from './generated/client.gen'; import { Sdk } from './generated/sdk.gen'; configureTRPCHeyApiClient(client, { baseUrl: 'http://localhost:3000' }); const sdk = new Sdk({ client }); const { data, error } = await sdk.user.byId({ query: { input: '1' } }); if (error) { console.log(error.error.data.code); // e.g. 'NOT_FOUND' } else { console.log(data?.result.data); // what the procedure returned } ``` ### Using a different generator or language The generated OpenAPI spec works with any OpenAPI-compatible client generator which can: - Emit accurate types for classes like Date - Support customising Search Params and request/response body serialization To integrate correctly with tRPC's protocol, you need to set up your generated client to do two things: - **Transformers** β€” If your tRPC API uses a transformer, the client must serialise inputs and deserialise outputs using the same format - **Query Inputs** β€” GET requests encode input as `?input=`, not as individual query parameters See the [Hey API config source](https://github.com/trpc/trpc/blob/f346e9bb97ff3c8a7e874f59110a47730293097a/packages/openapi/src/heyapi/index.ts) for a complete reference implementation. ### Transformers tRPC [data transformers](https://trpc.io/docs/server/data-transformers.md) let you send rich types like `Date`, `Map`, `Set`, and `BigInt` over the wire. When using the OpenAPI client, the same transformer must be configured on both the server and client so that inputs are serialised and outputs are deserialised correctly. Any transformer that implements the tRPC `DataTransformer` interface (`serialize` / `deserialize`) works with `configureTRPCHeyApiClient`. Below are some tested options. #### SuperJSON The most popular transformer for TypeScript-to-TypeScript setups. Handles `Date`, `Map`, `Set`, `BigInt`, `RegExp`, and more. ```bash pnpm add superjson ``` ```ts title="src/server.ts" import { initTRPC } from '@trpc/server'; import superjson from 'superjson'; const t = initTRPC.create({ transformer: superjson }); ``` ```ts title="src/client.ts" import { configureTRPCHeyApiClient } from '@trpc/openapi/heyapi'; import superjson from 'superjson'; import { client } from './generated/client.gen'; configureTRPCHeyApiClient(client, { baseUrl: 'http://localhost:3000', transformer: superjson, }); ``` See the [superjson test](https://github.com/trpc/trpc/blob/main/packages/openapi/test/generate.test.ts) for a full end-to-end example. #### MongoDB Extended JSON v2 [EJSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/#mongodb-extended-json-v2-usage) is a good choice when you need cross-language support. The `bson` npm package provides `EJSON.serialize` / `EJSON.deserialize` which map directly to a tRPC `DataTransformer`. Available in: C, C#, C++, Go, Java, Node.js, Perl, PHP, Python, Ruby, Scala ```bash pnpm add bson ``` ```ts title="src/transformer.ts" import { EJSON } from 'bson'; import type { Document } from 'bson'; import type { TRPCDataTransformer } from '@trpc/server'; export const ejsonTransformer: TRPCDataTransformer = { serialize: (value) => EJSON.serialize(value), deserialize: (value) => EJSON.deserialize(value as Document), }; ``` ```ts title="src/client.ts" import { configureTRPCHeyApiClient } from '@trpc/openapi/heyapi'; import { client } from './generated/client.gen'; import { ejsonTransformer } from './transformer'; configureTRPCHeyApiClient(client, { baseUrl: 'http://localhost:3000', transformer: ejsonTransformer, }); ``` See the [MongoDB EJSON test](https://github.com/trpc/trpc/blob/main/packages/openapi/test/mongoEjson.test.ts) for a full end-to-end example. #### Amazon Ion [Amazon Ion](https://amazon-ion.github.io/ion-docs/) is a richly-typed data format with broad language support. It doesn't directly support the `TRPCDataTransformer` interface and requires a bit of boilerplate to make work with tRPC in JS/TS, but may be a good choice for your own system. Available in: C, C#, D, Go, Java, JavaScript, PHP, Python, Rust ```bash pnpm add ion-js ``` See the [Amazon Ion test](https://github.com/trpc/trpc/blob/main/packages/openapi/test/amazonIon.test.ts) for the transformer implementation, boilerplate, and a full end-to-end example. #### Writing a custom transformer Any object with `serialize` and `deserialize` methods works: ```ts import type { TRPCDataTransformer } from '@trpc/server'; const myTransformer: TRPCDataTransformer = { serialize: (value) => { /* encode rich types */ }, deserialize: (value) => { /* decode them back */ }, }; ``` Pass it to both `initTRPC.create({ transformer })` on the server and `configureTRPCHeyApiClient(client, { transformer })` on the client. See the [data transformers docs](https://trpc.io/docs/server/data-transformers.md) for more details. ### Full example For a complete, runnable project that ties all of these steps together, see the [openapi-codegen example](https://github.com/trpc/trpc/tree/main/examples/openapi-codegen). Its [codegen script](https://github.com/trpc/trpc/blob/main/examples/openapi-codegen/src/scripts/codegen.ts) generates the spec with `generateOpenAPIDocument` and then the SDK with Hey API in one step. ## API changelog and breaking-change checks with `oasdiff` After generating OpenAPI specs, you can compare two versions with [`oasdiff`](https://github.com/oasdiff/oasdiff). For installation options (Homebrew, Docker, binaries, etc), see the official docs: - [oasdiff install docs](https://github.com/oasdiff/oasdiff/blob/main/docs/README.md) - [oasdiff changelog and breaking checks](https://github.com/oasdiff/oasdiff/blob/main/docs/BREAKING-CHANGES.md) Using this you can quick generate changelogs or detect inadvertent breaking changes to APIs to help plan and coordinate releases ```sh # Get a complete changelog including minor and breaking changes $ oasdiff changelog packages/openapi/test/routers/superjsonRouter.openapi.json /tmp/superjsonRouter.openapi.next.json 3 changes: 2 error, 0 warning, 1 info error [new-required-request-property] in API POST /createEvent added the new required request property 'location' error [api-path-removed-without-deprecation] in API GET /getBigInt api path removed without deprecation info [endpoint-added] in API GET /health endpoint added # Get a list of breaking changes if any $ oasdiff breaking packages/openapi/test/routers/superjsonRouter.openapi.json /tmp/superjsonRouter.openapi.next.json 2 changes: 2 error, 0 warning, 0 info error [new-required-request-property] in API POST /createEvent added the new required request property 'location' error [api-path-removed-without-deprecation] in API GET /getBigInt api path removed without deprecation ``` ## Common mistakes - **Using the wrong export name.** `--export` (`exportName`) defaults to `AppRouter`. If your file exports the router as `appRouter`, pass `-e appRouter`. When the name isn't found, the error lists the file's exports. - **Leaving the tRPC prefix out of the base URL.** The spec's paths are relative to where tRPC is mounted (`/user.create`), so if your adapter serves tRPC under `/trpc`, both `--server-url` and the client's `baseUrl` need to end in `/trpc`. - **Skipping `createTRPCHeyApiTypeResolvers()` when you use a transformer.** Without it, Hey API types `Date` fields as `string` and `bigint` fields as `number`. - **Configuring a transformer on the server only.** `configureTRPCHeyApiClient` needs the same `transformer` as your `initTRPC`, or rich types arrive still encoded. - **Expecting subscriptions in the spec.** The generator skips subscription procedures. --- Source: https://trpc.io/docs/community/awesome-trpc # Awesome tRPC Collection > A collection of resources on tRPC. **Please** edit this page and add your own links! πŸ™ ## 🧩 Extensions & community add-ons ### Extensions | Description | Link | | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | tRPC Docs Generator - Auto generate interactive documentation for your tRPC APIs | https://github.com/liorcodev/trpc-docs-generator | | tRPC-ui - Automatically generates a UI for manually testing your tRPC backend | https://github.com/aidansunbury/trpc-ui | | trpc-to-openapi - OpenAPI & REST support for your tRPC routers | https://github.com/mcampa/trpc-to-openapi | | tRPC Client Devtools browser extension | https://github.com/rhenriquez28/trpc-client-devtools | | tRPC Playground - sandbox for testing tRPC queries in the browser | https://github.com/sachinraja/trpc-playground | | tRPC-Chrome - Web extensions messaging support for tRPC | https://github.com/jlalmes/trpc-chrome | | Step CI - Automated API Testing and Quality Assurance | https://github.com/stepci/stepci | | msw-trpc - tRPC support for MSW | https://github.com/maloguertin/msw-trpc | | trpc-cli - Turn a tRPC router into a type-safe, fully documented CLI | https://github.com/mmkal/trpc-cli | | trpc-live - Live query solution for tRPC | https://github.com/strblr/trpc-live | | trpc-navigation-plugin - Fix goto-definition with emit declarations | https://github.com/ebg1223/trpc-navigation-plugin | | oRPC - OpenAPI support for your tRPC routers | https://orpc.dev/docs/openapi/integrations/trpc | | Prisma tRPC Generator - Automatically generate tRPC routers from Prisma schemas | https://github.com/omar-dulaimi/prisma-trpc-generator | | tRPC Shield - Permission system for tRPC | https://github.com/omar-dulaimi/trpc-shield | | Prisma tRPC Shield Generator - Generate tRPC Shield permissions from Prisma schema | https://github.com/omar-dulaimi/prisma-trpc-shield-generator | | trpc-to-mcp - Turn a tRPC router into MCP tools, server and handler | https://github.com/iboughtbed/trpc-to-mcp | | tRPC Studio - Swagger-like UI with input forms, Try It Out, output type visualization, and CLI extractor | https://github.com/sayefdeen/trpc-studio | ### Frontend frameworks | Description | Link | | ------------------------------------------------------- | ----------------------------------------------- | | tRPC-SvelteKit - SvelteKit tRPC extension | https://github.com/icflorescu/trpc-sveltekit | | tRPC-Remix - Adapter for Remix | https://github.com/ggrandi/trpc-remix | | tRPC-Remix-Call - Client and server side call for Remix | https://github.com/simonboisset/trpc-remix-call | | tRPC Client For SolidJS W/ Solid Query | https://github.com/OrJDev/solid-trpc | | tRPC API Handler For SolidStart | https://github.com/OrJDev/solid-start-trpc | | tRPC-nuxt - Nuxt 3 module | https://github.com/wobsoriano/trpc-nuxt | ### Bootstrappers | Description | Link | | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | create-t3-app - Scaffold a starter project using the T3 Stack (Next.js, tRPC, Tailwind CSS, Prisma) | https://create.t3.gg | | sidebase - Scaffold a starter project using sidebase (Nuxt 3, tRPC, Tailwind CSS, Prisma) | https://sidebase.io | | Create JD App - Scaffold a starter project using the JD Stack (SolidStart, tRPC, Tailwind, Prisma) | https://github.com/OrJDev/create-jd-app | | Create tRPC App - Create tRPC-powered apps with one command | https://github.com/omar-dulaimi/create-trpc-app | | viteRPC - Monorepo template powered by Vite (Vite, tRPC, Tailwind CSS) | https://web.archive.org/web/20241114210459/https://github.com/mnik01/viteRPC | | Start UI [web] - Opinionated frontend starter (tRPC, Prisma, Next.js, Chakra UI) | https://github.com/bearstudio/start-ui-web | | Nx Plugin for AWS - Scaffold a project using tRPC with Nx, and deploy to AWS with CDK or Terraform | https://awslabs.github.io/nx-plugin-for-aws/en/guides/trpc/ | ### Library adapters | Description | Link | | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | tRPC-uWebSockets - Adapter for uWebSockets.js server | https://github.com/romanzy-1612/trpc-uwebsockets | | jotai-trpc - Jotai wrapper around tRPC vanilla client | https://github.com/jotai-labs/jotai-trpc | | trpc-zustand - Zustand wrapper around tRPC client | https://github.com/strblr/trpc-zustand | | @h4ad/serverless-adapter - Connect tRPC with AWS SQS, AWS API Gateway, and many more event sources. | https://viniciusl.com.br/serverless-adapter/docs/main/frameworks/trpc | | trpc-koa-adapter - tRPC adapter for Koa server | https://github.com/BlairCurrey/trpc-koa-adapter | | tRPC - iron-session | https://github.com/parkgang/trpc-iron-session | | electron-trpc - Electron support for tRPC | https://github.com/jsonnull/electron-trpc | | cloudflare-pages-plugin-trpc - Quickly create a tRPC server with a Cloudflare Pages Function | https://github.com/toyamarinyon/cloudflare-pages-plugin-trpc | | ZenStack - Full-stack toolkit adds access control to Prisma and generates trpc routers from schema | https://github.com/zenstackhq/zenstack | | tRPC-SWR - tRPC adapter for Vercel's SWR client | https://trpc-swr.vercel.app/ | | trpc-rtk-query - Automatically generate RTK Query api endpoints from your tRPC setup | https://github.com/otahontas/trpc-rtk-query | | k6-trpc - k6 compatible tRPC client | https://github.com/dextertanyj/k6-trpc | | trpc-token-refresh-link - Link to refresh access tokens and refresh tokens | https://github.com/larskarbo/trpc-token-refresh-link | | trpc-bun-adapter - tRPC adapter for Bun runtime environment | https://github.com/cah4a/trpc-bun-adapter | | trpc-rabbitmq - tRPC adapter using RabbitMQ as a transport layer | https://github.com/imxeno/trpc-rabbitmq | | trpc-mqtt - tRPC adapter using MQTT as a transport layer | https://github.com/edorgeville/trpc-mqtt | | trpc-redis - tRPC adapter using Redis as a transport layer | https://github.com/cobeo2004/trpc-redis | | NestJS-tRPC - An opinionated approach to building end-to-end typesafe APIs with tRPC within NestJS. | https://www.nestjs-trpc.io/ | | vscode-trpc - tRPC adapter for VS Code extension development | https://github.com/wszgrcy/vscode-toolkit | ## πŸ€ Starting points, example projects, etc | Description | Link | | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | **Recommended:** Starter project with Prisma, Next.js, tRPC, E2E-testing | https://github.com/trpc/examples-next-prisma-starter | | **create-t3-turbo** - Clean and simple starter repo using the T3 Stack along with Expo React Native | https://github.com/t3-oss/create-t3-turbo | | Subscriptions Starter Project using SSE | https://github.com/trpc/examples-tanstack-start-sse-chat | | WebSockets Starter Project | https://github.com/trpc/examples-next-prisma-starter-websockets | | tRPC Kitchen Sink - A collection of tRPC usage patterns. | https://github.com/trpc/examples-kitchen-sink | | Turborepo + Expo + tRPC Starter | https://github.com/gunnnnii/turbo-expo-trpc-starter | | tRPC-SvelteKit Example Application | https://github.com/icflorescu/trpc-sveltekit-example | | tRPC + Ultra | https://github.com/sachinraja/trpc-ultra | | Nx Monorepo + tRPC + Prisma | https://github.com/nowlena/nx-trpc-test | | tRPC (w/ Fetch Adapter) + SvelteKit + Tailwind CSS | https://github.com/austins/trpc-sveltekit-fetchadapter-example | | Sign-In With Ethereum tRPC + ViteJS React | https://github.com/codingwithmanny/trpc-siwe-monorepo | | tRPC + Vue3 todo example project (tRPC, Express.js, Vue3, Prisma, vue-query) | https://github.com/guushamann/Todo-tRPC-Vue3 | | Vite + Svelte + tRPC | https://github.com/mishankov/vite-svelte-trpc | | V3 - A T3 Inspired Nuxt Stack | https://github.com/CRBroughton/V3 | | Twitter clone - A simple Twitter clone built with T3 Stack + NextAuth + Supabase + Prisma | https://github.com/AlandSleman/t3-twitter-clone | | Separate backend & frontend repositories | https://github.com/mkosir/trpc-api-boilerplate | | tRPC + Deno + fresh | https://github.com/LunaTK/fresh-trpc-example | | Ethereum Decentralized Application example (Next.js, tRPC, Ethers, Hardhat, Solidity) | https://github.com/tr1sm0s1n/next-trpc-dapp | | Yarn Workspaces + ESLint + CSpell + Commitlint + Lefthook + tRPC + React Query + Vite | https://github.com/sotnikov-link/yarn-workspaces-eslint-cspell-commitlint-lefthook-template | | Fullstack SaaS Boilerplate: Trpc Fastify React | https://github.com/alan345/Fullstack-SaaS-Boilerplate | | tRPC realtime server with Fastify, Prisma, Redis (or type-safe event emitter) and PostgreSQL | https://github.com/cobeo2004/trpc-fastify | | Build a Public tRPC API: trpc-openapi vs ts-rest | https://catalins.tech/public-api-trpc/ | | Next.js + Expo + tRPC Monorepo Boilerplate | https://github.com/monsieursam/boilerplate-next-expo-trpc | | Next.js + Express + BetterAuth + Prisma + bun + shadcn + tRPC Monorepo Boilerplate | https://github.com/KitsuneKode/template-nextjs-express-trpc-better-auth-monorepo | | Electron AppStack - Electron starter with type-safe tRPC IPC, React, SQLite, auto update, signing | https://electron-appstack.com | ## 🏁 Open-source projects using tRPC | Description | Link | | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | [Cal.com](https://cal.com) - Scheduling infrastructure | https://github.com/calcom/cal.com | | [Skill Recordings](https://github.com/skillrecordings/products) - Hosting courses by Matt Pocock, Kent C Dodds, Dan Abramov, and many others | https://github.com/skillrecordings/products | | [SST](https://sst.dev) - A framework that makes it easy to build serverless apps. | https://github.com/serverless-stack/sst | | [Beam](https://web.archive.org/web/20231214211856/https://planetscale.com/blog/introducing-beam) - A simple message board for your organization or project. | https://web.archive.org/web/20231212214304/https://github.com/planetscale/beam | | [Rallly](https://rallly.co) - Self-hostable doodle poll alternative. | https://github.com/lukevella/rallly | | [Hilde](https://github.com/nehalist/hilde) - Match-making app for games like foosball, air hockey and similar | https://github.com/nehalist/hilde | | [Answer Overflow](https://www.answeroverflow.com/) - Discord bot that indexes help channel content into Google | https://github.com/AnswerOverflow/AnswerOverflow | | [Prisma Editor](https://github.com/mohammed-bahumaish/prisma-editor) - Powerful tool to visualize and edit Prisma Schema | https://github.com/mohammed-bahumaish/prisma-editor | | [Saleor Apps](https://saleor.io/) - Official apps/integrations for Saleor Commerce | https://github.com/saleor/apps | | [Rao Pics App](https://github.com/rao-pics/rao-pics) - Visit Photo on any device. Supported MacOS/Windows | https://github.com/rao-pics/rao-pics | | [Tianji](https://tianji.msgbyte.com/) - All-in-One Insight Hub. Tianji = Website Analytics + Uptime Monitor + Server Status | https://github.com/msgbyte/tianji | | [Workplacify](https://workplacify.com/) - Desk scheduling software, for hybrid and in-office teams | https://workplacify.com/ | | [Dotfyle](https://dotfyle.com/) - Discover and share Neovim plugins | https://dotfyle.com/ | | [ConvoForm](https://www.convoform.com/?utm_source=github&utm_medium=social&utm_campaign=trpc) - Create your own AI-Powered conversational form | https://www.convoform.com/ | | [Authier](https://www.authier.pm/) - Open-source password manager with browser autofill and TOTP | https://github.com/authier-pm/authier | --- Source: https://trpc.io/docs/community/contributing # Contributing > All contributions are welcome and appreciated, big or small! Feel free to submit pull requests, create issues, or start discussions on the [GitHub repo](https://github.com/trpc/trpc). If you are not sure where to start, we have a tag for [good first issues](https://github.com/trpc/trpc/issues?q=is%3Aopen+is%3Aissue+label%3A%22%F0%9F%91%89+good+first+issue%22). If you need help or feedback, contact [**@alexdotjs** on Twitter](https://twitter.com/alexdotjs) or write in our [Discord Server](https://trpc.io/discord)! See official contribution guide [here on GitHub](https://github.com/trpc/trpc/blob/main/CONTRIBUTING.md). --- --- Source: https://trpc.io/docs/community/love # Testimonials / Love > Do you love or hate tRPC? Feel free to ping [@alexdotjs on Twitter](https://twitter.com/alexdotjs) ## From Twitter > For more testimonials, see this Twitter collection: https://twitter.com/alexdotjs/timelines/1441435105910796291
Tried out trpc for the first time yesterday. The fact that you get type safety WITHOUT codegen is extremely compelling. It makes the feedback loop very very fast.

Sort of wishing I had used this instead of graphql for my last project.
twitter.com/trpcio/status/1537719366908792832
That being said, we _are_ starting a production project right now, and we're using @nextjs with @trpcio . It's so good I don't even know where to start πŸ”₯. Probably with the e2e type-safety 😍
Haven't thought about client state much but the former probably applies.
The amount that tRPC has improved the quality of our code, the speed of our delivery, and the happiness of our devs is hard to comprehend.

I know I shill it a lot but seriously, please try @trpcio
I've used @trpcio for exactly 5 seconds, and I can already tell - it is the _best_ way to consume first-party APIs with React Query.

Why? The "t" - TypeScript means you get end-to-end type safety PLUS auto-complete for your query keys everywhere, like `invalidateQueries`.
tRPC - Safe API between your client and server πŸ”₯

I *LOVE* this project!

If you're building your client and server with TypeScript, tRPC allows you to have static verification of your communication protocol with *zero* overhead on the client.

github.com/trpc/trpc
tRPC is super cool. Mucho magic there and good magic at that.
Hah, we just did our first endpoint, returned some mock data from a resolver and got instant autocomplete in the client. Everyone's heads went 🀯πŸ₯³
for my money, Zod + @HookForm + tRPC has been the best stack for building typesafe forms for nearly three years now

what are the other challengers?
twitter.com/Hicksyfern/status/1629931362403713024
## From GitHub

We built a nextjs website with trpc and it has worked wonderful πŸ™Œ [...]

— cNille Aug 11, 2021

Hi - have just started using trpc and it is πŸ‘Œ [...]

— mmkal July 22, 2021

Hey @KATT - love the approach you have taken with this. Proper type sharing in Next.js projects is something I have been trying to achieve for a while and your solution here ticks all the boxes. [...]

— dangreaves June 2, 2021

First of all I want to say thank you very much for making this library! I was already looking for a library like this for quite some time. [...]

— simonedelmann May 17, 2021

Hi there, thanks for this library! I'm checking it out and appreciate how it feels like a much more lightweight approach to my typical Prisma-Nexus-Apollo-GQL Codegen stack. [...]

— lostfictions June 24, 2021

Thank you for the quick fix and the amazing project πŸ’―

— mgranderath May 3, 2021
--- Source: https://trpc.io/docs/community/sponsors # Sponsors > If you enjoy working with tRPC and want to support the project, consider giving a token appreciation by [GitHub Sponsors](/sponsor)! Also, if your company is using tRPC and want to support long-term maintenance of tRPC, have a look at the [sponsorship tiers](/sponsor) or [get in touch](mailto:alex@trpc.io) to discuss potential partnerships. ### πŸ₯ˆ Silver Sponsors
Greptile
Greptile
CodeRabbit
CodeRabbit
SerpApi
SerpApi
### 😻 Smaller Backers
Unkey
Unkey
Dr.%20B
Dr. B
Proxidize
Proxidize
Ryan%20Magoon
Ryan Magoon
Liminity%20AB
Liminity AB
BestKru
BestKru
Max%20Greenwald
Max Greenwald
Dmitry%20Maykov
Dmitry Maykov
Chris%20Bradley
Chris Bradley
fanvue
fanvue
Aerius%20Ventilation%20AB
Aerius Ventilation AB
Drizzle%20Team
Drizzle Team
Spencer%20McKenney
Spencer McKenney
Stefan%20Smiljkovic
Stefan Smiljkovic
Kalle
Kalle
Maicon%20Carraro
Maicon Carraro
Andrei%20Karushev
Andrei Karushev
Vault
Vault
--- Source: https://trpc.io/docs/faq # FAQ / Troubleshooting > Collection of frequently asked questions with ideas on how to troubleshoot & resolve them. Feel free to contribute to this page with improvements or create a new discussion [on GitHub](https://github.com/trpc/trpc/discussions) if you have a question that isn't answered here. Also, have a look through the [GitHub Discussions](https://github.com/trpc/trpc/discussions) and our [Discord](https://trpc.io/discord) if your question isn't answered here. ## It doesn't work! I'm getting `any` everywhere - Make sure you have no type errors in your code - Make sure you have `"strict": true` in your `tsconfig.json` - Make sure your `@trpc/*`-versions match in your `package.json` - Make sure you are using the TypeScript-version required by tRPC (`>=5.7.2`) - Make sure your editor is using the same TypeScript version as your `package.json` ### VSCode settings Add these settings to your `.vscode/settings.json` in your project root to make sure your editor is using the same TypeScript version as your `package.json`: ```json title=".vscode/settings.json" { "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true } ``` We highly recommend committing this file to your repo so your colleagues also get the same experience. ## How do I make a middleware change the type of my `Context`? See [Context Extension](https://trpc.io/docs/server/middlewares.md#context-extension). ## Is tRPC production ready? Yes. tRPC is very stable and is used by thousands of companies, even big ones like [Netflix](https://netflix.com) & [Pleo](https://pleo.io) are using tRPC in production. ## Why doesn't tRPC work in my monorepo? This is a difficult question to answer, but since tRPC doesn't have any build step, it's unlikely that the problem is on tRPC's side. Here are some things to check: - Make sure you have the same version of all `@trpc/*` across all your projects - Make sure you have `"strict": true` in all your `tsconfig.json`s - Make sure you have no type errors in your app - In the case that you have a dedicated server and client `tsconfig.json` files without a bundled server monorepo package, make sure you have `"paths": [...]` in your client `tsconfig.json` like your server `tsconfig.json`, so that the client can find the same file. You can also have a look at our [Awesome tRPC](https://trpc.io/docs/community/awesome-trpc.md)-collection to find several open-source projects that are using tRPC in a monorepo. ## Is a monorepo mandatory? No, a monorepo is not mandatory but you will lose some of the benefits of using tRPC if you don't use it since you will lose guarantees that your client and server works together. One way you can leverage tRPC is to publish a private npm package with the types of your backend repo and consume them in your frontend repo. > _Related discussion: https://github.com/trpc/trpc/discussions/1860_ ## Can I dynamically return a different output depending on what input I send? No, not currently, in order for tRPC to do that automatically, we need something called "Higher kinded types" which is not yet supported in TypeScript. > _Related discussion: https://github.com/trpc/trpc/discussions/2150_ ## Can I apply a middleware to a full router? No, but you can use [base procedures](https://trpc.io/docs/server/procedures.md#reusable-base-procedures) instead, which offers more flexibility than if this was done on a per-router-level. ## Does tRPC work with Next.js App Router & RSC? Yes, tRPC works with Next.js App Router & React Server Components. See the [Next.js App Router setup guide](https://trpc.io/docs/client/nextjs/app-router-setup.md) for the recommended approach. ## Am I safe with using features marked as `unstable_`? {#unstable} **tl;dr**: Yes! If you encounter a feature in tRPC that is marked as `unstable_` it means that the API is unstable and might change in minor version bumps, but: - Specifics of the implementation might change in minor changes - its name and options might change - If it exists in tRPC it's already being used in production - We very much encourage you to use it - If any changes are done to `unstable_`-feature, they will be included in the release notes (& you'll see type errors) - Please report any suggestion on the API design or issues on [github.com/trpc/trpc/issues](https://github.com/trpc/trpc/issues) or in the `#πŸ§ͺ-unstable-experimental-features` on [our Discord](https://trpc.io/discord) ## Am I safe with using features marked as `experimental_`? {#experimental} If you encounter a feature in tRPC that is marked as `experimental_` it means that the API is unstable and is very likely to change during any bump of tRPC. - Wide range of the feature and its usage might change - The feature might not be well-tested - We might drop the feature entirely - It's up to you to read the latest docs and upgrade without a guided migration path - Changes might not be well-documented in the release notes - Bugs are not guaranteed to be fixed We do, however, love input! Please report any suggestion on the API design or issues in the `#πŸ§ͺ-unstable-experimental-features` on [our Discord](https://trpc.io/discord). ## Is tRPC strict with semver? {#semver} Yes, tRPC is very strict with [semantic versioning](https://semver.org/) and we will never introduce breaking changes in a minor version bump. With this, we also consider changes on `export`ed TypeScript `type`s as major changes, apart from ones marked as `@internal` in the JSDoc. ## Why is tRPC on such a high version already? When tRPC started and had very few users, we often iterated on the API design while being strict with semver. - The first 9 versions of tRPC were released in the first 8 months of the project. - [Version 10](/blog/announcing-trpc-10) which we released 14 months after v9 should be seen as the real "version 2" of tRPC where we did any fundamental changes to the API decisions. _(2 is 10 in binary, amirite?)_ We expect the API to be stable now and are planning to release codemods for any breaking changes in the future, just like we did with the v9->v10 upgrade. --- ## Anything else you want to know? Please write a feature request on [GitHub](https://github.com/trpc/trpc/issues), write in [GitHub Discussions](https://github.com/trpc/trpc/discussions), or [Discord](https://trpc.io/discord). You're also free to suggest improvement of this page or any other page using the "Edit this page" button at the bottom of the page. --- Source: https://trpc.io/docs/rpc # HTTP RPC Specification > ## Methods \<-> Type mapping | HTTP Method | Mapping | Notes | | ----------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET` | `.query()` | Input JSON-stringified in query param.
_e.g._ `myQuery?input=${encodeURIComponent(JSON.stringify(input))}` | | `POST` | `.mutation()` | Input as POST body. | | `GET` | `.subscription()` | Subscriptions are supported via [Server-sent Events](https://trpc.io/docs/client/links/httpSubscriptionLink.md) using `httpSubscriptionLink`, or via [WebSockets](https://trpc.io/docs/server/websockets.md) using `wsLink`. | ## Content-Type Mapping The request's `Content-Type` header determines how tRPC parses the input. tRPC picks a handler by matching the header against the following, in order ([source](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/http/contentType.ts)): | `Content-Type` | Allowed methods | Notes | | -------------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application/json` | `GET`, `POST` | Default. `GET` requests fall back to this handler when no other handler matches (including when there is no `Content-Type` header), so a query URL can be opened directly in a browser. | | `multipart/form-data` | `POST` only | Other methods respond with `METHOD_NOT_SUPPORTED` (`405`). | | `application/octet-stream` | `POST` only | Other methods respond with `METHOD_NOT_SUPPORTED` (`405`). | | anything else (or missing) on a non-`GET` request | β€” | Responds with `UNSUPPORTED_MEDIA_TYPE` (`415`). | `HEAD` requests skip this and always respond with `204`, which is useful for warming up serverless functions. See [Content Types](https://trpc.io/docs/server/non-json-content-types.md) for how to send `FormData` and binary (`File`/`Blob`/`Uint8Array`) inputs, and which client links support them. ## Accessing nested procedures Nested procedures are separated by dots, so a request to `byId` below would end up being a request to `/api/trpc/post.byId`. ```ts export const appRouter = router({ post: router({ byId: publicProcedure.input(String).query(async (opts) => { // [...] }), }), }); ``` ### Path separator Some firewalls block URLs with a `.` in them. Set `pathSeparator` to use another character between path segments in URLs. Set it on the server and in every HTTP link: ```ts // server const t = initTRPC.create({ pathSeparator: '~' }); // client httpBatchLink({ url: '/api/trpc', pathSeparator: '~' }); ``` Now `post.byId` is served at `/api/trpc/post~byId`, and a batch of `post.byId` and `post.list` at `/api/trpc/post~byId,post~list?batch=1`. - It can be `'.'` (the default), `'~'`, `'_'` or `'-'`. These never need encoding in URLs, so routes and proxies leave them alone. - Only URLs change. Middlewares, `onError`, error shapes, server-side callers and query keys still see `post.byId`. - The server still accepts dotted URLs, so update the server before the clients. - A router key that contains the separator, such as `get_user` with `'_'`, throws when the router is built, since its URL would be ambiguous. Keys inside a `lazy()` router throw when that router loads, on its first call. `'~'` is the least likely to clash with your keys. - WebSockets don't put the path in the URL, so `wsLink` doesn't need it. - Pass `pathSeparator` to [`generateOpenAPIDocument`](https://trpc.io/docs/openapi.md) if it can't import your router at runtime. ## Batching When batching, we combine all parallel procedure calls of the same HTTP method in one request using a data loader. - The called procedures' names are combined by a comma (`,`) in the `pathname` - Input parameters are sent as a query parameter called `input` which has the shape `Record`. - We also need to pass `batch=1` as a query parameter. - If the response has different statuses, we send back `207 Multi-Status` _(e.g., if one call errored and one succeeded)_ ### Batching Example Request #### Given a router like this exposed at `/api/trpc`: ```tsx title="server/router.ts" export const appRouter = t.router({ postById: t.procedure.input(String).query(async (opts) => { const post = await opts.ctx.post.findUnique({ where: { id: opts.input }, }); return post; }), relatedPosts: t.procedure.input(String).query(async (opts) => { const posts = await opts.ctx.findRelatedPostsById(opts.input); return posts; }), }); ``` #### ... And two queries defined like this in a React component: ```tsx title="MyComponent.tsx" export function MyComponent() { const post1 = trpc.postById.useQuery('1'); const relatedPosts = trpc.relatedPosts.useQuery('1'); return (
      {JSON.stringify(
        {
          post1: post1.data ?? null,
          relatedPosts: relatedPosts.data ?? null,
        },
        null,
        4,
      )}
    
); } ``` #### The above would result in exactly 1 HTTP call with this data: | Location property | Value | | ----------------- | --------------------------------------------------------------- | | `pathname` | `/api/trpc/postById,relatedPosts` | | `search` | `?batch=1&input=%7B%220%22%3A%221%22%2C%221%22%3A%221%22%7D` \* | **\*) `input` in the above is the result of:** ```ts encodeURIComponent( JSON.stringify({ 0: '1', // <-- input for `postById` 1: '1', // <-- input for `relatedPosts` }), ); ``` ### Batching Example Response
Example output from server ```json [ // result for `postById` { "result": { "data": { "id": "1", "title": "Hello tRPC", "body": "..." // ... } } }, // result for `relatedPosts` { "result": { "data": [ /* ... */ ] } } ] ```
## HTTP Response Specification In order to have a specification that works regardless of the transport layer we try to conform to [JSON-RPC 2.0](https://www.jsonrpc.org/specification) where possible. ### Successful Response
Example JSON Response ```json { "result": { "data": { "id": "1", "title": "Hello tRPC", "body": "..." } } } ```
```ts interface SuccessResponse { result: { data: TOutput; // output from procedure } } ``` ### Error Response
Example JSON Response ```json [ { "error": { "json": { "message": "Something went wrong", "code": -32600, // JSON-RPC 2.0 code "data": { // Extra, customizable, meta data "code": "INTERNAL_SERVER_ERROR", "httpStatus": 500, "stack": "...", "path": "post.add" } } } } ] ```

- When possible, we propagate HTTP status codes from the error thrown. - If the response has different statuses, we send back `207 Multi-Status` _(e.g., if one call errored and one succeeded)_ - For more on errors and how to customize them see [Error Formatting](https://trpc.io/docs/server/error-formatting.md). ## Error Codes \<-> HTTP Status ```ts const HTTP_STATUS_CODES = { PARSE_ERROR: 400, BAD_REQUEST: 400, UNAUTHORIZED: 401, PAYMENT_REQUIRED: 402, FORBIDDEN: 403, NOT_FOUND: 404, METHOD_NOT_SUPPORTED: 405, TIMEOUT: 408, CONFLICT: 409, PRECONDITION_FAILED: 412, PAYLOAD_TOO_LARGE: 413, UNSUPPORTED_MEDIA_TYPE: 415, UNPROCESSABLE_CONTENT: 422, PRECONDITION_REQUIRED: 428, TOO_MANY_REQUESTS: 429, CLIENT_CLOSED_REQUEST: 499, INTERNAL_SERVER_ERROR: 500, NOT_IMPLEMENTED: 501, BAD_GATEWAY: 502, SERVICE_UNAVAILABLE: 503, GATEWAY_TIMEOUT: 504, } as const; ``` ## Error Codes \<-> JSON-RPC 2.0 Error Codes
Available codes & JSON-RPC code ```ts /** * JSON-RPC 2.0 Error codes * * `-32000` to `-32099` are reserved for implementation-defined server-errors. * For tRPC we're copying the last digits of HTTP 4XX errors. */ export const TRPC_ERROR_CODES_BY_KEY = { /** * Invalid JSON was received by the server. * An error occurred on the server while parsing the JSON text. */ PARSE_ERROR: -32700, /** * The JSON sent is not a valid Request object. */ BAD_REQUEST: -32600, // 400 // Internal JSON-RPC error INTERNAL_SERVER_ERROR: -32603, // 500 NOT_IMPLEMENTED: -32603, // 501 BAD_GATEWAY: -32603, // 502 SERVICE_UNAVAILABLE: -32603, // 503 GATEWAY_TIMEOUT: -32603, // 504 // Implementation specific errors UNAUTHORIZED: -32001, // 401 PAYMENT_REQUIRED: -32002, // 402 FORBIDDEN: -32003, // 403 NOT_FOUND: -32004, // 404 METHOD_NOT_SUPPORTED: -32005, // 405 TIMEOUT: -32008, // 408 CONFLICT: -32009, // 409 PRECONDITION_FAILED: -32012, // 412 PAYLOAD_TOO_LARGE: -32013, // 413 UNSUPPORTED_MEDIA_TYPE: -32015, // 415 UNPROCESSABLE_CONTENT: -32022, // 422 PRECONDITION_REQUIRED: -32028, // 428 TOO_MANY_REQUESTS: -32029, // 429 CLIENT_CLOSED_REQUEST: -32099, // 499 } as const; ```
### Overriding the default HTTP method To override the HTTP method used for queries/mutations, you can use the `methodOverride` option: ```tsx title="server/httpHandler.ts" // Your server must separately allow the client to override the HTTP method const handler = createHTTPHandler({ router: router, allowMethodOverride: true, }); ``` ```tsx title="client/trpc.ts" import { createTRPCClient, httpLink } from '@trpc/client'; import type { AppRouter } from './server'; // The client can then specify which HTTP method to use for all queries/mutations const client = createTRPCClient({ links: [ httpLink({ url: `http://localhost:3000`, methodOverride: 'POST', // all queries and mutations will be sent to the tRPC Server as POST requests. }), ], }); ``` ## Dig deeper You can read more details by drilling into the TypeScript definitions in - [/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/envelopes.ts) - [/packages/server/src/unstable-core-do-not-import/rpc/codes.ts](https://github.com/trpc/trpc/tree/main/packages/server/src/unstable-core-do-not-import/rpc/codes.ts) --- Source: https://trpc.io/docs/further-reading # Further Reading > ## Who is this for? - tRPC is for full-stack typescripters. It makes it dead easy to write "endpoints", which you can safely use in your app. - It's designed for monorepos, as you need to export/import the type definitions from/to your server. - If you already work in a team where languages are mixed or have third-party consumers over whom you have no control, you should create a language-agnostic [GraphQL](https://graphql.org/)-API. ## Relationship to GraphQL If you already have a custom GraphQL-server for your project, you may not want to use tRPC. GraphQL is amazing; it's great to be able to make a flexible API where each consumer can pick just the data they need. The thing is, GraphQL isn't that easy to get right - [ACL](https://en.wikipedia.org/wiki/Access-control_list) needs to be solved on a per-type basis, complexity analysis, and performance are all non-trivial things. We've taken a lot of inspiration from GraphQL. If you've previously built GraphQL servers, you'll be familiar with the concepts of input types and resolvers. tRPC is a lot simpler and couples your server & website/app more tightly together (for good and for bad). It allows you to move quickly, make changes without having to update a schema, and avoid thinking about the ever-traversable graph. --- Source: https://trpc.io/docs/migrate-from-v10-to-v11 # Migrate from v10 to v11 > ## Migrating from v10 to v11 > [!TIP] > For most users, the migration should be quick & straight-forward. > > If the below three steps aren't enough, look through the below document for _"rarely breaking"_. ### 1. Install new versions ```package-install @trpc/server@^11 @trpc/client@^11 @trpc/react-query@^11 @trpc/next@^11 @tanstack/react-query@^5 @tanstack/react-query-devtools@^5 ``` ### 2. If you're using `transformer`s, update your links See [transformers are moved to links](#transformers-moved) for more information. ### 3. If you're using `@trpc/react-query` update your `@tanstack/react-query`-version See [react-query-v5](#react-query-v5) for more information. ## Full reverse-chronological changelog ### New TanStack React Query integration! (non-breaking) We are excited to announce the new TanStack React Query integration for tRPC is now available in tRPC v11! Read the blog post for more information. The classic `@trpc/react-query` integration is deprecated. It only gets bug fixes and will be removed in the next major version of tRPC. Once you're on v11, follow the [migration guide](https://trpc.io/docs/client/tanstack-react-query/migrating.md) to move to `@trpc/tanstack-react-query`. ### Stopping subscriptions from the server (rarely breaking) We now support stopping subscriptions from the server, this means that you can now do things like this: ```ts const myRouter = router({ sub: publicProcedure.subscription(async function* (opts) { for await (const data of on(ee, 'data', { signal: opts.signal, })) { const num = data[0] as number | undefined; if (num === undefined) { // This will now stop the subscription on the client and trigger the `onComplete` callback return; } yield num; } }), }); ``` See the [subscriptions docs](https://trpc.io/docs/server/subscriptions.md#stopping-from-server) for more information. ### Added support for lazy-loading routers (non-breaking) See the [lazy-loading routers docs](https://trpc.io/docs/server/merging-routers.md#lazy-load) for more information. > As part of this, we've changed the argument of the internal method `callProcedure()` to receive a `{ router: AnyRouter }`-param instead of a `{ _def: AnyRouter['_def'] }`-param. ### Custom `basePath` to handle requests in the standalone adapter (non-breaking) The standalone adapter now supports a `basePath` option, which will slice the basePath from the beginning of the request path. See the [standalone adapter docs](https://trpc.io/docs/server/adapters/standalone.md#custom-basePath) for more information. ### Added support for HTTP/2 servers (non-breaking) We now support HTTP/2 servers, this means that you can now use the `createHTTP2Handler` to create HTTP/2 servers and `createHTTPServer` to create HTTP/1 servers. See the [standalone adapter docs](https://trpc.io/docs/server/adapters/standalone.md#http2) for more information. ### Move `TRPCProcedureOptions` to `@trpc/client` (non-breaking for most) If you previously used `ProcedureOptions` from `@trpc/server`, you now need to use `TRPCProcedureOptions` from `@trpc/client` instead. ### Allow promises to be embedded in nested data (non-breaking) We now allow promises to be embedded in nested data when using the [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md), this means that you can now do things like this: ```ts const appRouter = t.router({ embedPromise: publicProcedure.query(() => { async function slowThing() { await new Promise((resolve) => setTimeout(resolve, 1000)); return 'slow'; } return { instant: 'instant', slow: slowThing(), }; }), }); ``` ### Moved `reconnectAfterInactivityMs` to `sse.client` (non-breaking) Updated [HTTP Subscription Link improvements](#http-subscription-link-improvements)-section and related docs. ### TypeScript version >=5.7.2 is now required (non-breaking) tRPC now requires TypeScript version 5.7.2 or higher. This change was made in response to [a bug report](https://github.com/trpc/trpc/issues/6243) where we decided to take a forward-looking approach. If you try to install tRPC with an unsupported TypeScript version, you'll receive a peer dependency error during installation. If you notice your editor showing `any` types, it's likely because your editor isn't using the correct TypeScript version. To fix this, you'll need to configure your editor to use the TypeScript version installed in your project's `package.json`. For VSCode users, add these settings to your `.vscode/settings.json`: ```json title=".vscode/settings.json" { "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true } ``` ### Moves `experimental.sseSubscriptions` -> `sse` (non-breaking) The `experimental.sseSubscriptions` option has been moved to just `sse` in the `initTRPC.create()`-function. ### HTTP Subscription Link improvements (non-breaking) {#http-subscription-link-improvements} Added support for detecting and recovering from stale connections: On the server, you can configure a ping interval to keep the connection alive: ```ts import { initTRPC } from '@trpc/server'; export const t = initTRPC.create({ sse: { ping: { enabled: true, intervalMs: 15_000, }, client: { // Reconnect if no messages or pings are received for 20 seconds reconnectAfterInactivityMs: 20_000, }, }, }); ``` We will likely add a default ping interval and timeout configuration in the future, but this is not yet decided. Feedback is welcome in the [🎏-rfc-streaming](https://trpc.io/discord) channel on Discord. See the [`httpSubscriptionLink` docs](https://trpc.io/docs/client/links/httpSubscriptionLink.md#timeout) for more details on these features. ### Introduction of `retryLink` (non-breaking) See [retryLink](https://trpc.io/docs/client/links/retryLink.md) - allows you to retry failed operations ### `useSubscription` improvements (non-breaking) - When subscribing to procedures using the [useSubscription](https://trpc.io/docs/client/react/useSubscription.md) hook it will now return information about the status of the subscription and the connection. - Ability to have a ponyfill when using [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md) ### Subscription procedure output type changed to `AsyncGenerator` (non-breaking) If you've used subscriptions with async generators with the v11, this might be breaking with how you infer your types.
Details We changed the inferred output from: ```ts SubscriptionProcedure<{ input: __INPUT__; output: __OUTPUT__; }>; ``` to ```ts SubscriptionProcedure<{ input: __INPUT__; output: AsyncGenerator<__OUTPUT__, void, unknown>; }>; ``` If you need to infer the value you can use a helper like the below: ```ts type inferAsyncIterableYield = TOutput extends AsyncGenerator ? $Yield : never; ```
This change has been made to ensure the library remains compatible with future updates and allows for the use of the `return` type in subscriptions' `AsyncGenerator`s. See [subscriptions docs](https://trpc.io/docs/server/subscriptions.md#output-validation) for more information. ### Added support for output validators in subscriptions (non-breaking) See [subscriptions docs](https://trpc.io/docs/server/subscriptions.md#output-validation) for more information. ### Deprecation of subscriptions returning `Observable`s (non-breaking) We now support returning async generator function for subscriptions and we previously added a [`httpSubscriptionLink`](https://trpc.io/docs/client/links/httpSubscriptionLink.md). To see how to use async generator functions for subscriptions see the [subscriptions docs](https://trpc.io/docs/server/subscriptions.md). ### Removal of `AbortControllerEsque`-ponyfill (rarely breaking) We have removed the `AbortControllerEsque`-ponyfill from tRPC, if you need to support older browsers you can use a polyfill like `abortcontroller-polyfill`. ### Support for Server-sent events (SSE) (non-breaking) We now support SSE for subscriptions, this means that you don't need to spin up a WebSocket server to get real-time updates in your application & that the client can automatically reconnect and resume if the connection is lost. πŸ‘‰ [See more in the `httpSubscriptionLink` docs](https://trpc.io/docs/client/links/httpSubscriptionLink.md). ### Support for streaming responses over HTTP (non-breaking) We now support streaming mutations and queries using the [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink.md#generators). This means that query and mutation resolvers can either be [`AsyncGenerator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator)s with `yield` or return promises that can be deferred for later and you can use stream responses over HTTP, without using WebSockets. We want your feedback on this feature, so please try it out and let us know what you think in the [`🎏-rfc-streaming`-channel on our Discord](https://trpc.io/discord)! πŸ‘‰ [See more in the `httpBatchStreamLink` docs](https://trpc.io/docs/client/links/httpBatchStreamLink.md#generators) ### `resolveHTTPRequest` has been replaced by `resolveRequest` that uses Fetch APIs (rarely breaking) The function `resolveHTTPRequest` has been replaced by `resolveRequest` which uses the Fetch API - [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)/[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). This is a breaking change for HTTP-adapters, but should not affect you as a user. If you're building an adapter, check out how our adapters work [in the code](https://github.com/trpc/trpc/tree/main/packages/server/src/adapters) and don't be a stranger to ask for help in our [Discord](https://trpc.io/discord). ### `TRPCRequestInfo` has been updated (rarely breaking) Inputs are now materialised lazily when required by the procedure, which means the input and procedure type is no longer available when tRPC calls `createContext`. You can still access the input by calling `info.calls[index].getRawInput()`. ### All the experimental form-data support has been replaced (rarely breaking) > This only affects you if you used the experimental formdata features - experimental_formDataLink - use httpLink - experimental_parseMultipartFormData - not needed anymore - experimental_isMultipartFormDataRequest - not needed anymore - experimental_composeUploadHandlers - not needed anymore - experimental_createMemoryUploadHandler - not needed anymore - experimental_NodeOnDiskFile and experimental_createFileUploadHandler - not supported in this first release, open an issue if you need to hold data on disk - experimental_contentTypeHandlers - not needed anymore, but could come back if needed by the community for novel data types You can see the new approach in `examples/next-formdata` ### Moved `Procedure._def._output_in` / `Procedure._def._input_in` to `Procedure._def.$types` (non-breaking) This is a breaking change for tRPC internals, but should not affect you as a user. You don't have to do anything, unless you're using `Procedure._def._output_in` or `Procedure._def._input_in` directly in your code. ### Explicit Content-Type checks (non-breaking) We now have explicit checks for the `Content-Type`-header when doing POST-requests. This means that if you send a request with a `Content-Type` that doesn't match the expected one, you will get a `415 Unsupported Media Type`-error. Our tRPC clients already sends content-type headers, so is only a potential breaking change if you call tRPC manually. ### Added support for method overriding (rarely breaking) Allows you to override the HTTP method for procedures to always be sent with `POST` in order to get around some limitations with e.g. max URL lengths. Closes [#3910](https://github.com/trpc/trpc/issues/3910) ### Added support for bi-directional infinite queries (non-breaking) See [`useInfiniteQuery()`](https://trpc.io/docs/client/react/useInfiniteQuery.md) ### Added `inferProcedureBuilderResolverOptions`-helper (non-breaking) Adds a helper to infer the options for a procedure builder resolver. This is useful if you want to create reusable functions for different procedures. See test [here](https://github.com/trpc/trpc/blob/743fa6aed8ac889d9c60f321c4b4ad060b56e791/packages/server/src/unstable-core-do-not-import/procedureBuilder.test.ts#L36-L231) for a reference on how to use it ### Transformers are moved to links (breaking) - {#transformers-moved} > TypeScript will guide you through this migration > > Only applies if you use data transformers. You now set up data transformers in the `links`-array instead of when you initialize the tRPC-client; Wherever you have a HTTP Link you have to add `transformer: superjson` if you use transformers: ```ts httpBatchLink({ url: '/api/trpc', transformer: superjson, // <-- add this }); ``` ```ts import { createTRPCNext } from '@trpc/next'; import superjson from 'superjson'; import { AppRouter } from './appRouter' createTRPCNext({ // [..] transformer: superjson, // <-- add this }); ``` ### `@trpc/next` ssr mode now requires a prepass helper with `ssr: true` (rarely breaking) This is to fix https://github.com/trpc/trpc/issues/5378 where `react-dom` was imported regardless if you were using this functionality or not. See [SSR docs](https://trpc.io/docs/client/nextjs/pages-router/ssr.md) ### Added support for short-hand router definitions (non-breaking) See [Routers](https://trpc.io/docs/server/routers.md#inline-sub-router) ```ts const appRouter = router({ // Shorthand plain object for creating a sub-router nested1: { proc: publicProcedure.query(() => '...'), }, // Equivalent of: nested2: router({ proc: publicProcedure.query(() => '...'), }), }); ``` ### Deleted `inferHandlerInput` and `ProcedureArgs` (non-breaking for most) > If these types mean nothing for you or your codebase, just ignore this Use `inferProcedureInput` instead & `TRPCProcedureOptions` instead ### Added `useSuspenseQueries()` See [useSuspenseQueries](https://trpc.io/docs/client/react/suspense.md#usesuspensequeries) https://github.com/trpc/trpc/pull/5226 ### Refactor internal generics (rarely breaking) We have refactored our internal generics and made them more readable. ### React is now >=18.2.0 (rarely breaking) Check their migration guide: https://react.dev/blog/2022/03/08/react-18-upgrade-guide ### NodeJS 18+ and Modern Browsers are now required (rarely breaking) We have added usage of FormData, File, Blob, and ReadableStream. NodeJS 18 is now required, though these have been supported by browsers for many years now. ### `wsLink` improvements (minor) - Ability to pass a `Promise` in the `url`-callback if servers switch location during deploys - Added new `lazy` option that makes the websocket automatically disconnect when there are no pending requests ### `rawInput` in middleware is now a `getRawInput` (rarely breaking) While we're not doing anything differently internally (just yet) this is to help support a much requested feature in tRPC: content types other than JSON. ### Simplified types and `.d.ts` outputs Procedures in your router now only emit their input & output - where before they would also contain the full context object for every procedure, leading to unnecessary complexity in e.g. `.d.ts`. ### React Query peerDep is now v5 (breaking) - {#react-query-v5} > The main thing you'll need to do is to replace a bunch of `isLoading` to `isPending` Check their migration guide: https://tanstack.com/query/v5/docs/framework/react/guides/migrating-to-v5 ### Exports names `AbcProxyXyz` has been renamed to `AbcXyz` (non-breaking) The proxy names were due to v9 using the `AbcXyz` names, these have been removed and the proxy ones have been renamed to the non-proxy names, e.g: - `createTRPCClient` was deprecated from v9, and is now completely removed. The `createTRPCProxyClient` has been renamed to `createTRPCClient` instead. `createTRPCProxyClient` is now marked as deprecated. ### SSG Helpers (rarely breaking) - `createSSGHelpers` were for v9 which has now been removed. the v10 equivalent `createProxySSGHelpers` have been renamed to `createSSGHelpers` now instead. - `createProxySSGHelpers` is now deprecated but aliased to `createSSGHelpers` for backwards compatibility. - Removed exported type `CreateSSGHelpersOptions` ### `interop`-mode has been removed (rarely breaking) - {#interop-mode-removed} We have removed the `interop`-mode from tRPC. This was a mode that allowed you to have an easy transition period from v9 to v10. This mode was never meant to be supported long-term and we have now removed it.