Table of Contents

JavaScript Client

The JavaScript client runs in Node 22 or later and in browsers. It is generated by NexNet.Generator together with its runtime, so it needs no npm package from a registry. It is plain ES modules with JSDoc types, and the generated code comes with .d.ts files for TypeScript.

Environment Transports
Node WebSocket (ws://, wss://), HttpSocket (http://, https://), TCP, TCP + TLS, Unix domain sockets
Browser WebSocket (ws://, wss://) only

See Multi-language Clients for the opt-in, the build options, the feature parity table and the type mapping.

1. The example API

The examples on this page use this API, defined in C# in the server's project:

[NexusObject]
public class ChatMessage
{
    [NexusKey(0)] public string User { get; set; } = "";
    [NexusKey(1)] public string Text { get; set; } = "";
}

public interface IChatClientNexus
{
    void Message(ChatMessage message);          // the server pushes a message
    ValueTask<string> GetStatus();              // the server asks the client
}

public interface IChatServerNexus
{
    void Send(string text);
    ValueTask<ChatMessage[]> History(int count, CancellationToken cancellationToken);
    ValueTask Upload(INexusDuplexPipe pipe, string fileName);
    ValueTask Subscribe(INexusDuplexChannel<ChatMessage> channel);

    [NexusCollection(NexusCollectionMode.BiDirectional)]
    INexusList<string> Rooms { get; }
}

[Nexus<IChatServerNexus, IChatClientNexus>(NexusType = NexusType.Server,
    Targets = NexusTargets.Java | NexusTargets.JavaScript)]
public partial class ChatServerNexus
{
    // server implementation
}

2. Generate the client

Configure the output directory in the project that holds ChatServerNexus and build it:

<PropertyGroup>
  <NexNetJavaScriptOutputDir>../chat-web/src/generated</NexNetJavaScriptOutputDir>
</PropertyGroup>
dotnet build

chat-web/src/generated/ now holds:

File Contents
ChatServerNexus.js / .d.ts createChatClient, ChatServerProxy, ChatClientNexusBase, ChatClientBinding, ChatHandshake
ChatMessage.js / .d.ts The ChatMessage class
formatters.js / .d.ts ChatMessageFormatter and the other serializers
nexnet-runtime/ The client runtime (@dtronix/nexnet)

Every build rewrites the folder (only files that changed), so do not edit it.

3. Reference the runtime

By default (RuntimeImport=package) generated modules import @dtronix/nexnet. Point that name at the emitted runtime with a local dependency in your package.json:

{
  "type": "module",
  "dependencies": {
    "@dtronix/nexnet": "file:src/generated/nexnet-runtime"
  }
}

npm install links the folder; nothing is downloaded. Bundlers (Vite, webpack, esbuild) then resolve the runtime's browser entry for web builds and Node resolves its node entry, which adds the Node transports.

Without npm (plain <script type="module"> pages, quick scripts), build with <NexNetJavaScriptRuntimeImport>relative</NexNetJavaScriptRuntimeImport>: generated modules then import ./nexnet-runtime/index.js directly.

TypeScript. Import the generated modules as usual; their .d.ts describe the API. The emitted runtime has a .d.ts beside each of its modules (and types conditions in its package.json), so no allowJs is needed.

4. Connect

import { createChatClient, ChatClientNexusBase } from './generated/ChatServerNexus.js';

class ChatNexus extends ChatClientNexusBase {
  message(message) {
    console.log(`${message.user}: ${message.text}`);
  }

  getStatus() {
    return 'online';               // or a Promise
  }

  onConnected(isReconnected) { /* optional hook */ }
  onDisconnected(reason) { /* optional hook */ }
}

const client = createChatClient({
  webSocket: { url: 'wss://chat.example.com/nexus' },
  authenticate: () => new TextEncoder().encode(sessionToken),
}, new ChatNexus());

await client.connect();
client.proxy.send('hello');                          // void: fire and forget
const history = await client.proxy.history(20);      // ChatMessage[]
await client.disconnect();

A config holds exactly one transport property and the common options, named as the C# ClientConfig properties in camelCase, with durations in milliseconds (connectionTimeout, handshakeTimeout, timeout, pingInterval, maxPipes, …).

Transport Config Where
WebSocket webSocket: { url: 'wss://host/path', headers?, tls? } Node, browser
HttpSocket httpSocket: { url: 'https://host/path', headers?, tls? } Node
TCP tcp: { host, port } Node
TCP + TLS tcpTls: { host, port, tls? } Node
Unix domain socket uds: { path } Node

HttpSocket over TLS from Node, trusting a private CA and pinning the server key:

import { readFileSync } from 'node:fs';

const client = createChatClient({
  httpSocket: {
    url: 'https://chat.internal:5001/nexus',
    headers: { Authorization: `Bearer ${jwt}` },        // Node only
    tls: {
      ca: readFileSync('ca.pem'),
      pins: ['base64-sha256-of-spki='],                  // optional
      // cert/key or pfx/passphrase for a client certificate
    },
  },
}, new ChatNexus());
  • connect({ signal }) throws when the connection fails; tryConnect({ signal }) returns { success, state, disconnectReason, error } instead.
  • client.state is a ConnectionState; the client is an EventTarget with statechange (detail.state, detail.previous) and disconnected (detail.reason) events.
  • client.disconnected is a promise that settles when the connection is over for good (after reconnection gave up).
  • client.isSecure is false for ws://, http:// and plain TCP. Those log a warning once per client.
  • client.remoteCertificate is the server certificate (Node TLS transports only).
  • await using client = … disposes the client (Symbol.asyncDispose) where your platform supports it.

Node transports with relative imports

With RuntimeImport=relative, the generated createChatClient knows only WebSocket. For the other Node transports, create the client from the Node entry:

import { NodeNexusClient } from './generated/nexnet-runtime/node.js';
import { ChatClientBinding } from './generated/ChatServerNexus.js';

const client = NodeNexusClient.create({ tcpTls: { host: 'chat.internal', port: 7000 } }, new ChatNexus(),
  ChatClientBinding);

5. Authentication

The NexNet greeting token is the authentication mechanism every client supports, browsers included. authenticate runs before the transport connects, on every connect and reconnect, and may return a Uint8Array, null or a promise of one. If it throws, the connect fails with DisconnectReason.Authentication and no connection is opened. The server checks the token in OnAuthenticate (see Authentication).

authenticate: async ({ signal }) => {
  const token = await fetchToken({ signal });          // bounded by handshakeTimeout
  return new TextEncoder().encode(token);
},

A server method the client is not authorized for rejects with NexusUnauthorizedError.

6. Invocations and errors

Proxy methods are camelCase. A C# method that returns ValueTask<T> returns a Promise<T>, ValueTask a Promise<void>, and void returns nothing (fire and forget).

Error When
NexusTransportError (reason) Not connected, or the transport failed
NexusRemoteInvocationError (code, remoteType, remoteMessage) The server method threw (details only when the server sends them)
NexusUnauthorizedError The server's OnAuthorize refused the call
NexusBusyError A pipe, channel or collection was refused (limit or authorization)
NexusMessageTooLargeError An argument exceeded the server's MaxMessageSize
AbortError (DOMException) The call was canceled, or the session ended while it was pending (cause is the NexusTransportError)

All but AbortError extend NexusError. Client nexus methods that throw while returning a result send the failure to the server; override onInvocationException(error, methodId) to send your own { code, message }.

7. Cancellation

A C# CancellationToken parameter becomes a trailing { signal } option:

import { isCancellationError } from '@dtronix/nexnet';

try {
  const history = await client.proxy.history(1000, { signal: AbortSignal.timeout(5000) });
} catch (error) {
  if (isCancellationError(error)) { /* canceled or timed out */ }
}
  • Aborted before the call is sent: it rejects with signal.reason (or an AbortError) and nothing is sent.
  • Aborted after: it rejects at once and the server method's CancellationToken is canceled.
  • In a client nexus method, the CancellationToken parameter is an AbortSignal, aborted when the server cancels the call or the session ends.

8. Duplex pipes

const pipe = client.createPipe();
try {
  await client.proxy.upload(pipe, 'report.pdf');   // resolves once the invocation is sent
  await pipe.ready;

  const writer = pipe.writable.getWriter();
  await writer.write(fileBytes);                   // waits for the server's credit
  await writer.close();                            // half-close: the server reads the end of input
  await pipe.completed;
} finally {
  await pipe[Symbol.asyncDispose]();               // frees the pipe slot and its window
}
  • readable is a ReadableStream<Uint8Array> and writable a WritableStream<Uint8Array>. Credit is granted to the server only as you read, so a slow reader slows the server's writer, never the session.
  • A pipe from createPipe() holds a pipe slot until it is disposed, even if it was never used.
  • A pipe a client nexus method receives is released when the method returns or its promise settles.
  • pipe.forwardTo(other) and NexusDuplexPipe.bridge(a, b) copy between pipes with backpressure.

9. Channels

import { ChatMessageFormatter } from './generated/formatters.js';

const channel = client.createChannel(ChatMessageFormatter);
await client.proxy.subscribe(channel);

for await (const message of await channel.getReader()) {
  console.log(message.user, message.text);
}
  • await channel.getReader() (resolves once the pipe is ready): read(), readBatch(max), readUntilComplete() and async iteration.
  • await channel.getWriter(): write(item), writeMany(items), complete(), writeAndComplete(items).
  • Built-in item types use the runtime formatters (int32Formatter, stringFormatter, …); generated types use formatters.js.
  • A class formatter (ChatMessageFormatter, stringFormatter) reads T | null; createChannel still gives the NexusDuplexChannel<T> the proxy's channel parameter takes. For a channel of nullable items (INexusDuplexChannel<string?>), pass the type: createChannel<string | null>(stringFormatter).

10. Synchronized collections

const rooms = client.proxy.rooms;             // the same NexusList every time
rooms.addEventListener('changed', (e) => {
  const { action, index, item } = e.detail;   // add, remove, replace, move, reset, ready
  render(rooms.toArray());
});

await rooms.enable();                         // true once the initial state arrived
await rooms.add('general');                   // BiDirectional only; true once the server applied it
await rooms.disable();

The list changes only when the server's change arrives. ServerToClient and Relay lists are read-only on the client. ready and disabled are promises of the list's lifetime.

11. Reconnection

import { DefaultReconnectionPolicy } from '@dtronix/nexnet';

const config = {
  webSocket: { url: 'wss://chat.example.com/nexus' },
  reconnectionPolicy: new DefaultReconnectionPolicy({ delays: [0, 2000, 10000, 30000] }),
};
  • Node: no reconnection unless you set a policy. Browsers: DefaultReconnectionPolicy unless you set reconnectionPolicy: null.
  • A policy is { reconnectDelay(attempt) => ms | null, shouldReconnect?(reason) }. The default retries after 0, 2, 10 and 30 s, then every 30 s, for SocketError, Timeout and ServerRestarting.
  • During reconnection the nexus gets onReconnecting() and then onConnected(true). client.reconnection raises reconnecting, reconnectattempt, reconnected and reconnectfailed events.

12. Client pool

import { NexusClientPool } from '@dtronix/nexnet';
import { ChatClientBinding } from './generated/ChatServerNexus.js';

const pool = new NexusClientPool(
  { clientConfig: config, maxConnections: 8, maxIdleTime: 120_000, minIdleConnections: 1 },
  () => new ChatNexus(),
  ChatClientBinding);

const rented = await pool.rent();
try {
  await rented.proxy.history(10);
} finally {
  rented.release();
}
await pool[Symbol.asyncDispose]();

In Node, NexusClientPool from @dtronix/nexnet is the Node pool, with every Node transport. pool.collectionConnector(proxy => proxy.rooms) returns a connector whose getCollection() returns the client it holds to the pool, rents one and returns its list; release() returns the rented client.

13. Logging, metrics and diagnostics

import { ConsoleLogger, NexusMetrics } from '@dtronix/nexnet';

const config = { webSocket: { url }, logger: new ConsoleLogger({ minLevel: 'information' }) };

NexusMetrics.shared.track(client);                   // the C# instruments, same names and tags
NexusMetrics.shared.addListener({
  add: (instrument, value, tags) => { /* counters */ },
  record: (instrument, value, tags) => { /* histograms */ },
});
NexusMetrics.shared.collect((instrument, value, tags) => { /* observable instruments */ });

const snapshot = client.getSnapshot();               // the C# NexusSessionSnapshot, camelCase
  • A logger is { log(level, message, error) } (optional child(path)); ConsoleLogger and RollingLogger are provided. Tokens are never logged.
  • The metrics follow Metrics & Diagnostics: the module comment of NexusMetrics.js shows how to bridge them to OpenTelemetry.
  • import { getSessionCounters, getInvocationCounters } from '@dtronix/nexnet/diagnostics' exposes the process-wide leak counters.

14. Types

The generated classes take an init object: new ChatMessage({ user: 'me', text: 'hi' }). Members missing from it start at their C# initial value. Generated classes have equals(other) and hashKey() (use it as a Map key).

C# JavaScript
long, ulong, BigInteger bigint (number with [NexusJsNumber])
decimal, DateTime, TimeSpan, … runtime NexusDecimal, NexusDateTime, NexusTimeSpan, … (toDate()/fromDate())
Guid lower-case string
Dictionary<K, V>, HashSet<T> Map, Set

The full table is in Multi-language Clients: Type mapping.

Browser notes

  • WebSocket only. Expose a WebSocket endpoint on the server (NexNet.Asp MapNexusWebSocket or UseWebSocketNexusServerAsync); one server can also serve TCP, TLS and HttpSocket endpoints for other clients.
  • Use wss:// from pages served over HTTPS; browsers block ws:// there.
  • No headers, client certificates, custom CA or pinning. Authenticate with the greeting token (authenticate). If the server uses ASP.NET authentication, use cookies or the opt-in AccessTokenQueryParameter.
  • A refused credential is AuthenticationError. When ASP.NET authentication refuses the cookie or query-string token, NexNet.Asp accepts the WebSocket and refuses the session inside the protocol, so connect() rejects with transportError AuthenticationError in browsers as in Node, the same as for a token refused by the greeting (authenticate). Browsers hide the HTTP status of a refused WebSocket upgrade, so an upgrade the server does refuse (403 for an origin outside AllowedOrigins) looks like any other connect failure: InternalError, as for an unreachable server.
  • AllowedOrigins. When the server relies on cookies, set WebSocketServerConfig.AllowedOrigins to your site's origins to prevent cross-site WebSocket hijacking (see ASP.NET Integration: Browser Clients).
  • Background tabs. Browsers throttle timers in hidden tabs, which could let the server's idle timeout expire. The runtime runs its keepalive in a Web Worker created from a blob: URL; under a Content-Security-Policy, allow worker-src blob:, or the client falls back to a throttled main-thread timer. Reconnection also retries at once when the tab becomes visible or the network comes back.
  • Bundles. The browser entry never imports node: modules, so the Node transports are not bundled.