0
# Connection Management
1
2
NATS connection management provides robust connection handling with authentication, TLS security, automatic reconnection, and graceful shutdown capabilities.
3
4
## Capabilities
5
6
### Connect Function
7
8
Establishes a connection to one or more NATS servers with comprehensive configuration options.
9
10
```typescript { .api }
11
/**
12
* Connect to NATS server(s) with optional configuration
13
* @param opts - Connection options including servers, auth, and behavior settings
14
* @returns Promise resolving to NatsConnection instance
15
*/
16
function connect(opts?: ConnectionOptions): Promise<NatsConnection>;
17
18
interface ConnectionOptions {
19
/** NATS server URLs - single string or array (default: 127.0.0.1:4222) */
20
servers?: string[] | string;
21
/** Port number on localhost (mutually exclusive with servers) */
22
port?: number;
23
/** Username for basic authentication */
24
user?: string;
25
/** Password for basic authentication */
26
pass?: string;
27
/** Authentication token */
28
token?: string;
29
/** Custom authenticator function */
30
authenticator?: Authenticator | Authenticator[];
31
/** Enable automatic reconnection (default: true) */
32
reconnect?: boolean;
33
/** Maximum reconnection attempts (-1 for unlimited, default: 10) */
34
maxReconnectAttempts?: number;
35
/** Milliseconds to wait between reconnection attempts (default: 2000) */
36
reconnectTimeWait?: number;
37
/** Upper bound for random reconnect delay (default: 100ms) */
38
reconnectJitter?: number;
39
/** Upper bound for random TLS reconnect delay (default: 1000ms) */
40
reconnectJitterTLS?: number;
41
/** Function returning reconnect delay in milliseconds */
42
reconnectDelayHandler?: () => number;
43
/** Connection timeout in milliseconds (default: 20000) */
44
timeout?: number;
45
/** Ping interval in milliseconds (default: 2 minutes) */
46
pingInterval?: number;
47
/** Maximum outstanding pings before considering connection stale (default: 2) */
48
maxPingOut?: number;
49
/** Client name for identification */
50
name?: string;
51
/** Enable verbose protocol logging */
52
verbose?: boolean;
53
/** Enable pedantic mode for strict protocol compliance */
54
pedantic?: boolean;
55
/** TLS/SSL configuration (set to null to disable TLS) */
56
tls?: TlsOptions | null;
57
/** Ignore cluster topology updates */
58
ignoreClusterUpdates?: boolean;
59
/** Custom inbox prefix for replies (default: "_INBOX") */
60
inboxPrefix?: string;
61
/** Disable message echo back to publisher */
62
noEcho?: boolean;
63
/** Enable debug logging */
64
debug?: boolean;
65
/** Disable server list randomization */
66
noRandomize?: boolean;
67
/** Wait for first connection before counting reconnect attempts */
68
waitOnFirstConnect?: boolean;
69
/** Ignore auth error abort */
70
ignoreAuthErrorAbort?: boolean;
71
/** Disable async stack traces for performance */
72
noAsyncTraces?: boolean;
73
}
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { connect } from "nats";
80
81
// Simple connection
82
const nc = await connect();
83
84
// Multiple servers with authentication
85
const nc = await connect({
86
servers: ["nats://server1:4222", "nats://server2:4222"],
87
user: "myuser",
88
pass: "mypass"
89
});
90
91
// Token authentication
92
const nc = await connect({
93
servers: "nats://localhost:4222",
94
token: "my-auth-token"
95
});
96
97
// Custom timeout and reconnection settings
98
const nc = await connect({
99
servers: "nats://localhost:4222",
100
timeout: 10000,
101
reconnectTimeWait: 5000,
102
maxReconnectAttempts: 20
103
});
104
```
105
106
### Connection Lifecycle
107
108
Methods for managing connection state, monitoring health, and graceful shutdown.
109
110
```typescript { .api }
111
interface NatsConnection {
112
/** Information about the currently connected server */
113
info?: ServerInfo;
114
115
/**
116
* Close the connection immediately
117
* @returns Promise that resolves when connection is closed
118
*/
119
close(): Promise<void>;
120
121
/**
122
* Monitor connection close status
123
* @returns Promise that resolves when connection closes (with Error if abnormal)
124
*/
125
closed(): Promise<void | Error>;
126
127
/**
128
* Gracefully drain and close the connection
129
* Ensures all subscriptions process pending messages before closing
130
* @returns Promise that resolves when drain completes
131
*/
132
drain(): Promise<void>;
133
134
/** Check if connection is closed */
135
isClosed(): boolean;
136
137
/** Check if connection is draining */
138
isDraining(): boolean;
139
140
/**
141
* Flush pending operations and wait for server acknowledgment
142
* @returns Promise that resolves when flush completes
143
*/
144
flush(): Promise<void>;
145
146
/**
147
* Measure round-trip time to server
148
* @returns Promise resolving to RTT in milliseconds
149
*/
150
rtt(): Promise<number>;
151
152
/** Get the hostport of connected server */
153
getServer(): string;
154
155
/** Get connection statistics */
156
stats(): Stats;
157
158
/**
159
* Monitor connection status events
160
* @returns AsyncIterable of Status events
161
*/
162
status(): AsyncIterable<Status>;
163
164
/**
165
* Force reconnection (experimental API)
166
* May disconnect and reconnect based on reconnection policy
167
*/
168
reconnect(): void;
169
}
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
import { connect, Events } from "nats";
176
177
const nc = await connect();
178
179
// Monitor connection status
180
(async () => {
181
for await (const status of nc.status()) {
182
switch (status.type) {
183
case Events.Disconnect:
184
console.log("Disconnected from server");
185
break;
186
case Events.Reconnect:
187
console.log("Reconnected to server");
188
break;
189
case Events.Error:
190
console.error("Connection error:", status.data);
191
break;
192
}
193
}
194
})();
195
196
// Check connection health
197
console.log(`RTT: ${await nc.rtt()}ms`);
198
console.log(`Connected to: ${nc.getServer()}`);
199
console.log(`Stats:`, nc.stats());
200
201
// Graceful shutdown
202
await nc.drain();
203
console.log("Connection drained and closed");
204
```
205
206
### Authentication
207
208
Various authentication methods including basic auth, tokens, NKeys, and JWT.
209
210
```typescript { .api }
211
type Authenticator = (nonce?: string) => Auth;
212
213
interface Auth {
214
user?: string;
215
pass?: string;
216
auth_token?: string;
217
nkey?: string;
218
sig?: string;
219
jwt?: string;
220
}
221
222
interface NoAuth extends Auth {}
223
224
interface UserPass extends Auth {
225
user: string;
226
pass: string;
227
}
228
229
interface TokenAuth extends Auth {
230
auth_token: string;
231
}
232
233
interface NKeyAuth extends Auth {
234
nkey: string;
235
sig: string;
236
}
237
238
interface JwtAuth extends Auth {
239
jwt: string;
240
nkey?: string;
241
sig?: string;
242
}
243
244
/** Build authenticator from connection options */
245
function buildAuthenticator(opts: ConnectionOptions): Authenticator;
246
247
/** Create username/password authenticator */
248
function usernamePasswordAuthenticator(user: string, pass: string): Authenticator;
249
250
/** Create token authenticator */
251
function tokenAuthenticator(token: string): Authenticator;
252
253
/** Create NKey authenticator */
254
function nkeyAuthenticator(nkey: Uint8Array): Authenticator;
255
256
/** Create JWT authenticator */
257
function jwtAuthenticator(jwt: string, sk?: Uint8Array): Authenticator;
258
259
/** Create credentials file authenticator */
260
function credsAuthenticator(creds: Uint8Array): Authenticator;
261
```
262
263
**Usage Examples:**
264
265
```typescript
266
import { connect, credsAuthenticator, nkeyAuthenticator } from "nats";
267
import { readFileSync } from "fs";
268
269
// Credentials file authentication
270
const creds = readFileSync("./user.creds");
271
const nc = await connect({
272
servers: "nats://localhost:4222",
273
authenticator: credsAuthenticator(creds)
274
});
275
276
// NKey authentication
277
const nkey = readFileSync("./user.nk");
278
const nc = await connect({
279
servers: "nats://localhost:4222",
280
authenticator: nkeyAuthenticator(nkey)
281
});
282
```
283
284
### TLS Configuration
285
286
Secure connection options including client certificates and custom CA validation.
287
288
```typescript { .api }
289
interface TlsOptions {
290
/** Client certificate */
291
cert?: string;
292
/** Client private key */
293
key?: string;
294
/** Certificate authority certificates */
295
ca?: string;
296
/** Custom certificate verification function */
297
checkServerIdentity?: (hostname: string, cert: any) => Error | undefined;
298
/** Reject unauthorized certificates (default: true) */
299
rejectUnauthorized?: boolean;
300
/** Handshake timeout in milliseconds */
301
timeout?: number;
302
}
303
```
304
305
**Usage Examples:**
306
307
```typescript
308
import { connect } from "nats";
309
import { readFileSync } from "fs";
310
311
// TLS with client certificates
312
const nc = await connect({
313
servers: "tls://localhost:4222",
314
tls: {
315
cert: readFileSync("./client-cert.pem"),
316
key: readFileSync("./client-key.pem"),
317
ca: readFileSync("./ca.pem")
318
}
319
});
320
321
// TLS with custom verification
322
const nc = await connect({
323
servers: "tls://localhost:4222",
324
tls: {
325
rejectUnauthorized: false
326
}
327
});
328
```
329
330
## Types
331
332
```typescript { .api }
333
interface Stats {
334
/** Bytes received by client */
335
inBytes: number;
336
/** Bytes sent by client */
337
outBytes: number;
338
/** Messages received by client */
339
inMsgs: number;
340
/** Messages sent by client */
341
outMsgs: number;
342
}
343
344
interface Status {
345
/** Event type */
346
type: Events | DebugEvents;
347
/** Event data */
348
data: string | ServersChanged | number;
349
/** Permission context for auth errors */
350
permissionContext?: { operation: string; subject: string };
351
}
352
353
interface ServersChanged {
354
/** Newly discovered servers */
355
readonly added: string[];
356
/** Removed servers */
357
readonly deleted: string[];
358
}
359
360
interface ServerInfo {
361
/** Server ID */
362
server_id: string;
363
/** Server name */
364
server_name: string;
365
/** NATS server version */
366
version: string;
367
/** Protocol version */
368
proto: number;
369
/** Server hostname */
370
host: string;
371
/** Server port */
372
port: number;
373
/** Headers support available */
374
headers?: boolean;
375
/** Maximum message payload size */
376
max_payload: number;
377
/** JetStream available */
378
jetstream?: boolean;
379
/** Authentication required */
380
auth_required?: boolean;
381
/** TLS required */
382
tls_required?: boolean;
383
/** TLS available */
384
tls_available?: boolean;
385
/** Client ID assigned by server */
386
client_id: number;
387
/** Client IP as seen by server */
388
client_ip?: string;
389
/** Cluster name */
390
cluster?: string;
391
/** Other servers in cluster */
392
connect_urls?: string[];
393
/** Server in lame duck mode */
394
ldm?: boolean;
395
/** Git commit of server build */
396
git_commit?: string;
397
/** Go version used to build server */
398
go: string;
399
/** Nonce for challenge/response auth */
400
nonce?: string;
401
/** TLS verification required */
402
tls_verify?: boolean;
403
}
404
405
enum Events {
406
/** Client disconnected */
407
Disconnect = "disconnect",
408
/** Client reconnected */
409
Reconnect = "reconnect",
410
/** Cluster update received */
411
Update = "update",
412
/** Server entering lame duck mode */
413
LDM = "ldm",
414
/** Async error received */
415
Error = "error"
416
}
417
418
enum DebugEvents {
419
Reconnecting = "reconnecting",
420
PingTimer = "pingTimer",
421
StaleConnection = "staleConnection",
422
ClientInitiatedReconnect = "client initiated reconnect"
423
}
424
```