Skip to content
Back to skills

Trpc Knowledge Patch

ASecurity

tRPC

  • 25 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added May 27, 2026
developmenttypescriptreactnextjsnodeexpressapi

Works with

  • cursor
  • cli
  • api

Security analysis

A96/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro scans all 6 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Nevaberry/nevaberry-plugins --skill trpc-knowledge-patch --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Trpc Knowledge Patch?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Trpc Knowledge Patch
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nevaberry-trpc-knowledge-patch/badge)](https://www.skillsdirectory.com/skills/nevaberry-trpc-knowledge-patch)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: trpc-knowledge-patch
description: tRPC
version: "11.35.1"
license: MIT
metadata:
  author: Nevaberry
---


# tRPC Knowledge Patch

Load this skill when working on tRPC clients, routers, HTTP transports,
subscriptions, OpenAPI generation, or React and Next.js integrations.
Use the topic references for complete guidance and examples.

## Reference index

| Reference | Topics |
| --- | --- |
| [Migration and Core APIs](references/migration-and-core.md) | Local calls, resolver types, subscription inference, React proxy coercion, lazy and merged routers, standalone HTTP and HTTP/2 adapters |
| [Non-JSON Inputs and HTTP Transport](references/non-json-and-http.md) | Transformers, body parsing, binary inputs, empty bodies, batch limits, middleware headers, Express paths |
| [OpenAPI](references/openapi.md) | Alpha generator, document and schema types, procedure mapping, Hey API clients, transformer-aware generated types |
| [Streaming and Retry Links](references/streaming-and-retry.md) | Streamed batches, response headers, async generators, error isolation, keepalives, runtime requirements, retry policies |
| [Subscriptions](references/subscriptions.md) | React hook migration and state, callback-free iteration, output validation, cursors, SSE configuration, WebSocket reconnects |
| [TanStack Query and Next.js](references/tanstack-and-nextjs.md) | Classic integration deprecation, key prefixes, prefetching, Server Components, experimental Server Actions, cache scope, coding-agent setup |

## Deprecations and migration

Every published version of `@trpc/react-query` is deprecated on npm.
The classic and TanStack-native integrations can coexist in one app, allowing
migration one component at a time. Classic proxy hooks cannot be linted correctly
under the Rules of Hooks; passing them as props can break under React Compiler.

To pause `useSubscription`, pass `skipToken` in the input position.
The `enabled` option is deprecated for removal in v12.

```ts
import { skipToken } from '@tanstack/react-query';

const subscription = trpc.onPostAdd.useSubscription(paused ? skipToken : undefined);
```

## HTTP inputs and response headers

When the server has a transformer, TypeScript requires one on both HTTP links.
Route `isNonJsonSerializable(op.input)` to `httpLink` with passthrough request
serialization and the server's response deserializer. Use the full transformer
on the `httpBatchLink` or `httpBatchStreamLink` branch.

tRPC parses bodies according to `Content-Type` and needs access before host
middleware consumes them. When mounting tRPC at `/trpc` in Express, scope JSON
parsing to other routes with `app.use('/rest', express.json())`.

For raw `Blob`, `Uint8Array`, or `File` mutation inputs, use `octetInputParser`
from `@trpc/server/http`; the resolver receives a `ReadableStream`.
The Node HTTP adapter passes a pre-populated `Buffer` in `req.body` through as
bytes, and the Fastify plugin accepts binary inputs.

An empty POST body is `undefined` input; the Node HTTP adapter also treats an
empty pre-parsed body as no input. The server can cap the number of procedure
calls in a single incoming batch request.

tRPC preserves `Set-Cookie` headers already set before `responseMeta` and retains
`Vary` set by middleware. With `httpBatchStreamLink`, headers are sent before
result data is available, so `responseMeta` receives no procedure results in
`data`. Use `httpBatchLink` for procedures that set headers such as `Set-Cookie`.

## Streamed batches and retries

Set `streamHeader` on `httpBatchStreamLink` to choose the request header that
signals acceptance of a streamed batch response. Already-buffered result chunks
remain readable after the response stream closes.

A query can return an async generator through `httpBatchStreamLink`.
Await the query to obtain the iterable, then consume arriving values:

```ts
const updates = await trpc.examples.iterable.query();
for await (const update of updates) {
  console.log(update);
}
```

Set `jsonl.pingMs` in the root server configuration to keep streamed batch
responses alive while waiting for results. React Native needs a streaming-capable
`fetch` implementation and decoder polyfills; see the streaming reference for
the additional conditional stream polyfills and server runtime requirements.

Streaming `onError` receives the underlying error unwrapped from `cause`.
Streamed batch errors use the failing call's original batch index. A throwing
`errorFormatter` leaves the rest of the batch running, and a JSONL serialization
failure fails only the call that produced the value.

Place `retryLink` before the terminating link and supply
`retry({ op, error, attempts })`. The initial failed call counts as attempt 1,
so `attempts <= 3` allows three retries. Optional `retryDelayMs(attempt)` sets
the delay in milliseconds; the default delay is zero.

For an SSE subscription using `tracked()`, an approved retry carries the last
received event ID through `httpSubscriptionLink` so the procedure can resume.

## Subscription consumption and reconnection

Calling a client's `.subscribe()` without callbacks returns an async iterable.
For an input-free `events` procedure:

```ts
for await (const event of client.events.subscribe(undefined)) {
  console.log(event);
}
```

Subscription procedures support output validators. A Zod 4 output schema can
wrap an async iterable and validate each yield; use `isTrackedEnvelope` to
validate the envelope and rewrap the parsed payload with `tracked(id, payload)`
to preserve its cursor. See the subscription reference for the complete schema.

For SSE and WebSockets, accept `lastEventId` in the procedure input. The client
can provide the initial cursor; on reconnect, read `input.lastEventId` to fetch
missed events. Resuming also preserves non-plain-object inputs.

A generator error reaches server `onError`. Procedure errors with 5xx codes
trigger automatic client reconnection; other procedure errors end the
subscription and reach client `onError`.

Native `EventSource` reconnection reuses its original URL and options.
A `retryLink` before `httpSubscriptionLink` can retry a procedure error such as
`UNAUTHORIZED` with a fresh `EventSource`, rerunning `url` and
`eventSourceOptions` factories to pick up renewed credentials.

SSE reconnects after the server closes a stream at `maxDurationMs`.
Set `sse.client.reconnectAfterInactivityMs` to reconnect after silence;
pings count as activity, so set `sse.ping.intervalMs` below that timeout when
enabling pings. On a serverless runtime that cannot stream responses,
`sse.emitAndEndImmediately: true` ends the response after its first data item.

`useSubscription` exposes `idle`, `connecting`, `pending` (connected), and
`error` (unrecoverable) statuses, plus `reset()` to reconnect. `connecting` can
carry the last connection error. Server completion calls `onComplete`, returns
the hook to `idle`, and sets `data: undefined`.

## Experimental Server Actions and Server Components

Pair `.experimental_caller(...)` with `experimental_nextAppDirCaller` to export
a mutation as a typed async function from a `'use server'` module. This supports
the argument shift introduced by React's `useActionState`.

Actions bypass the HTTP adapter: load session context in `.use()` and map
`.meta()` to an action path with `pathExtractor` for logging and tracing.
Return `''` from a custom `pathExtractor` when there is no path to extract.

The Server Action caller passes only validated input to procedures and converts
indexed FormData fields to arrays only when the indices have no gaps.
It passes submitted input to `onError`, reports FormData normalization and
`createContext` errors through that hook, and rethrows Next.js errors.

For Server Components, configure `createTRPCOptionsProxy` with a request-scoped
QueryClient getter plus local `router` and `ctx` callback to run queries in
process. For a separately hosted router, pass a tRPC `client` alongside
`queryClient`.

Start queries with the React Server Component prefetch helpers. The client can
hydrate its React Query cache from a pending promise even while the procedure
is still running when the server component renders.
`experimental_nextCacheLink` can reuse results across requests.

## Query keys and query lifecycle

Query Key Prefixing namespaces generated query keys under a chosen key in a
shared QueryClient. Generated mutation options in `@trpc/tanstack-react-query`
include the configured prefix in `mutationKey`, allowing prefix-scoped filters.

With unprefixed tRPC keys, `queryKey[1]?.type === 'infinite'` identifies infinite
query options for a shared server helper to choose the matching prefetch method.
Pass `skipToken` from `@tanstack/react-query` as an entry to skip in
`@trpc/tanstack-react-query`'s `loadHandles`.

Setting `abortOnUnmount: true` in `createTRPCReact` also aborts `useQueries`
and infinite queries on unmount.

## Router composition and local calls

`unstable_localLink` terminates a client link chain with in-process queries,
mutations, and subscriptions, including abort signal support. Its zero-argument
`createContext` returns a promise for each procedure call; the link also accepts
`transformer` and `onError`.

Use `lazy` from `@trpc/server` to load a child router module on demand while
keeping its procedure paths. Return the import directly for a module exporting
exactly one router, or select the desired export when it exports several.
A rejected `lazy()` load can be retried when another request needs the router.
`mergeRouters` keeps the first router's root options; put that router first.

The standalone adapter's `basePath` defaults to `'/'` and strips the configured
prefix before procedure lookup. For `'/trpc/'`, `/trpc/post.list` becomes
`post.list`. Check the prefix before forwarding requests on a shared Node server.
Pass the handler from `createHTTP2Handler` to Node's HTTP/2 server;
`CreateHTTP2ContextOptions` provides HTTP/2 `req`, `res`, and request metadata
in `info`.

## OpenAPI generation and generated clients

The alpha `@trpc/openapi` package statically analyzes an exported TypeScript
router type to emit OpenAPI 3.1. It infers return types when `.output()` is
omitted and carries Zod `.describe()` text and router/procedure JSDoc into the spec.

```sh
pnpm add @trpc/openapi
pnpm exec trpc-openapi ./src/server/router.ts -e AppRouter -o openapi.json
```

Queries map to `GET /procedure.path`, mutations to `POST /procedure.path`, and
subscriptions are omitted. For a custom client generator, encode GET input as
a single `input` query parameter containing JSON and use the server's configured
transformer for input and output.

After `pnpm exec openapi-ts -i openapi.json -o ./generated`, call
`configureTRPCHeyApiClient` for request serialization, response parsing, and
error deserialization even with plain JSON. Queries take `{ query: { input } }`;
mutations take `{ body }`. Pass the server's transformer in the runtime options.
For native SDK types such as `Date`, configure the TypeScript plugin's
`~resolvers` with `createTRPCHeyApiTypeResolvers()`.

## Type helpers and coding-agent setup

`@trpc/client` exports `SubscriptionResolver` and `ResolverDef` for client-side
helpers. tRPC also provides TypeScript helpers for deriving subscription types
from procedure definitions.

The setup guide uses the TanStack Intent CLI to install tRPC coding-agent skills:

```sh
npx @tanstack/intent@latest install
```

Files in this skill

  • SKILL.md6.6 KB
  • references/advanced-features.md3.2 KB
  • references/nextjs-server-actions.md1.6 KB
  • references/subscriptions-streaming.md3 KB
  • references/tanstack-react-query.md1.8 KB
  • references/v11-migration.md793 B

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.