{"id":15714,"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.","status":"renamed","version":"1.30.3","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/nats-io/nats.ws","tags":["javascript","NATS","websockets","typescript"],"install":[{"cmd":"npm install nats.ws","lang":"bash","label":"npm"},{"cmd":"yarn add nats.ws","lang":"bash","label":"yarn"},{"cmd":"pnpm add nats.ws","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The direct 'nats.ws' import path is correct since v1.6.0 for ESM. Older versions (<1.6.0) used 'nats.ws/nats.js'. For CommonJS in Node.js, ensure a global WebSocket shim is provided before requiring.","wrong":"import { connect } from 'nats.ws/nats.js';","symbol":"connect","correct":"import { connect } from 'nats.ws';"},{"note":"StringCodec is commonly used for encoding and decoding NATS messages, especially for string payloads. The import path changed with v1.6.0.","wrong":"import { StringCodec } from 'nats.ws/nats.js';","symbol":"StringCodec","correct":"import { StringCodec } from 'nats.ws';"},{"note":"This is a TypeScript type import for the connection object returned by `connect()`.","symbol":"NatsConnection","correct":"import type { NatsConnection } from 'nats.ws';"}],"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."},"warnings":[{"fix":"Review the NATS.deno v1.29.2 release notes for specific instructions on migrating large object store data or adjusting your application logic.","message":"Version 1.30.2 introduced a breaking change for NATS Object Store. Objects 512MB and larger might require a migration strategy. Users should consult the `nats.deno` v1.29.2 release notes (linked from `nats.ws` v1.30.2 changelog) for detailed migration steps before updating to avoid data integrity issues.","severity":"breaking","affected_versions":">=1.30.2"},{"fix":"Ensure your `nats-server` is updated to version v2.10.26 or newer if utilizing JetStream features, or review the `nats.deno` v1.29.3 release notes for specific impacts and necessary client-side adjustments.","message":"Version 1.30.3 includes updates to support a change in JetStream behavior in `nats-server` v2.10.26 and beyond. This may affect applications using JetStream features with older server versions, potentially leading to unexpected behavior.","severity":"breaking","affected_versions":">=1.30.3"},{"fix":"Migrate to the `nats.js` package. Refer to the `migration.md` document within the `nats.js` GitHub repository for detailed migration guidance.","message":"The `nats.ws` project is now integrated into the `nats.js` monorepo. While `nats.ws` still receives maintenance updates, the primary development and new feature additions are concentrated in `nats.js`. Users are strongly encouraged to migrate to `nats.js` for new projects or existing ones to benefit from ongoing improvements and unified API.","severity":"deprecated","affected_versions":">=1.30.0"},{"fix":"Always specify the full protocol in server URLs within `ConnectionOptions`, for example: `{ servers: ['ws://localhost:9222', 'wss://secure.nats.io'] }`.","message":"By default, `nats.ws` assumes `wss://` (secure WebSocket) for server addresses provided as `host:port` (e.g., `localhost:9222`). If connecting to an insecure `ws://` endpoint, the protocol must be explicitly specified in the server URL (e.g., `ws://localhost:9222`).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For heterogeneous or proxied environments, configure your connection with `connect({ servers: [...], ignoreServerUpdates: true })` and explicitly list all valid server URLs.","message":"When connecting to NATS clusters with mixed `ws://` and `wss://` protocols, or if using a proxy that might advertise incorrect server updates, you may need to set the `ignoreServerUpdates` connection option to `true`. Failure to do so might cause the client to attempt to connect to an incompatible endpoint.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Update your import statements to `import { connect } from 'nats.ws';` for versions 1.6.0 and higher. If targeting older versions, use the specific path.","message":"The primary import path for modules like `connect` changed with `v1.6.0`. Prior to `v1.6.0`, the correct ESM import was `import { connect } from 'nats.ws/nats.js';`. For `v1.6.0` and later, it is simply `import { connect } from 'nats.ws';`.","severity":"breaking","affected_versions":">=1.6.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Install a WebSocket library like `websocket` (`npm install websocket`) and shim it globally before importing `nats.ws`: `globalThis.WebSocket = require(\"websocket\").w3cwebsocket;`.","cause":"Running `nats.ws` in a Node.js environment without a global `WebSocket` implementation (shim). The library expects a W3C-compatible WebSocket API.","error":"ReferenceError: WebSocket is not defined"},{"fix":"Verify the NATS server URL and port are correct (including `ws://` or `wss://` protocol). Ensure the NATS server is running and accessible from the client. Check for any network or firewall rules that might be blocking the connection.","cause":"This error (or similar 'NatsError: Could not connect to server', 'EOF') indicates that the client failed to establish a proper WebSocket connection to the NATS server. Common causes include an incorrect server URL, the NATS server not running, a firewall blocking the connection, or unexpected data during the handshake.","error":"NatsError: Protocol error -1 (code: 1006)"},{"fix":"For `nats.ws` v1.6.0 and newer, change the import statement to `import { connect } from 'nats.ws';`. If the issue persists with bundlers, ensure your bundler is correctly configured to handle ESM exports and resolve the main entry point (e.g., by ensuring `module` field in `package.json` is respected).","cause":"This error typically occurs in bundlers (e.g., Webpack, Rollup, Angular CLI) when `nats.ws` v1.6.0 or newer is used, but the import statement `import { connect } from 'nats.ws/nats.js';` (which was for older versions) is still present. Bundlers might also struggle with ESM/CJS resolution.","error":"Module not found: Can't resolve 'nats.ws/nats.js'"}],"ecosystem":"npm"}