Node.js client for NATS, a lightweight, high-performance cloud native messaging system
npx @tessl/cli install tessl/npm-nats@2.29.00
# NATS
1
2
NATS is a high-performance, lightweight cloud-native messaging system for distributed applications and microservices. The Node.js client provides full TypeScript support with async/await patterns, automatic reconnection handling, and comprehensive features including core pub/sub messaging, JetStream for persistence and streaming, Key-Value stores, Object stores, and Service discovery APIs.
3
4
## Package Information
5
6
- **Package Name**: nats
7
- **Package Type**: npm
8
- **Language**: TypeScript/JavaScript
9
- **Installation**: `npm install nats`
10
11
## Core Imports
12
13
```typescript
14
import { connect, StringCodec, JSONCodec } from "nats";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { connect, StringCodec, JSONCodec } = require("nats");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { connect, StringCodec } from "nats";
27
28
// Connect to NATS server
29
const nc = await connect({ servers: ["nats://localhost:4222"] });
30
const sc = StringCodec();
31
32
// Simple publish/subscribe
33
const sub = nc.subscribe("news.updates");
34
(async () => {
35
for await (const m of sub) {
36
console.log(`Received: ${sc.decode(m.data)}`);
37
}
38
})();
39
40
// Publish a message
41
nc.publish("news.updates", sc.encode("Hello NATS!"));
42
43
// Request/reply pattern
44
const response = await nc.request("time", sc.encode(""));
45
console.log(`Time: ${sc.decode(response.data)}`);
46
47
// Clean shutdown
48
await nc.drain();
49
```
50
51
## Architecture
52
53
NATS is built around several key components:
54
55
- **Core Connection**: Primary `NatsConnection` interface providing pub/sub messaging with wildcards, queues, and request/reply patterns
56
- **JetStream**: Persistent messaging system with streams, consumers, and acknowledgments for reliable delivery
57
- **Key-Value Store**: High-level abstraction built on JetStream for key-value operations with history and watching
58
- **Object Store**: File-like storage system for larger payloads with metadata and linking
59
- **Services API**: Service discovery and monitoring framework for building NATS-based microservices
60
- **Transport Layer**: Node.js-optimized transport with automatic reconnection, TLS support, and connection draining
61
62
## Capabilities
63
64
### Connection Management
65
66
Core NATS connection functionality including authentication, TLS, reconnection handling, and connection lifecycle management.
67
68
```typescript { .api }
69
function connect(opts?: ConnectionOptions): Promise<NatsConnection>;
70
71
interface ConnectionOptions {
72
servers?: string[] | string;
73
port?: number;
74
user?: string;
75
pass?: string;
76
token?: string;
77
authenticator?: Authenticator | Authenticator[];
78
reconnect?: boolean;
79
maxReconnectAttempts?: number;
80
reconnectTimeWait?: number;
81
timeout?: number;
82
pingInterval?: number;
83
maxPingOut?: number;
84
name?: string;
85
verbose?: boolean;
86
pedantic?: boolean;
87
tls?: TlsOptions | null;
88
ignoreClusterUpdates?: boolean;
89
inboxPrefix?: string;
90
noEcho?: boolean;
91
debug?: boolean;
92
noRandomize?: boolean;
93
waitOnFirstConnect?: boolean;
94
}
95
```
96
97
[Connection Management](./connection.md)
98
99
### Core Messaging
100
101
Essential pub/sub messaging operations including publishing, subscribing, request/reply patterns, and message handling with full wildcard support.
102
103
```typescript { .api }
104
interface NatsConnection {
105
publish(subject: string, payload?: Payload, options?: PublishOptions): void;
106
subscribe(subject: string, opts?: SubscriptionOptions): Subscription;
107
request(subject: string, payload?: Payload, opts?: RequestOptions): Promise<Msg>;
108
requestMany(subject: string, payload?: Payload, opts?: Partial<RequestManyOptions>): Promise<AsyncIterable<Msg>>;
109
}
110
111
interface Msg {
112
subject: string;
113
data: Uint8Array;
114
reply?: string;
115
headers?: MsgHdrs;
116
respond(data?: Payload, opts?: PublishOptions): boolean;
117
}
118
```
119
120
[Core Messaging](./messaging.md)
121
122
### JetStream
123
124
Persistent messaging system providing streams for message storage, consumers for reliable delivery, and advanced features like deduplication and retention policies.
125
126
```typescript { .api }
127
interface JetStreamClient {
128
publish(subj: string, payload?: Payload, options?: Partial<JetStreamPublishOptions>): Promise<PubAck>;
129
subscribe(subject: string, opts?: Partial<ConsumerOptsBuilder>): Promise<JetStreamSubscription>;
130
pullSubscribe(subject: string, opts?: Partial<ConsumerOptsBuilder>): Promise<JetStreamPullSubscription>;
131
}
132
133
interface JetStreamManager {
134
streams: StreamAPI;
135
consumers: ConsumerAPI;
136
getAccountInfo(): Promise<JetStreamAccountStats>;
137
}
138
```
139
140
[JetStream](./jetstream.md)
141
142
### Key-Value Store
143
144
High-level key-value abstraction with history tracking, watch capabilities, and automatic conflict resolution built on JetStream streams.
145
146
```typescript { .api }
147
interface KV {
148
get(key: string): Promise<KvEntry | null>;
149
put(key: string, value: Uint8Array, opts?: Partial<KvPutOptions>): Promise<number>;
150
delete(key: string, opts?: Partial<KvDeleteOptions>): Promise<void>;
151
watch(opts?: Partial<KvWatchOptions>): Promise<QueuedIterator<KvEntry>>;
152
history(key: string): Promise<QueuedIterator<KvEntry>>;
153
}
154
```
155
156
[Key-Value Store](./kv-store.md)
157
158
### Object Store
159
160
File-like storage system for larger payloads with metadata, chunking, and linking capabilities for complex data structures.
161
162
```typescript { .api }
163
interface ObjectStore {
164
put(meta: ObjectStoreMeta, payload: AsyncIterable<Uint8Array>): Promise<ObjectInfo>;
165
get(name: string): Promise<ObjectResult | null>;
166
info(name: string): Promise<ObjectInfo | null>;
167
list(): Promise<QueuedIterator<ObjectInfo>>;
168
delete(name: string): Promise<boolean>;
169
}
170
```
171
172
[Object Store](./object-store.md)
173
174
### Services API
175
176
Service discovery and monitoring framework enabling service registration, health checks, and observability for NATS-based microservices.
177
178
```typescript { .api }
179
interface ServicesAPI {
180
add(config: ServiceConfig): Promise<Service>;
181
client(opts?: RequestManyOptions, prefix?: string): ServiceClient;
182
}
183
184
interface ServiceClient {
185
ping(name?: string, id?: string): Promise<QueuedIterator<ServiceIdentity>>;
186
stats(name?: string, id?: string): Promise<QueuedIterator<ServiceStats>>;
187
info(name?: string, id?: string): Promise<QueuedIterator<ServiceInfo>>;
188
}
189
```
190
191
[Services API](./services.md)
192
193
## Core Types
194
195
```typescript { .api }
196
type Payload = Uint8Array | string;
197
198
interface Msg {
199
subject: string;
200
data: Uint8Array;
201
reply?: string;
202
headers?: MsgHdrs;
203
respond(data?: Payload, opts?: PublishOptions): boolean;
204
}
205
206
interface Subscription {
207
unsubscribe(max?: number): void;
208
drain(): Promise<void>;
209
isClosed(): boolean;
210
getSubject(): string;
211
getReceived(): number;
212
getProcessed(): number;
213
getPending(): number;
214
getID(): number;
215
getMax(): number | undefined;
216
}
217
218
interface NatsError extends Error {
219
name: string;
220
message: string;
221
code: string;
222
chainedError?: Error;
223
api_error?: ApiError;
224
}
225
226
interface Stats {
227
inBytes: number;
228
outBytes: number;
229
inMsgs: number;
230
outMsgs: number;
231
}
232
233
interface ServerInfo {
234
server_id: string;
235
server_name: string;
236
version: string;
237
proto: number;
238
host: string;
239
port: number;
240
headers?: boolean;
241
max_payload: number;
242
jetstream?: boolean;
243
auth_required?: boolean;
244
tls_required?: boolean;
245
tls_available?: boolean;
246
}
247
```