NATS WebSocket Client

1.30.3 · renamed · verified Tue Apr 21

nats.ws is a robust JavaScript and TypeScript client library designed for interacting with the NATS messaging system over WebSocket connections. It supports a variety of environments including modern web browsers, Deno, and Node.js (requiring a WebSocket shim for Node.js). The library is currently at version 1.30.3 and maintains a frequent release cadence, often aligning with updates to its underlying core client logic (NBC, which is derived from `nats.deno`). A key differentiating factor is its specialized focus on WebSocket connectivity and its tight integration with the NATS ecosystem. Users are advised that nats.ws is now considered an integrated component within the larger nats.js monorepo, and future development and major feature enhancements are primarily focused there. Comprehensive migration documentation is available for transitioning to nats.js.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a NATS server via WebSocket, subscribing to a subject, responding to requests, publishing messages, and gracefully closing the connection.

import { connect, StringCodec, Empty } from 'nats.ws';

// In a Node.js environment, you might need to shim WebSocket:
// globalThis.WebSocket = require('websocket').w3cwebsocket; 

async function runNatsClient() {
  const servers = process.env.NATS_SERVER_URL ?? 'ws://localhost:9222';
  console.log(`Connecting to NATS server at: ${servers}`);
  try {
    const nc = await connect({ servers: servers });
    const sc = StringCodec.create();

    console.log(`Connected to ${nc.getServer()}`);

    // Subscribe to a subject and respond to requests
    const sub = nc.subscribe('time.requests');
    (async () => {
      for await (const m of sub) {
        const requestPayload = sc.decode(m.data);
        const response = `Current time for '${requestPayload}': ${new Date().toLocaleTimeString()}`;
        m.respond(sc.encode(response));
        console.log(`[time.requests] received: '${requestPayload}' and responded with: '${response}'`);
      }
      console.log('Subscription to time.requests closed');
    })();

    // Publish a message and request a response
    const requestPayload = 'What time is it in Tokyo?';
    const response = await nc.request('time.requests', sc.encode(requestPayload), { timeout: 1000 });
    console.log(`[time.requests] received response: ${sc.decode(response.data)}`);

    // Publish a simple message
    nc.publish('hello', sc.encode('world'));
    console.log('Published "hello world" to subject "hello"');

    await nc.flush(); // Ensure all messages are sent
    await nc.close();
    console.log('Connection closed.');
  } catch (err: any) {
    console.error(`Error connecting or interacting with NATS: ${err.message}`);
    if (err.code) {
      console.error(`NATS Error Code: ${err.code}`);
    }
  }
}

runNatsClient();

view raw JSON →