useNats is your pack’s async transport. It wraps the platform’s NATS bridge so your frontend can talk to your service, react to events from other packs, or broadcast messages across the org.
Signature
true when the NATS bridge is online. Re-renders when connection status changes.Fire-and-forget publish. No response, no ack. Payload is JSON-serialized.
Register a handler for a subject (wildcards
* and > supported). Returns an unsubscribe function — call it on unmount.Send a request and await a reply. Rejects after
timeoutMs (default 5000 ms).Current org id, synced from
useKhalAuth. Use it to scope subjects.Current user id. Useful for per-user subject segments.
Basic example — publish and subscribe
Request / reply example
When you need an answer, userequest. This pattern is how pack-terminal spawns a PTY session — the frontend requests, the service responds with the new session id.
pack-terminal/package/src/views/terminal/useNatsPty.ts.
Subject naming
Subjects your pack owns should always be scoped byorgId and your pack’s id:
pack-terminal:
khal.<orgId>.terminal.pty.spawn— request a new PTY sessionkhal.<orgId>.terminal.pty.input.<sessionId>— publish stdin to a sessionkhal.<orgId>.terminal.pty.output.<sessionId>— subscribe to stdout
Error handling
publishnever throws. If the bridge is offline, the frame is dropped.subscribenever throws. Callbacks that throw are isolated — other subscribers still fire.requestrejects with anErrorwhen it times out. Always wrap intry/catchor.catch().- Connection drops: read
connectedand guard side effects on it. Re-subscribing on reconnect is automatic — the bridge replays your active subscriptions.
Wildcards
Subscribe patterns support NATS wildcards:*matches exactly one token:khal.*.terminal.pty.spawn>matches one or more tokens, and must be last:khal.<orgId>.terminal.pty.>
What’s next
useKhalAuth
Current user, org, role — the auth contract your pack receives.
useService
Call into your pack’s own backend service.