{postQuery.data.title}
{postQuery.data.text}
# 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 >
## 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:ZodType, e.g. z.string() or z.object({}).
YupSchema, e.g. yup.string() or yup.object({}).
v.string() or v.object({}).
| 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?" |
| Description | Links |
|---|---|
| Standalone tRPC Server | |
| Standalone tRPC Server with CORS handling |
| Description | Links |
|---|---|
| Express server & procedure calls with Node.js. |
| Description | Links |
|---|---|
|
| Description | Links |
|---|---|
Next.js Prisma Starter: an API route with createNextApiHandler |
|
Next.js Minimal Starter: an App Router route handler with fetchRequestHandler |
| Description | Links |
|---|---|
| API Gateway with NodeJS client. | |
| API Gateway REST API with response streaming. |
| Description | Links |
|---|---|
| Cloudflare Workers example | Source |
| Deno Deploy example | Source |
| Next.js Edge Runtime example | Source |
| Vercel Edge Runtime example | Source |
>
> 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{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{userQuery.data?.name}
{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{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{helloQuery.data?.greeting}
{userQuery.data?.name}
{JSON.stringify(helloNoArgs.data, null, 2)}
{JSON.stringify(helloWithArgs.data, null, 2)}
Something went wrong! {mutation.error.message}
}Connecting...
} {subscription.status === 'error' && (Error: {subscription.error.message}
{greeting.data?.message}
Loading...
; case 'error': returnError: {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 = ReturnTypeLoading...
; case 'error': returnError: {postQuery.error.message}
; case 'success': return ({postQuery.data.text}
Loading...
; case 'error': returnError: {postQuery.error.message}
; case 'success': { const post = postQuery.data; return ({post.text}
Loading...
; case 'error': returnError: {postQuery.error.message}
; case 'success': return ({postQuery.data.text}
Loading...
; case 'error': returnError: {postQuery.error.message}
; case 'success': return| 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
|
| Description | URL | Links |
|---|---|---|
Next.js starter with Prisma, E2E testing, & ESLint.
Quick start with
|
nextjs.trpc.io | |
|
zART-stack example (zero-API, TypeScript, React).
Monorepo setup with React Native, Next.js, & Prisma Quick start with
|
n/a | |
Next.js TodoMVC-example with SSG & Prisma.
Quick start with
|
todomvc.trpc.io |
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
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
--- 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. Become a Sponsor! ### π₯ Silver SponsorsThank you for the quick fix and the amazing project π―
— mgranderath May 3, 2021
Greptile |
CodeRabbit |
![]() SerpApi |
{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