0
# Temporal TypeScript Client
1
2
The Temporal TypeScript Client (`@temporalio/client`) provides a comprehensive TypeScript/JavaScript interface for communicating with Temporal workflow orchestration systems. It enables developers to connect to Temporal services, start and manage workflows, send signals and queries, and handle durable execution patterns with strongly-typed APIs and seamless gRPC integration.
3
4
## Package Information
5
6
- **Package Name**: @temporalio/client
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @temporalio/client`
10
11
## Core Imports
12
13
```typescript
14
import { Client, Connection, WorkflowClient } from "@temporalio/client";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Client, Connection, WorkflowClient } = require("@temporalio/client");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { Client, Connection } from "@temporalio/client";
27
28
// Create connection to Temporal server
29
const connection = await Connection.connect({
30
address: 'localhost:7233', // Local Temporal server
31
});
32
33
// Create client with connection
34
const client = new Client({ connection });
35
36
// Start a workflow
37
const handle = await client.workflow.start('myWorkflowType', {
38
args: ['argument1', 'argument2'],
39
taskQueue: 'my-task-queue',
40
workflowId: 'my-workflow-id-1',
41
});
42
43
// Wait for result
44
const result = await handle.result();
45
console.log('Workflow result:', result);
46
```
47
48
## Architecture
49
50
The Temporal TypeScript Client is built around several key components:
51
52
- **Main Client**: High-level `Client` class that aggregates specialized sub-clients
53
- **Connection Management**: `Connection` class for managing gRPC connections to Temporal Server
54
- **Workflow Operations**: `WorkflowClient` for starting, querying, and managing workflow lifecycles
55
- **Schedule Management**: `ScheduleClient` for creating and managing scheduled workflow executions
56
- **Activity Completion**: `AsyncCompletionClient` for manually completing activities outside worker processes
57
- **Task Queue Operations**: `TaskQueueClient` for worker versioning and build ID management
58
- **Error Handling**: Comprehensive error classes for different failure scenarios
59
- **Interceptor System**: Pluggable interceptors for custom logging, metrics, and modification of client operations
60
- **Type System**: Full TypeScript integration with generics for type-safe workflow and activity operations
61
62
## Capabilities
63
64
### Main Client & Connection
65
66
Core client functionality for establishing connections and accessing sub-clients for different Temporal operations.
67
68
```typescript { .api }
69
class Client {
70
constructor(options: ClientOptions);
71
readonly workflow: WorkflowClient;
72
readonly activity: AsyncCompletionClient;
73
readonly schedule: ScheduleClient;
74
readonly taskQueue: TaskQueueClient;
75
readonly workflowService: WorkflowService;
76
withDeadline<R>(deadline: number | Date, fn: () => Promise<R>): Promise<R>;
77
withAbortSignal<R>(signal: AbortSignal, fn: () => Promise<R>): Promise<R>;
78
withMetadata<R>(metadata: Metadata, fn: () => Promise<R>): Promise<R>;
79
}
80
81
class Connection {
82
static connect(options: ConnectionOptions): Promise<Connection>;
83
static lazy(options: ConnectionOptions): Connection;
84
ensureConnected(): Promise<void>;
85
close(): Promise<void>;
86
withDeadline<R>(deadline: number | Date, fn: () => Promise<R>): Promise<R>;
87
withAbortSignal<R>(signal: AbortSignal, fn: () => Promise<R>): Promise<R>;
88
withMetadata<R>(metadata: Metadata, fn: () => Promise<R>): Promise<R>;
89
withApiKey<R>(apiKey: string, fn: () => Promise<R>): Promise<R>;
90
setApiKey(apiKey: string): void;
91
readonly workflowService: WorkflowService;
92
readonly operatorService: OperatorService;
93
readonly testService: TestService;
94
readonly healthService: HealthService;
95
}
96
97
interface ClientOptions {
98
connection?: ConnectionLike;
99
namespace?: string;
100
dataConverter?: DataConverter;
101
interceptors?: ClientInterceptors;
102
workflow?: {
103
queryRejectCondition?: QueryRejectCondition;
104
};
105
}
106
107
interface ConnectionOptions {
108
address?: string;
109
tls?: TLSConfig | boolean;
110
credentials?: ChannelCredentials;
111
callCredentials?: CallCredentials[];
112
channelArgs?: object;
113
interceptors?: Interceptor[];
114
metadata?: Metadata;
115
apiKey?: string;
116
connectTimeout?: string | number;
117
}
118
```
119
120
[Client & Connection](./client-connection.md)
121
122
### Workflow Operations
123
124
Complete workflow lifecycle management including starting workflows, handling updates, sending signals and queries, and managing workflow execution.
125
126
```typescript { .api }
127
class WorkflowClient {
128
start<T extends Workflow>(
129
workflowTypeOrFunc: string | T,
130
options: WorkflowStartOptions<T>
131
): Promise<WorkflowHandleWithFirstExecutionRunId<T>>;
132
execute<T extends Workflow>(
133
workflowTypeOrFunc: string | T,
134
options: WorkflowStartOptions<T>
135
): Promise<WorkflowResultType<T>>;
136
getHandle<T extends Workflow>(
137
workflowId: string,
138
runId?: string,
139
options?: GetWorkflowHandleOptions
140
): WorkflowHandle<WorkflowResultType<T>>;
141
list(options?: ListOptions): AsyncWorkflowListIterable;
142
count(query?: string): Promise<CountWorkflowExecution>;
143
}
144
145
interface WorkflowHandle<T> {
146
readonly workflowId: string;
147
readonly runId: string | undefined;
148
readonly firstExecutionRunId: string;
149
result(): Promise<T>;
150
terminate(reason?: string): Promise<void>;
151
cancel(): Promise<void>;
152
signal<Args extends any[]>(
153
def: SignalDefinition<Args> | string,
154
...args: Args
155
): Promise<void>;
156
query<Ret, Args extends any[]>(
157
def: QueryDefinition<Ret, Args> | string,
158
...args: Args
159
): Promise<Ret>;
160
executeUpdate<Ret, Args extends any[]>(
161
def: UpdateDefinition<Ret, Args> | string,
162
options?: WorkflowUpdateOptions,
163
...args: Args
164
): Promise<Ret>;
165
}
166
```
167
168
[Workflow Client](./workflow-client.md)
169
170
### Schedule Management
171
172
Manage scheduled workflow executions with flexible calendar-based and interval-based scheduling configurations.
173
174
```typescript { .api }
175
class ScheduleClient {
176
create<A extends any[]>(options: ScheduleOptions<A>): Promise<ScheduleHandle>;
177
getHandle(scheduleId: string): ScheduleHandle;
178
list(options?: ListScheduleOptions): AsyncIterable<ScheduleListEntry>;
179
}
180
181
interface ScheduleHandle {
182
readonly scheduleId: string;
183
describe(): Promise<ScheduleDescription>;
184
update<A extends any[]>(options: ScheduleUpdateOptions<A>): Promise<void>;
185
delete(): Promise<void>;
186
trigger(options?: TriggerImmediatelyOptions): Promise<void>;
187
pause(note?: string): Promise<void>;
188
unpause(note?: string): Promise<void>;
189
backfill(backfills: Backfill[]): Promise<void>;
190
}
191
192
interface ScheduleOptions<A extends any[]> {
193
scheduleId: string;
194
spec: ScheduleSpec;
195
action: ScheduleAction<A>;
196
policies?: SchedulePolicies;
197
state?: ScheduleState;
198
memo?: Record<string, any>;
199
searchAttributes?: SearchAttributes;
200
}
201
```
202
203
[Schedule Management](./schedule-client.md)
204
205
### Activity Completion
206
207
Manual activity completion for activities that complete outside the normal worker execution model.
208
209
```typescript { .api }
210
class AsyncCompletionClient {
211
complete<T = any>(
212
taskTokenOrActivityId: Uint8Array | string,
213
result?: T
214
): Promise<void>;
215
complete<T = any>(fullActivityId: FullActivityId, result?: T): Promise<void>;
216
fail(
217
taskTokenOrActivityId: Uint8Array | string,
218
err: unknown
219
): Promise<void>;
220
fail(fullActivityId: FullActivityId, err: unknown): Promise<void>;
221
reportCancellation(
222
taskTokenOrActivityId: Uint8Array | string,
223
details?: unknown
224
): Promise<void>;
225
heartbeat(
226
taskTokenOrActivityId: Uint8Array | string,
227
details?: unknown
228
): Promise<void>;
229
}
230
231
interface FullActivityId {
232
workflowId: string;
233
runId?: string;
234
activityId: string;
235
}
236
```
237
238
[Activity Completion](./activity-completion.md)
239
240
### Task Queue Management
241
242
Worker build ID versioning and task reachability management for gradual deployments and worker compatibility.
243
244
```typescript { .api }
245
class TaskQueueClient {
246
updateBuildIdCompatibility(
247
taskQueue: string,
248
operation: BuildIdOperation
249
): Promise<void>;
250
getBuildIdCompatability(
251
taskQueue: string
252
): Promise<WorkerBuildIdVersionSets>;
253
getReachability(options: ReachabilityOptions): Promise<ReachabilityResponse>;
254
}
255
256
type BuildIdOperation =
257
| AddNewIdInNewDefaultSet
258
| AddNewCompatibleVersion
259
| PromoteSetByBuildId
260
| PromoteBuildIdWithinSet
261
| MergeSets;
262
```
263
264
[Task Queue Management](./task-queue-client.md)
265
266
### Error Handling
267
268
Comprehensive error types for different failure scenarios in Temporal operations.
269
270
```typescript { .api }
271
class WorkflowFailedError extends Error {
272
readonly cause: TemporalFailure;
273
readonly workflowId: string;
274
readonly workflowType: string;
275
readonly runId: string;
276
}
277
278
class ServiceError extends Error {
279
readonly code: Status;
280
readonly details: string;
281
}
282
283
// Error checking utilities
284
function isGrpcServiceError(error: unknown): error is ServiceError;
285
function isGrpcDeadlineError(error: unknown): boolean;
286
function isGrpcCancelledError(error: unknown): boolean;
287
```
288
289
[Error Handling](./error-handling.md)
290
291
### Interceptors
292
293
Pluggable system for customizing client behavior through interceptors that can modify requests, responses, and add cross-cutting concerns.
294
295
```typescript { .api }
296
interface WorkflowClientInterceptor {
297
start?(
298
input: WorkflowStartInput,
299
next: WorkflowClientCallsInterceptor['start']
300
): Promise<WorkflowHandle>;
301
signalWithStart?(
302
input: WorkflowSignalWithStartInput,
303
next: WorkflowClientCallsInterceptor['signalWithStart']
304
): Promise<WorkflowHandle>;
305
signal?(
306
input: WorkflowSignalInput,
307
next: WorkflowClientCallsInterceptor['signal']
308
): Promise<void>;
309
query?(
310
input: WorkflowQueryInput,
311
next: WorkflowClientCallsInterceptor['query']
312
): Promise<unknown>;
313
}
314
315
interface ClientInterceptors {
316
workflow?: WorkflowClientInterceptor[];
317
schedule?: ScheduleClientInterceptor[];
318
}
319
```
320
321
[Interceptors](./interceptors.md)
322
323
## Types
324
325
### Core Types
326
327
```typescript { .api }
328
interface WorkflowExecution {
329
workflowId: string;
330
runId: string;
331
}
332
333
interface WorkflowExecutionInfo {
334
workflowExecution: WorkflowExecution;
335
workflowType: string;
336
startTime: Date;
337
executionTime?: Date;
338
closeTime?: Date;
339
status: WorkflowExecutionStatus;
340
historyLength: number;
341
parentExecution?: WorkflowExecution;
342
memo?: Memo;
343
searchAttributes?: SearchAttributes;
344
autoResetPoints?: AutoResetPoints;
345
taskQueue: string;
346
}
347
348
type Metadata = Record<string, string | Buffer | string[] | Buffer[]>;
349
350
interface CallContext {
351
deadline?: Date;
352
abortSignal?: AbortSignal;
353
}
354
355
type WorkflowResultType<T extends Workflow> = T extends (...args: any[]) => Promise<infer R> ? R : any;
356
357
interface WorkflowHandleWithFirstExecutionRunId<T = any> extends WorkflowHandle<T> {
358
readonly firstExecutionRunId: string;
359
}
360
361
interface CountWorkflowExecution {
362
count: number;
363
}
364
365
// Constants
366
const LOCAL_TARGET = 'localhost:7233';
367
```