Skip to content
VaelJS Blog

vael:nats

Async NATS messaging and JetStream client (vael:nats).

Available in the vjs (vaeljs) runtime only when built with the opt-in vael-nats (or vael-messaging) Cargo feature; absent in default builds and in vjs-lite.

import ... from "vael:nats"
Since v0.0.0-alpha.2 vjs (V8)
Cargo feature: vael-nats / vael-messaging (opt-in in vaeljs-core, disabled by default; absent in vaeljs-lite-core)
import { connect } from "vael:nats";
const nc = await connect({ host: "127.0.0.1", port: 4222 });
try {
await nc.publish("jobs.created", JSON.stringify({ id: 1 }));
await nc.flush();
} finally {
await nc.close();
}
functionSince v0.0.0-alpha.2vjs only
export function connect(options: NatsConnectOptions): Promise<NatsClient>;

Connect asynchronously to a NATS server (vael-nats feature required).

Parameters
NameTypeDescription
optionsNatsConnectOptionsNATS connection options.
Returns
Promise<NatsClient> — Promise resolving to a connected NatsClient.
Exceptions
  • TypeError — on invalid argument types.
  • NatsError — on connection, authentication, TLS, or timeout failures.
classSince v0.0.0-alpha.2vjs only
export class NatsError extends Error {
  override name: "NatsError";
  code: NatsErrorCode;
  constructor(code: NatsErrorCode, message: string);
}

Redacted NATS client error carrying a stable NatsErrorCode.

Constructor
constructor(code: NatsErrorCode, message: string);

Construct a NatsError.

Parameters
NameTypeDescription
codeNatsErrorCodeMachine-readable NatsErrorCode.
messagestringHuman-readable redacted error description.
Properties
PropertyTypeDescriptionSince
name "NatsError"Error name ("NatsError").v0.0.0-alpha.2
code NatsErrorCodeMachine-readable NATS error code.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsConnectOptions {
  host: string;
  port?: number;
  user?: string;
  pass?: string;
  token?: string;
  name?: string;
  tls?: boolean;
  connectTimeoutMs?: number;
  requestTimeoutMs?: number;
}

Connection configuration accepted by connect(options).

Properties
PropertyTypeDescriptionSince
host stringServer hostname or IP address (required).v0.0.0-alpha.2
port optionalnumberServer TCP port (1..=65535, default 4222).v0.0.0-alpha.2
user optionalstringOptional username for CONNECT authentication.v0.0.0-alpha.2
pass optionalstringOptional password for CONNECT authentication.v0.0.0-alpha.2
token optionalstringOptional bearer auth token for CONNECT authentication.v0.0.0-alpha.2
name optionalstringOptional client name sent in CONNECT.v0.0.0-alpha.2
tls optionalbooleanEnable fail-closed rustls TLS upgrade (default false).v0.0.0-alpha.2
connectTimeoutMs optionalnumberTCP/TLS connect timeout in milliseconds (1..=300000).v0.0.0-alpha.2
requestTimeoutMs optionalnumberDefault timeout in milliseconds for request() and flush() (1..=300000).v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsPublishOptions {
  reply?: string;
  headers?: Record<string, string | readonly string[]>;
}

Options accepted by NatsClient.publish() and NatsMessage.respond().

Properties
PropertyTypeDescriptionSince
reply optionalstringOptional reply-to subject for request/reply routing.v0.0.0-alpha.2
headers optionalRecord<string, string | readonly string[]>Optional NATS message headers (HPUB / HMSG).v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsRequestOptions {
  headers?: Record<string, string | readonly string[]>;
  timeoutMs?: number;
}

Options accepted by NatsClient.request().

Properties
PropertyTypeDescriptionSince
headers optionalRecord<string, string | readonly string[]>Optional NATS message headers.v0.0.0-alpha.2
timeoutMs optionalnumberRequest deadline in milliseconds (1..=300000).v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsSubscribeOptions {
  queue?: string;
  max?: number;
}

Options accepted by NatsClient.subscribe().

Properties
PropertyTypeDescriptionSince
queue optionalstringOptional queue group name for load-balanced delivery.v0.0.0-alpha.2
max optionalnumberAutomatically unsubscribe after receiving at most max messages.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsMessage {
  readonly subject: string;
  readonly reply?: string;
  readonly data: Uint8Array;
  readonly headers?: Record<string, readonly string[]>;
  readonly status?: number;
  string(): string;
  json<T = unknown>(): T;
  respond(payload?: string | Uint8Array, options?: NatsPublishOptions): Promise<void>;
  ack(): Promise<void>;
  nak(): Promise<void>;
  term(): Promise<void>;
  inProgress(): Promise<void>;
}

