Getting started
Connect from a browser
The library uses wsconnect from @nats-io/nats-core. Use a ws:// or wss:// server URL, not the TCP nats:// address. An HTTPS page needs a secure wss:// endpoint.
import { createActor } from 'xstate'
import { natsMachine } from '@jr200-labs/xstate-nats'
const actor = createActor(natsMachine)
actor.subscribe((snapshot) => console.log(snapshot.value))
actor.start()
actor.send({
type: 'CONFIGURE',
config: {
opts: { servers: ['ws://localhost:42222'], timeout: 3000 },
maxRetries: 3,
},
})
actor.send({ type: 'CONNECT' })Wait for snapshot.matches('connected') before sending messaging or KV events. The root waits for both child managers to report readiness. A failed initial connection enters error; send CONNECT again to retry or CONFIGURE to replace the configuration.
For React, use the same machine with useActor(natsMachine) from @xstate/react. The library has no React dependency.
Run a local NATS broker
Install nats-server, then use the repository’s development configuration:
nats-server -c nats-server.confThis enables JetStream and an unencrypted development WebSocket listener on port 42222. Preview the demo locally and select Real NATS · your server with ws://localhost:42222. The config has verbose development logging; use your own TLS, origin policy, and authentication for a deployed broker. See NATS WebSocket configuration.
Close and recover
actor.send({ type: 'DISCONNECT' })
// Wait for closed, then reconnect with the current configuration:
actor.send({ type: 'CONNECT' })DISCONNECT drains and closes the connection. RESET is available in configured, closed, and error; it clears the root configuration. Send DISCONNECT and wait for closed before resetting an active session. Calling actor.stop() alone is not a replacement for disconnecting the broker connection.
Build the documentation
Use Node.js 22.15+ and the pnpm version in package.json. Install Quarto.
pnpm install --frozen-lockfile
pnpm demo:dev # browser demo at http://localhost:3001
quarto preview docs # complete documentation site
quarto render docs # static output in docs/_siteQuarto’s pre-render hook installs locked dependencies and builds the demo. Its relative asset paths work both locally and under the GitHub Pages project path. The Documentation workflow renders a preview on pull requests and publishes through the shared Quarto workflow after changes reach master.