CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nats

Node.js client for NATS, a lightweight, high-performance cloud native messaging system

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

connection.mddocs/

Connection Management

NATS connection management provides robust connection handling with authentication, TLS security, automatic reconnection, and graceful shutdown capabilities.

Capabilities

Connect Function

Establishes a connection to one or more NATS servers with comprehensive configuration options.

/**
 * Connect to NATS server(s) with optional configuration
 * @param opts - Connection options including servers, auth, and behavior settings
 * @returns Promise resolving to NatsConnection instance
 */
function connect(opts?: ConnectionOptions): Promise<NatsConnection>;

interface ConnectionOptions {
  /** NATS server URLs - single string or array (default: 127.0.0.1:4222) */
  servers?: string[] | string;
  /** Port number on localhost (mutually exclusive with servers) */
  port?: number;
  /** Username for basic authentication */
  user?: string;
  /** Password for basic authentication */
  pass?: string;
  /** Authentication token */
  token?: string;
  /** Custom authenticator function */
  authenticator?: Authenticator | Authenticator[];
  /** Enable automatic reconnection (default: true) */
  reconnect?: boolean;
  /** Maximum reconnection attempts (-1 for unlimited, default: 10) */
  maxReconnectAttempts?: number;
  /** Milliseconds to wait between reconnection attempts (default: 2000) */
  reconnectTimeWait?: number;
  /** Upper bound for random reconnect delay (default: 100ms) */
  reconnectJitter?: number;
  /** Upper bound for random TLS reconnect delay (default: 1000ms) */
  reconnectJitterTLS?: number;
  /** Function returning reconnect delay in milliseconds */
  reconnectDelayHandler?: () => number;
  /** Connection timeout in milliseconds (default: 20000) */
  timeout?: number;
  /** Ping interval in milliseconds (default: 2 minutes) */
  pingInterval?: number;
  /** Maximum outstanding pings before considering connection stale (default: 2) */
  maxPingOut?: number;
  /** Client name for identification */
  name?: string;
  /** Enable verbose protocol logging */
  verbose?: boolean;
  /** Enable pedantic mode for strict protocol compliance */
  pedantic?: boolean;
  /** TLS/SSL configuration (set to null to disable TLS) */
  tls?: TlsOptions | null;
  /** Ignore cluster topology updates */
  ignoreClusterUpdates?: boolean;
  /** Custom inbox prefix for replies (default: "_INBOX") */
  inboxPrefix?: string;
  /** Disable message echo back to publisher */
  noEcho?: boolean;
  /** Enable debug logging */
  debug?: boolean;
  /** Disable server list randomization */
  noRandomize?: boolean;
  /** Wait for first connection before counting reconnect attempts */
  waitOnFirstConnect?: boolean;
  /** Ignore auth error abort */
  ignoreAuthErrorAbort?: boolean;
  /** Disable async stack traces for performance */
  noAsyncTraces?: boolean;
}

Usage Examples:

import { connect } from "nats";

// Simple connection
const nc = await connect();

// Multiple servers with authentication
const nc = await connect({
  servers: ["nats://server1:4222", "nats://server2:4222"],
  user: "myuser",
  pass: "mypass"
});

// Token authentication
const nc = await connect({
  servers: "nats://localhost:4222",
  token: "my-auth-token"
});

// Custom timeout and reconnection settings
const nc = await connect({
  servers: "nats://localhost:4222",
  timeout: 10000,
  reconnectTimeWait: 5000,
  maxReconnectAttempts: 20
});

Connection Lifecycle

Methods for managing connection state, monitoring health, and graceful shutdown.

interface NatsConnection {
  /** Information about the currently connected server */
  info?: ServerInfo;

  /** 
   * Close the connection immediately
   * @returns Promise that resolves when connection is closed
   */
  close(): Promise<void>;

  /**
   * Monitor connection close status
   * @returns Promise that resolves when connection closes (with Error if abnormal)
   */
  closed(): Promise<void | Error>;

  /**
   * Gracefully drain and close the connection
   * Ensures all subscriptions process pending messages before closing
   * @returns Promise that resolves when drain completes
   */
  drain(): Promise<void>;

  /** Check if connection is closed */
  isClosed(): boolean;

  /** Check if connection is draining */
  isDraining(): boolean;

  /** 
   * Flush pending operations and wait for server acknowledgment
   * @returns Promise that resolves when flush completes
   */
  flush(): Promise<void>;

  /**
   * Measure round-trip time to server
   * @returns Promise resolving to RTT in milliseconds
   */
  rtt(): Promise<number>;

  /** Get the hostport of connected server */
  getServer(): string;

  /** Get connection statistics */
  stats(): Stats;

  /** 
   * Monitor connection status events
   * @returns AsyncIterable of Status events
   */
  status(): AsyncIterable<Status>;

  /**
   * Force reconnection (experimental API)
   * May disconnect and reconnect based on reconnection policy
   */
  reconnect(): void;
}

Usage Examples:

import { connect, Events } from "nats";

const nc = await connect();

// Monitor connection status
(async () => {
  for await (const status of nc.status()) {
    switch (status.type) {
      case Events.Disconnect:
        console.log("Disconnected from server");
        break;
      case Events.Reconnect:
        console.log("Reconnected to server");
        break;
      case Events.Error:
        console.error("Connection error:", status.data);
        break;
    }
  }
})();