Message received from a NATS subscription, request reply, or JetStream pull.

Properties
PropertyTypeDescriptionSince
subject readonlystringSubject on which the message was delivered.v0.0.0-alpha.2
reply readonly optionalstringOptional reply subject for respond() / JetStream acknowledgments.v0.0.0-alpha.2
data readonlyUint8ArrayRaw payload bytes.v0.0.0-alpha.2
headers readonly optionalRecord<string, readonly string[]>Parsed multi-value NATS headers, if present.v0.0.0-alpha.2
status readonly optionalnumberOptional NATS status code (e.g., 503 for no-responders).v0.0.0-alpha.2
Methods
methodSince v0.0.0-alpha.2
string(): string;

Decode data as UTF-8 text.

Returns
string
methodSince v0.0.0-alpha.2
json<T = unknown>(): T;

Decode data as UTF-8 and parse as JSON.

Returns
T
methodSince v0.0.0-alpha.2
respond(payload?: string | Uint8Array, options?: NatsPublishOptions): Promise<void>;

Publish a reply to msg.reply. Throws NatsError if no reply is present.

Parameters
NameTypeDescription
payload optionalstring | Uint8Array—
options optionalNatsPublishOptions—
Returns
Promise<void>
methodSince v0.0.0-alpha.2
ack(): Promise<void>;

Send a JetStream positive acknowledgment (+ACK) if reply is present.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
nak(): Promise<void>;

Send a JetStream negative acknowledgment (-NAK) if reply is present.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
term(): Promise<void>;

Send a JetStream terminal acknowledgment (+TERM) if reply is present.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
inProgress(): Promise<void>;

Notify JetStream that work is still in progress (+WPI) to reset ack wait if reply is present.

Returns
Promise<void>
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsSubscription {
  next(): Promise<NatsMessage | null>;
  unsubscribe(): Promise<void>;
  [Symbol.asyncIterator](): AsyncIterableIterator<NatsMessage>;
}

Active NATS subscription returned by NatsClient.subscribe().

Methods
methodSince v0.0.0-alpha.2
next(): Promise<NatsMessage | null>;

Await the next delivered message, or null once unsubscribed or exhausted.

Returns
methodSince v0.0.0-alpha.2
unsubscribe(): Promise<void>;

Unsubscribe and stop receiving further messages.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
[Symbol.asyncIterator](): AsyncIterableIterator<NatsMessage>;

Iterate asynchronously over incoming messages (for await (const msg of sub)).

interfaceSince v0.0.0-alpha.2vjs only
export interface JetStreamPublishOptions {
  msgId?: string;
  timeoutMs?: number;
}

Options accepted by JetStreamClient.publish().

Properties
PropertyTypeDescriptionSince
msgId optionalstringOptional deduplication message ID (Nats-Msg-Id header).v0.0.0-alpha.2
timeoutMs optionalnumberPublish acknowledgment deadline in milliseconds (1..=300000).v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface JetStreamFetchOptions {
  maxMessages?: number;
  expiresMs?: number;
}

Options accepted by JetStreamClient.fetch().

Properties
PropertyTypeDescriptionSince
maxMessages optionalnumberMaximum number of messages to pull (1..=1024).v0.0.0-alpha.2
expiresMs optionalnumberPull expiration timeout in milliseconds (1..=300000).v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface JetStreamAck {
  readonly stream: string;
  readonly seq: number;
  readonly duplicate: boolean;
}

Server acknowledgment returned by JetStreamClient.publish().

Properties
PropertyTypeDescriptionSince
stream readonlystringStream that persisted the message.v0.0.0-alpha.2
seq readonlynumberAssigned stream sequence number.v0.0.0-alpha.2
duplicate readonlybooleantrue if the server deduplicated this message by msgId.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs only
export interface JetStreamClient {
  publish(
      subject: string,
      payload?: string | Uint8Array,
      options?: JetStreamPublishOptions,
    ): Promise<JetStreamAck>;
  streamInfo(stream: string): Promise<Record<string, unknown>>;
  createStream(config: Record<string, unknown>): Promise<Record<string, unknown>>;
  deleteStream(stream: string): Promise<Record<string, unknown>>;
  createConsumer(
      stream: string,
      config: Record<string, unknown>,
    ): Promise<Record<string, unknown>>;
  fetch(
      stream: string,
      consumer: string,
      options?: JetStreamFetchOptions,
    ): Promise<NatsMessage[]>;
}

JetStream client facade returned by NatsClient.jetstream().

Methods
methodSince v0.0.0-alpha.2
publish(
  subject: string,
  payload?: string | Uint8Array,
  options?: JetStreamPublishOptions,
): Promise<JetStreamAck>;

