NATS™ Client
NatsClient is a singleton connection manager for NATS™. All publish(),
subscribe(), and subscribeRequest() methods use Ext-JSON serialization
automatically — consumers pass plain TypeScript® objects and receive plain
TypeScript® objects. BigInt values are preserved across the wire.
Connection
Code
The connection is a singleton — subsequent getConnection() calls return the
existing connection. The JetStream client is also available via
getJetStream() (throws if getConnection() was not called first).
getConnection() logs a [startup] NATS <version> connected (<url>) banner
automatically. Use NatsClient.getServerVersion() in your health check so the
/health response includes the NATS server version:
Code
See HTTP Server for the full HealthResponse shape.
Publish
Publish a message with automatic Ext-JSON serialization. Optional headers can be attached (e.g. auth headers for GATEWAY-RESOLVED mode).
Code
BigInt values are serialized as JSON numbers (42n → 42 in the wire format)
and parsed back to bigint on the receiving end.
Subscribe
Subscribe to a subject with automatic Ext-JSON deserialization. The handler receives a typed object — no manual decode/parse.
Code
Empty payloads are passed as null to the handler. Processing errors are
caught and logged — they do not crash the subscription loop.
Request-reply (responder side)
subscribeRequest() implements the NATS™ request-reply pattern on the
responder side. The handler receives the parsed request and returns a response
that is automatically serialized and published to msg.reply.
Code
If the handler throws, an error response { success: false, error, requestId }
is published back to the reply subject (if set).
Request-reply (caller side)
request() is the caller-side counterpart — send a request and wait for the
response. The request is serialized with extJsonStringify, the response is
parsed with extJsonParse. Pass null or undefined for an empty request.
Code
If the responder doesn't reply within timeoutMs, the promise rejects with a
NATS timeout error. The default timeout is 5000ms.
Shared config over NATS™
The SDK uses request() internally for the BE→microservice config sharing
protocol. The BE subscribes to config.get via subscribeSharedConfig() and
responds with the SharedConfig payload; microservices call
fetchSharedConfig() (which wraps NatsClient.request("config.get", null))
at startup to get their auth_mode, casdoor_endpoint, redis_url, etc. See
Config tables for the full protocol.
Next steps
- Authentication — verifyNatsMessage and auth headers
- Service Registration — lifecycle events over NATS™
- Config tables — the
config.getrequest-reply protocol - HTTP Server — using
getServerVersion()in the health check - Ext-JSON — how BigInt serialization works
- API Reference — NatsClient method signatures