{"library":"nats.ws","title":"NATS WebSocket Client","description":"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.","language":"javascript","status":"renamed","last_verified":"Tue Apr 21","install":{"commands":["npm install nats.ws"],"cli":null},"imports":["import { connect } from 'nats.ws';","import { StringCodec } from 'nats.ws';","import type { NatsConnection } from 'nats.ws';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { connect, StringCodec, Empty } from 'nats.ws';\n\n// In a Node.js environment, you might need to shim WebSocket:\n// globalThis.WebSocket = require('websocket').w3cwebsocket; \n\nasync function runNatsClient() {\n  const servers = process.env.NATS_SERVER_URL ?? 'ws://localhost:9222';\n  console.log(`Connecting to NATS server at: ${servers}`);\n  try {\n    const nc = await connect({ servers: servers });\n    const sc = StringCodec.create();\n\n    console.log(`Connected to ${nc.getServer()}`);\n\n    // Subscribe to a subject and respond to requests\n    const sub = nc.subscribe('time.requests');\n    (async () => {\n      for await (const m of sub) {\n        const requestPayload = sc.decode(m.data);\n        const response = `Current time for '${requestPayload}': ${new Date().toLocaleTimeString()}`;\n        m.respond(sc.encode(response));\n        console.log(`[time.requests] received: '${requestPayload}' and responded with: '${response}'`);\n      }\n      console.log('Subscription to time.requests closed');\n    })();\n\n    // Publish a message and request a response\n    const requestPayload = 'What time is it in Tokyo?';\n    const response = await nc.request('time.requests', sc.encode(requestPayload), { timeout: 1000 });\n    console.log(`[time.requests] received response: ${sc.decode(response.data)}`);\n\n    // Publish a simple message\n    nc.publish('hello', sc.encode('world'));\n    console.log('Published \"hello world\" to subject \"hello\"');\n\n    await nc.flush(); // Ensure all messages are sent\n    await nc.close();\n    console.log('Connection closed.');\n  } catch (err: any) {\n    console.error(`Error connecting or interacting with NATS: ${err.message}`);\n    if (err.code) {\n      console.error(`NATS Error Code: ${err.code}`);\n    }\n  }\n}\n\nrunNatsClient();","lang":"typescript","description":"Demonstrates connecting to a NATS server via WebSocket, subscribing to a subject, responding to requests, publishing messages, and gracefully closing the connection.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}