new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

tRPC · all subjects

linking and http

32 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

tRPC Cache-Control headers for CDN and browser caching

Set Cache-Control headers on query responses for CDN and browser caching. Refer to caching skill for implementation patterns.

tRPC SuperJSON transformer for complex types

Use SuperJSON transformer for serializing and deserializing Date, Map, Set, and BigInt types. Refer to superjson skill for configuration.

tRPC client link configuration

Configure link chains in the client using the links array in createTRPCClient. Available links include httpBatchLink for batching requests. Refer to links skill for full configuration options.

tRPC service-oriented architecture patterns

Implement multi-service gateway, custom routing links, and SOA patterns with tRPC. Refer to service-oriented-architecture skill for details.

httpLink sends one operation per HTTP request

httpLink is a terminating link that sends one tRPC operation per HTTP request. It is imported from '@trpc/client'.

httpSubscriptionLink for Server-Sent Events (SSE) subscriptions

httpSubscriptionLink is a terminating link for Server-Sent Events (SSE) subscriptions. It is imported from '@trpc/client'. For cross-domain cookies, use eventSourceOptions: () => ({ withCredentials: true }).

httpLink options reference

httpLink accepts the following options: url (string | URL, required) - Server endpoint URL; fetch (typeof fetch, default global fetch) - Fetch ponyfill; transformer (DataTransformerOptions, default none) - Data transformer such as superjson; headers (HTTPHeaders | (opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>, default {}) - Static headers object or per-request callback; methodOverride ('POST', default none) - Force all requests as POST.

httpBatchLink batches multiple operations into single HTTP request

httpBatchLink is a terminating link that batches multiple operations into a single HTTP request. It is imported from '@trpc/client'.

httpBatchLink options reference

httpBatchLink accepts the following options: url (string | URL, required) - Server endpoint URL; fetch (typeof fetch, default global fetch) - Fetch ponyfill; transformer (DataTransformerOptions, default none) - Data transformer; headers (HTTPHeaders | (opts: { opList: Operation[] }) => HTTPHeaders | Promise<HTTPHeaders>, default {}) - Headers callback receives opList (array), not op; maxURLLength (number, default Infinity) - Split batch if URL exceeds this length; maxItems (number, default Infinity) - Maximum operations per batch; methodOverride ('POST', default none) - Force all requests as POST.

httpBatchStreamLink streams responses as they arrive

httpBatchStreamLink is a terminating link similar to httpBatchLink but streams responses as they arrive instead of waiting for all to complete. It inherits all httpBatchLink options and adds a streamHeader option.

httpBatchStreamLink options reference

httpBatchStreamLink inherits all httpBatchLink options. Additionally, it accepts: streamHeader ('trpc-accept' | 'accept', default 'trpc-accept') - Header used to signal streaming. Use 'accept' to avoid CORS preflight on cross-origin requests. Sends trpc-accept: application/jsonl (or Accept: application/jsonl). Response arrives as transfer-encoding: chunked with content-type: application/jsonl. Cannot set response headers (including cookies) after stream begins.

splitLink branches link chain based on condition

splitLink is a non-terminating link that branches the link chain based on a condition. It routes operations to different links depending on whether a predicate evaluates to true or false. Each branch creates its own sub-chain, so both branches need a terminating link.

splitLink options reference

splitLink accepts the following options: condition ((op: Operation) => boolean, required) - Route predicate; true (TRPCLink | TRPCLink[], required) - Link(s) for condition=true. Must include a terminating link; false (TRPCLink | TRPCLink[], required) - Link(s) for condition=false. Must include a terminating link.

loggerLink logs operations to console

loggerLink is a non-terminating link that logs operations to the console. It is imported from '@trpc/client'.

loggerLink options reference

loggerLink accepts the following options: enabled ((opts: { direction: 'up' | 'down'; result?: unknown }) => boolean, default () => true) - Control when logging is active; logger ((opts: LoggerOpts) => void, default built-in pretty logger) - Custom log function; console ({ log: Function; error: Function }, default globalThis.console) - Console implementation; colorMode ('ansi' | 'css' | 'none', default 'css' in browser, 'ansi' in Node) - Color output mode; withContext (boolean, default false, true if css) - Include operation context in log.

retryLink retries failed operations

retryLink is a non-terminating link that retries failed operations. It is imported from '@trpc/client'. When used with subscriptions that use tracked(), it automatically includes the last known event ID on retry.

retryLink options reference

retryLink accepts the following options: retry ((opts: { op, error, attempts }) => boolean, required) - Return true to retry; retryDelayMs ((attempt: number) => number, default () => 0) - Delay between retries in ms.

wsLink for WebSocket connections

wsLink is a terminating link for WebSocket connections. It requires a TRPCWebSocketClient created with createWSClient. It is imported from '@trpc/client'.

wsLink options reference

wsLink accepts the following options: client (TRPCWebSocketClient, required) - WebSocket client from createWSClient; transformer (DataTransformerOptions, default none) - Data transformer.

createWSClient options reference

createWSClient accepts the following options: url (string | (() => MaybePromise<string>), required) - WebSocket server URL; connectionParams (Record<string, string> | null | (() => MaybePromise<Record<string, string> | null>), default null) - Auth params sent as first message, available in createContext(); WebSocket (typeof WebSocket, default global WebSocket) - WebSocket ponyfill; retryDelayMs ((attemptIndex: number) => number, default exponential backoff) - Reconnection delay; onOpen (() => void, default none) - Connection opened callback; onError ((evt?: Event) => void, default none) - Connection error callback; onClose ((cause?: { code?: number }) => void, default none) - Connection closed callback; lazy.enabled (boolean, default false) - Close WS after inactivity; lazy.closeMs (number, default 0) - Idle timeout before closing; keepAlive.enabled (boolean, default false) - Send ping messages; keepAlive.intervalMs (number, default 5000) - Ping interval; keepAlive.pongTimeoutMs (number, default 1000) - Close if no pong within this time.

httpSubscriptionLink options reference

httpSubscriptionLink accepts the following options: url (string | (() => string | Promise<string>), required) - Server endpoint URL; connectionParams (Record<string, string> | null | (() => MaybePromise<...>), default none) - Serialized as URL query param; transformer (DataTransformerOptions, default none) - Data transformer; EventSource (EventSource constructor, default global EventSource) - EventSource ponyfill for custom headers; eventSourceOptions (EventSourceInit | ((opts: { op }) => EventSourceInit | Promise<EventSourceInit>), default none) - Options passed to EventSource constructor.

unstable_localLink for direct procedure calls

unstable_localLink is a terminating link for direct procedure calls without HTTP. It is useful for testing and server-side usage. It is imported from '@trpc/client'.

unstable_localLink options reference

unstable_localLink accepts the following options: router (AnyRouter, required) - tRPC router instance; createContext (() => Promise<Context>, required) - Context factory per call; onError ((opts: ErrorHandlerOptions) => void, default none) - Error handler; transformer (DataTransformerOptions, default none) - Data transformer.

Main link options in tRPC

The main link options available in tRPC are: httpLink (sends one operation per HTTP request), httpBatchLink (batches multiple operations into single HTTP request), httpBatchStreamLink (batches with streaming responses), wsLink (WebSocket connections), httpSubscriptionLink (Server-Sent Events), splitLink (conditional routing), loggerLink (console logging), retryLink (automatic retries), and unstable_localLink (direct calls without HTTP).

httpBatchLink example code

import { httpBatchLink } from '@trpc/client'; httpBatchLink({ url: 'http://localhost:3000/trpc', maxURLLength: 2083, maxItems: 10, headers({ opList }) { return { Authorization: `Bearer ${opList[0]?.context.token}` }; }, transformer: superjson, });

wsLink and createWSClient example code

import { createWSClient, wsLink } from '@trpc/client'; const wsClient = createWSClient({ url: 'ws://localhost:3000', connectionParams: () => ({ token: 'supersecret' }), lazy: { enabled: true, closeMs: 10_000 }, keepAlive: { enabled: true, intervalMs: 5_000, pongTimeoutMs: 1_000 }, }); wsLink<AppRouter>({ client: wsClient, transformer: superjson, });

httpSubscriptionLink example code

import { httpSubscriptionLink } from '@trpc/client'; import { EventSourcePolyfill } from 'event-source-polyfill'; httpSubscriptionLink({ url: 'http://localhost:3000/trpc', connectionParams: async () => ({ token: 'supersecret' }), transformer: superjson, EventSource: EventSourcePolyfill, eventSourceOptions: async ({ op }) => ({ headers: { authorization: 'Bearer token', }, }), });

splitLink example code

import { httpBatchLink, httpLink, httpSubscriptionLink, splitLink, } from '@trpc/client'; splitLink({ condition: (op) => op.type === 'subscription', true: httpSubscriptionLink({ url }), false: httpBatchLink({ url }), });

loggerLink example code

import { loggerLink } from '@trpc/client'; loggerLink({ enabled: (opts) => (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') || (opts.direction === 'down' && opts.result instanceof Error), colorMode: 'ansi', });

retryLink example code

import { retryLink } from '@trpc/client'; retryLink({ retry(opts) { if (opts.error.data?.code === 'INTERNAL_SERVER_ERROR') { return opts.attempts <= 3; } return false; }, retryDelayMs: (attempt) => Math.min(1000 * 2 ** attempt, 30000), });

unstable_localLink example code

import { unstable_localLink } from '@trpc/client'; import { appRouter } from './server'; unstable_localLink({ router: appRouter, createContext: async () => ({ db: prisma }), onError: (opts) => console.error('Error:', opts.error), });

Limit batch size with maxBatchSize

Pass maxBatchSize option to createNextApiHandler. Requests batching more than maxBatchSize operations are rejected with 400 Bad Request. Set maxItems on client httpBatchLink to the same value to avoid exceeding the limit.

Give your agent this brain