Publish a message to a JetStream subject and await server acknowledgment.

Parameters
NameTypeDescription
subjectstring—
payload optionalstring | Uint8Array—
options optionalJetStreamPublishOptions—
methodSince v0.0.0-alpha.2
streamInfo(stream: string): Promise<Record<string, unknown>>;

Retrieve JetStream stream metadata via $JS.API.STREAM.INFO.

Parameters
NameTypeDescription
streamstring—
Returns
Promise<Record<string, unknown>>
methodSince v0.0.0-alpha.2
createStream(config: Record<string, unknown>): Promise<Record<string, unknown>>;

Create or update a JetStream stream via $JS.API.STREAM.CREATE.

Parameters
NameTypeDescription
configRecord<string, unknown>—
Returns
Promise<Record<string, unknown>>
methodSince v0.0.0-alpha.2
deleteStream(stream: string): Promise<Record<string, unknown>>;

Delete a JetStream stream via $JS.API.STREAM.DELETE.

Parameters
NameTypeDescription
streamstring—
Returns
Promise<Record<string, unknown>>
methodSince v0.0.0-alpha.2
createConsumer(
  stream: string,
  config: Record<string, unknown>,
): Promise<Record<string, unknown>>;

Create or update a JetStream durable/ephemeral consumer.

Parameters
NameTypeDescription
streamstring—
configRecord<string, unknown>—
Returns
Promise<Record<string, unknown>>
methodSince v0.0.0-alpha.2
fetch(
  stream: string,
  consumer: string,
  options?: JetStreamFetchOptions,
): Promise<NatsMessage[]>;

Pull up to options.maxMessages messages from a JetStream pull consumer.

Parameters
NameTypeDescription
streamstring—
consumerstring—
options optionalJetStreamFetchOptions—
interfaceSince v0.0.0-alpha.2vjs only
export interface NatsClient {
  publish(
      subject: string,
      payload?: string | Uint8Array,
      options?: NatsPublishOptions,
    ): Promise<void>;
  request(
      subject: string,
      payload?: string | Uint8Array,
      options?: NatsRequestOptions,
    ): Promise<NatsMessage>;
  subscribe(subject: string, options?: NatsSubscribeOptions): NatsSubscription;
  flush(): Promise<void>;
  jetstream(): JetStreamClient;
  close(): Promise<void>;
  [Symbol.asyncDispose](): Promise<void>;
}

Connected async NATS client handle returned by connect().

Methods
methodSince v0.0.0-alpha.2
publish(
  subject: string,
  payload?: string | Uint8Array,
  options?: NatsPublishOptions,
): Promise<void>;

Publish payload to subject.

Parameters
NameTypeDescription
subjectstring—
payload optionalstring | Uint8Array—
options optionalNatsPublishOptions—
Returns
Promise<void>
methodSince v0.0.0-alpha.2
request(
  subject: string,
  payload?: string | Uint8Array,
  options?: NatsRequestOptions,
): Promise<NatsMessage>;

Send a request to subject and await a single NatsMessage reply.

Parameters
NameTypeDescription
subjectstring—
payload optionalstring | Uint8Array—
options optionalNatsRequestOptions—
methodSince v0.0.0-alpha.2
subscribe(subject: string, options?: NatsSubscribeOptions): NatsSubscription;

Synchronously create a subscription to subject (supporting * and > wildcards).

Parameters
NameTypeDescription
subjectstring—
options optionalNatsSubscribeOptions—
methodSince v0.0.0-alpha.2
flush(): Promise<void>;

Send PING and await PONG round-trip to flush outbound frames.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
jetstream(): JetStreamClient;

Return a JetStreamClient bound to this NATS connection.

methodSince v0.0.0-alpha.2
close(): Promise<void>;

Close the NATS connection immediately. Idempotent.

Returns
Promise<void>
methodSince v0.0.0-alpha.2
[Symbol.asyncDispose](): Promise<void>;

Close the connection asynchronously when disposed via await using.

Returns
Promise<void>
typeSince v0.0.0-alpha.2vjs only
export type NatsErrorCode =
  | "VAEL_NATS_CONFIG"
  | "VAEL_NATS_CONNECT"
  | "VAEL_NATS_TLS"
  | "VAEL_NATS_AUTH"
  | "VAEL_NATS_TIMEOUT"
  | "VAEL_NATS_PROTOCOL"
  | "VAEL_NATS_SERVER"
  | "VAEL_NATS_LIMIT"
  | "VAEL_NATS_CLOSED"
  | "VAEL_NATS_IO"
  | "VAEL_NATS_NOT_FOUND";

Stable screaming-snake-case error codes reported on NatsError.code.