A TypeScript-first client library for tRPC that enables end-to-end type-safe communication between client and server applications.
npx @tessl/cli install tessl/npm-trpc--client@11.5.00
# @trpc/client
1
2
@trpc/client is a type-safe client library for communicating with tRPC servers, supporting queries, mutations, and subscriptions through various transport mechanisms. It provides full TypeScript inference and compile-time type safety when connected to your tRPC router definitions.
3
4
## Package Information
5
6
- **Package Name**: @trpc/client
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @trpc/client`
10
11
## Core Imports
12
13
```typescript
14
import { createTRPCClient, httpBatchLink, httpLink, TRPCClientError } from "@trpc/client";
15
import { wsLink, createWSClient } from "@trpc/client";
16
import { loggerLink, splitLink } from "@trpc/client";
17
```
18
19
For CommonJS:
20
21
```javascript
22
const { createTRPCClient, httpBatchLink, httpLink, TRPCClientError } = require("@trpc/client");
23
const { wsLink, createWSClient } = require("@trpc/client");
24
const { loggerLink, splitLink } = require("@trpc/client");
25
```
26
27
## Basic Usage
28
29
```typescript
30
import { createTRPCClient, httpBatchLink } from "@trpc/client";
31
import type { AppRouter } from "./server"; // Import your router type
32
33
// Create client with HTTP transport
34
const client = createTRPCClient<AppRouter>({
35
links: [
36
httpBatchLink({
37
url: "http://localhost:3000/trpc",
38
}),
39
],
40
});
41
42
// Use the client
43
const user = await client.user.getById.query({ id: 1 });
44
const newUser = await client.user.create.mutate({
45
name: "Alice",
46
email: "alice@example.com",
47
});
48
49
// Subscribe to real-time updates (with WebSocket)
50
client.posts.onUpdate.subscribe(undefined, {
51
onData: (post) => console.log("Post updated:", post),
52
onError: (err) => console.error("Subscription error:", err),
53
});
54
```
55
56
## Architecture
57
58
@trpc/client is built around several key components:
59
60
- **Type-Safe Client**: Main `TRPCClient` with full TypeScript inference from server router definitions
61
- **Untyped Client**: Lower-level `TRPCUntypedClient` for dynamic operations without compile-time type safety
62
- **Link Chain**: Middleware system where transport and utility links can be composed together
63
- **Transport Links**: HTTP, WebSocket, and local transport mechanisms for server communication
64
- **Error System**: Structured error handling with `TRPCClientError` providing detailed error information
65
- **Proxy Interface**: Router procedures are automatically transformed into client methods through JavaScript proxies
66
67
## Capabilities
68
69
### Client Creation
70
71
Core client factory functions for creating type-safe and untyped tRPC clients with configurable transport links.
72
73
```typescript { .api }
74
function createTRPCClient<TRouter extends AnyRouter>(
75
opts: CreateTRPCClientOptions<TRouter>
76
): TRPCClient<TRouter>;
77
78
function createTRPCUntypedClient<TRouter extends AnyRouter>(
79
opts: CreateTRPCClientOptions<TRouter>
80
): TRPCUntypedClient<TRouter>;
81
82
interface CreateTRPCClientOptions<TRouter> {
83
links: TRPCLink<TRouter>[];
84
}
85
```
86
87
[Client Creation](./client-creation.md)
88
89
### HTTP Transport Links
90
91
HTTP-based transport mechanisms including standard HTTP, batching, streaming, and subscription capabilities for queries and mutations.
92
93
```typescript { .api }
94
function httpLink<TRouter extends AnyRouter>(
95
opts: HTTPLinkOptions<TRouter['_def']['_config']['$types']>
96
): TRPCLink<TRouter>;
97
98
function httpBatchLink<TRouter extends AnyRouter>(
99
opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>
100
): TRPCLink<TRouter>;
101
102
function httpBatchStreamLink<TRouter extends AnyRouter>(
103
opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>
104
): TRPCLink<TRouter>;
105
106
function httpSubscriptionLink<TRouter extends AnyRouter>(
107
opts: HTTPSubscriptionLinkOptions<TRouter['_def']['_config']['$types']>
108
): TRPCLink<TRouter>;
109
110
interface HTTPLinkOptions<TTypes> {
111
url: string;
112
headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
113
transformer?: TTypes['transformer'];
114
fetch?: TRPCFetch;
115
}
116
```
117
118
[HTTP Transport Links](./http-links.md)
119
120
### WebSocket Links
121
122
Real-time communication through WebSocket connections for subscriptions and bidirectional communication.
123
124
```typescript { .api }
125
function wsLink<TRouter extends AnyRouter>(
126
opts: WSLinkOptions<TRouter>
127
): TRPCLink<TRouter>;
128
129
function createWSClient(opts: WebSocketClientOptions): TRPCWebSocketClient;
130
131
interface WSLinkOptions<TRouter> {
132
client: TRPCWebSocketClient;
133
transformer?: TRouter['_def']['_config']['$types']['transformer'];
134
}
135
136
interface WebSocketClientOptions {
137
url: string;
138
WebSocket?: typeof WebSocket;
139
retryDelayMs?: (attemptIndex: number) => number;
140
onOpen?: (ws: WebSocket) => void;
141
onError?: (event: Event) => void;
142
onClose?: (event: CloseEvent) => void;
143
lazy?: boolean;
144
keepAlive?: number;
145
}
146
```
147
148
[WebSocket Links](./websocket-links.md)
149
150
### Error Handling
151
152
Comprehensive error handling system with structured error information and type guards for error identification.
153
154
```typescript { .api }
155
class TRPCClientError<TRouterOrProcedure extends InferrableClientTypes> extends Error {
156
readonly message: string;
157
readonly shape: Maybe<inferErrorShape<TRouterOrProcedure>>;
158
readonly data: Maybe<inferErrorShape<TRouterOrProcedure>['data']>;
159
readonly cause: Error;
160
meta: Record<string, unknown>;
161
162
static from<TRouterOrProcedure extends InferrableClientTypes>(
163
cause: Error | TRPCErrorResponse | object,
164
opts?: { meta?: Record<string, unknown> }
165
): TRPCClientError<TRouterOrProcedure>;
166
}
167
168
function isTRPCClientError<TInferrable extends InferrableClientTypes>(
169
cause: unknown
170
): cause is TRPCClientError<TInferrable>;
171
```
172
173
[Error Handling](./error-handling.md)
174
175
### Utility Links
176
177
Middleware links for logging, conditional routing, retry logic, and other cross-cutting concerns in the link chain.
178
179
```typescript { .api }
180
function loggerLink<TRouter extends AnyRouter>(
181
opts?: LoggerLinkOptions<TRouter>
182
): TRPCLink<TRouter>;
183
184
function splitLink<TRouter extends AnyRouter>(
185
opts: SplitLinkOptions<TRouter>
186
): TRPCLink<TRouter>;
187
188
function retryLink<TInferrable extends InferrableClientTypes>(
189
opts: RetryLinkOptions<TInferrable>
190
): TRPCLink<TInferrable>;
191
```
192
193
[Utility Links](./utility-links.md)
194
195
### Advanced Features
196
197
Advanced functionality including local transport for in-process communication, fetch utilities, and unstable internal APIs.
198
199
```typescript { .api }
200
function unstable_localLink<TRouter extends AnyRouter>(
201
opts: LocalLinkOptions<TRouter>
202
): TRPCLink<TRouter>;
203
204
function getFetch(customFetchImpl?: FetchEsque | NativeFetchEsque): FetchEsque;
205
206
interface LocalLinkOptions<TRouter> {
207
router: TRouter;
208
createContext?: () => any;
209
onError?: (err: Error) => void;
210
transformer?: TRouter['_def']['_config']['$types']['transformer'];
211
}
212
```
213
214
[Advanced Features](./advanced-features.md)