// Check connection health
console.log(`RTT: ${await nc.rtt()}ms`);
console.log(`Connected to: ${nc.getServer()}`);
console.log(`Stats:`, nc.stats());

// Graceful shutdown
await nc.drain();
console.log("Connection drained and closed");

Authentication

Various authentication methods including basic auth, tokens, NKeys, and JWT.

type Authenticator = (nonce?: string) => Auth;

interface Auth {
  user?: string;
  pass?: string;
  auth_token?: string;
  nkey?: string;
  sig?: string;
  jwt?: string;
}

interface NoAuth extends Auth {}

interface UserPass extends Auth {
  user: string;
  pass: string;
}

interface TokenAuth extends Auth {
  auth_token: string;
}

interface NKeyAuth extends Auth {
  nkey: string;
  sig: string;
}

interface JwtAuth extends Auth {
  jwt: string;
  nkey?: string;
  sig?: string;
}

/** Build authenticator from connection options */
function buildAuthenticator(opts: ConnectionOptions): Authenticator;

/** Create username/password authenticator */
function usernamePasswordAuthenticator(user: string, pass: string): Authenticator;

/** Create token authenticator */
function tokenAuthenticator(token: string): Authenticator;

/** Create NKey authenticator */
function nkeyAuthenticator(nkey: Uint8Array): Authenticator;

/** Create JWT authenticator */
function jwtAuthenticator(jwt: string, sk?: Uint8Array): Authenticator;

/** Create credentials file authenticator */
function credsAuthenticator(creds: Uint8Array): Authenticator;

Usage Examples:

import { connect, credsAuthenticator, nkeyAuthenticator } from "nats";
import { readFileSync } from "fs";

// Credentials file authentication
const creds = readFileSync("./user.creds");
const nc = await connect({
  servers: "nats://localhost:4222",
  authenticator: credsAuthenticator(creds)
});

// NKey authentication
const nkey = readFileSync("./user.nk");
const nc = await connect({
  servers: "nats://localhost:4222",
  authenticator: nkeyAuthenticator(nkey)
});

TLS Configuration

Secure connection options including client certificates and custom CA validation.

interface TlsOptions {
  /** Client certificate */
  cert?: string;
  /** Client private key */
  key?: string;
  /** Certificate authority certificates */
  ca?: string;
  /** Custom certificate verification function */
  checkServerIdentity?: (hostname: string, cert: any) => Error | undefined;
  /** Reject unauthorized certificates (default: true) */
  rejectUnauthorized?: boolean;
  /** Handshake timeout in milliseconds */
  timeout?: number;
}

Usage Examples:

import { connect } from "nats";
import { readFileSync } from "fs";

// TLS with client certificates
const nc = await connect({
  servers: "tls://localhost:4222",
  tls: {
    cert: readFileSync("./client-cert.pem"),
    key: readFileSync("./client-key.pem"),
    ca: readFileSync("./ca.pem")
  }
});

// TLS with custom verification
const nc = await connect({
  servers: "tls://localhost:4222",
  tls: {
    rejectUnauthorized: false
  }
});

Types

interface Stats {
  /** Bytes received by client */
  inBytes: number;
  /** Bytes sent by client */
  outBytes: number;
  /** Messages received by client */
  inMsgs: number;
  /** Messages sent by client */
  outMsgs: number;
}

interface Status {
  /** Event type */
  type: Events | DebugEvents;
  /** Event data */
  data: string | ServersChanged | number;
  /** Permission context for auth errors */
  permissionContext?: { operation: string; subject: string };
}

interface ServersChanged {
  /** Newly discovered servers */
  readonly added: string[];
  /** Removed servers */
  readonly deleted: string[];
}

interface ServerInfo {
  /** Server ID */
  server_id: string;
  /** Server name */
  server_name: string;
  /** NATS server version */
  version: string;
  /** Protocol version */
  proto: number;
  /** Server hostname */
  host: string;
  /** Server port */
  port: number;
  /** Headers support available */
  headers?: boolean;
  /** Maximum message payload size */
  max_payload: number;
  /** JetStream available */
  jetstream?: boolean;
  /** Authentication required */
  auth_required?: boolean;
  /** TLS required */
  tls_required?: boolean;
  /** TLS available */
  tls_available?: boolean;
  /** Client ID assigned by server */
  client_id: number;
  /** Client IP as seen by server */
  client_ip?: string;
  /** Cluster name */
  cluster?: string;
  /** Other servers in cluster */
  connect_urls?: string[];
  /** Server in lame duck mode */
  ldm?: boolean;
  /** Git commit of server build */
  git_commit?: string;
  /** Go version used to build server */
  go: string;
  /** Nonce for challenge/response auth */
  nonce?: string;
  /** TLS verification required */
  tls_verify?: boolean;
}

enum Events {
  /** Client disconnected */
  Disconnect = "disconnect",
  /** Client reconnected */
  Reconnect = "reconnect", 
  /** Cluster update received */
  Update = "update",
  /** Server entering lame duck mode */
  LDM = "ldm",
  /** Async error received */
  Error = "error"
}

enum DebugEvents {
  Reconnecting = "reconnecting",
  PingTimer = "pingTimer",
  StaleConnection = "staleConnection",
  ClientInitiatedReconnect = "client initiated reconnect"
}

docs

connection.md

index.md

jetstream.md

kv-store.md

messaging.md

object-store.md

services.md

tile.json