Skip to content

Messages ​

client.session is the messages layer of RFC 6241: the <hello> exchange, <rpc> and <rpc-reply>, and <notification>. It numbers your requests, matches replies to them, turns <rpc-error> into exceptions, and tells you when the session closes. It knows nothing about datastores, paths or device profiles.

Most of the time you'll use client.ops or client.content instead, which are built on this layer. Nevertheless it exposes the lower level messaging primitives if you want to work with them. Some situations where you do need to work at this layer are:

  • when you need client.session to send an RPC that has no method, such as a vendor RPC
  • to look at what the server said in its hello
  • to listen for events
MessageOn client.session
<hello>sessionId, serverCapabilities, advertisedCapabilities, clientCapabilities, baseVersion
<rpc> / <rpc-reply>rpc(operation, { timeout, signal }), resolving with an RpcReply
<rpc-error>rejects with RpcError; warnings come back as reply.warnings and 'warning' events
<notification>the 'notification' event
<close-session>close(), state, and the 'closing' and 'closed' events

Hello ​

connect() resolves once both sides have sent their <hello>. What the server sent is then on the session:

ts
// The session-id the server assigned
console.log(client.session.sessionId);

// '1.1' (chunked framing) or '1.0' (end-of-message framing)
console.log(client.session.baseVersion);

const caps = client.session.serverCapabilities;
// true
console.log(caps.has(':candidate'));
// '2014-08-06'
console.log(caps.helloModule('ietf-system')?.revision);
// every YANG module advertised in the hello
console.log(caps.helloModules.map((m) => m.name));
// the advertised URIs, unchanged
caps.toArray();

has() takes a capability's short name (':candidate', ':base:1.1', ':xpath') or its full URI. The highest base version both sides support is used, so a server that only offers base:1.0 still works.

helloModule(), hasHelloModule() and helloModules cover only the YANG modules advertised in the hello. A hello advertises YANG 1.0 modules only; YANG 1.1 modules appear only in the server's YANG library (RFC 7950 §5.6.4). For the complete list, use client.content.modules().

A capability set prints, and serialises to JSON, as its list of advertised URIs.

There are three capability sets:

  • serverCapabilities: what the server advertised, after any corrections from the device profile. Capability checks use these.
  • advertisedCapabilities: exactly what the server advertised.
  • clientCapabilities: what the client advertised: both base versions, any you passed to connect({ capabilities }), and any added by enabled extensions.
ts
import { connect } from '@node-net/netconf';

const WIDGETS = 'urn:example:params:netconf:capability:widgets:1.0';

// lab is the REPL's transport to the lab device
const widgets = await connect({ transport: lab, capabilities: [WIDGETS] });
// true
console.log(widgets.session.clientCapabilities.has(WIDGETS));
await widgets.close();

The rest of the client hello can't be changed. To send a hello of your own, use the framed message channel.

Capability URIs ​

parseCapability() splits one capability URI into its id (the URI without its query) and its params. get() on a capability set returns the same parsed form, so a capability's parameters, such as with-defaults' basic-mode, are one call away. To query URIs you hold yourself, such as a hello you saved, build a CapabilitySet from them:

ts
import { CapabilitySet, parseCapability } from '@node-net/netconf';

const WD = 'urn:ietf:params:netconf:capability:with-defaults:1.0';

const cap = parseCapability(`${WD}?basic-mode=explicit&also-supported=trim`);
// 'urn:ietf:params:netconf:capability:with-defaults:1.0'
console.log(cap.id);
// 'explicit'
console.log(cap.params.get('basic-mode'));

const saved = new CapabilitySet([
  'urn:ietf:params:netconf:base:1.1',
  `${WD}?basic-mode=explicit`,
]);
// true
console.log(saved.has(':with-defaults'));
saved.get(':with-defaults')?.params.get('basic-mode');

has() and get() take a short name or a full URI, as on the session's sets.

RPC and reply ​

RPC ​

client.session.rpc() sends any operation. You give it what goes inside <rpc>, and the session adds the <rpc> element and the next message-id:

ts
import { x } from '@node-net/netconf';

const IF = 'urn:ietf:params:xml:ns:yang:ietf-interfaces';

const filter = x('filter', { type: 'subtree' },
  x('interfaces', { xmlns: IF },
    x('interface', x('name', 'eth0'), x('oper-status')),
  ),
);

const reply = await client.session.rpc(x('get', filter));
reply.data;

sends (indented here):

Output
<?xml version="1.0" encoding="UTF-8"?>
<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
  <get>
    <filter type="subtree">
      <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
        <interface>
          <name>eth0</name>
          <oper-status/>
        </interface>
      </interfaces>
    </filter>
  </get>
</rpc>

and reply.data is:

Output
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
  <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
    <interface>
      <name>eth0</name>
      <oper-status>up</oper-status>
    </interface>
  </interfaces>
</data>

The operation can be an element or XML text. Text is parsed first, so malformed XML rejects with an XmlError and nothing is sent. Passing the <rpc> element itself throws a TypeError.

RPC reply ​

rpc() resolves with an RpcReply:

messageIdthe message-id of the request and reply
oktrue if the reply is <ok/>
datathe <data> element, if the reply has one
outputevery child element other than <ok> and <rpc-error>: the operation's output parameters, such as an RPC's or action's output
elementthe whole <rpc-reply> element
warnings<rpc-error>s with severity warning
ts
const SYS = 'urn:ietf:params:xml:ns:yang:ietf-system';
const op = `<get-config>
  <source><running/></source>
  <filter><system xmlns="${SYS}"/></filter>
</get-config>`;
const reply = await client.session.rpc(op);

// XML text: '<data xmlns="…"><system xmlns="…"><contact>…'
console.log(reply.data?.toString());

// RFC 7951 JSON:
// { 'ietf-system:system': { contact: '…', hostname: 'lab1' } }
await client.content.toJson(reply.data!, { datastore: 'running' });

An <rpc-error> with severity error rejects with an RpcError. It holds every error in the reply (errors), the first one's tag (tag) and the <rpc-reply> element (reply). See Errors.

Prefixes inside values ​

Some values name schema items with a namespace prefix: an identityref such as ianaift:ethernetCsmacd, an instance-identifier, or an XPath. The prefix means whatever the namespace declarations in scope say, and a server may declare it on any element above the value, up to <rpc-reply> or <notification> (RFC 7950 §9.10.3):

xml
<rpc-reply message-id="7"
    xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
    xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">
  <data>
    <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
      <interface>
        <name>eth0</name>
        <type>ianaift:ethernetCsmacd</type>
      </interface>
    </interfaces>
  </data>
</rpc-reply>

Every element the client parses keeps the declarations in scope where it was parsed, so the prefix still resolves however you reach the value: from reply.data, an element below it, a notification's event, or an element read() selected. lookupNamespace(prefix) resolves one, and inScope holds them all:

ts
const op = '<get-config><source><running/></source></get-config>';
const reply = await client.session.rpc(op);

const type = reply.data!.path('interfaces/interface/type')!;
// 'ianaift:ethernetCsmacd'
type.text();
// 'urn:ietf:params:xml:ns:yang:iana-if-type'
type.lookupNamespace('ianaift');

Written out on its own, with toString() or in a log, an element declares the prefixes it inherited, so the text means the same apart from the reply. An element you build with x() knows only its own declarations, so declare a prefix on the element whose value uses it.

Timeouts and cancelling ​

Each call takes { timeout, signal }. Without a timeout, the client's timeouts.rpc (60 seconds by default) applies:

ts
const op = '<get-config><source><running/></source></get-config>';

const a = await client.session.rpc(op, { timeout: 120_000 });
const b = await client.session.rpc(op, { signal: AbortSignal.timeout(5_000) });
// both replied in time: their message-ids
[a.messageId, b.messageId];

A timeout rejects with a TimeoutError and an abort with an AbortError, and the session stays open. NETCONF has no way to cancel an RPC, so the server still carries it out. Its reply is dropped when it arrives.

For an RPC that may take a long time, such as a large commit, pass timeout: Infinity to wait with no limit. A value above 2,147,483,647 ms is shortened to it. Zero, a negative number or NaN rejects with a RangeError before the RPC is sent (Connecting has the rules).

Pipelining ​

Requests are sent as soon as you make them, without waiting for earlier replies, up to maxInFlight (32 by default) at once. Later ones wait their turn. Replies are matched to requests by message-id, whatever order they arrive in:

ts
const [running, candidate] = await Promise.all([
  client.ops.getConfig({ source: 'running' }),
  client.ops.getConfig({ source: 'candidate' }),
]);

A device that mishandles pipelining can set the maxInFlight quirk to 1 in its profile.

Notifications ​

Every <notification> the session receives is a 'notification' event, whichever subscription it belongs to:

ts
client.session.on('notification', (n) => {
  // as sent, e.g. '2026-11-10T09:12:44Z'
  n.eventTime;
  // the event element: the first child after eventTime
  n.event;
  // the whole <notification>
  n.element;
});

To start a subscription and read only its notifications, see Notifications and subscriptions.

Events ​

Type
// Every <notification> received
client.session.on('notification', (n) => …);

// rpc-error warnings, unmatched replies, stray messages
client.session.on('warning', (w) => …);

// close() was called
client.session.on('closing', () => …);

// Exactly once; cause is set if something failed
client.session.on('closed', ({ cause }) => …);

// Every NETCONF message sent or received, redacted
client.session.on('message', ({ direction, xml }) => …);

on() returns a function that removes the listener, and once() listens for one event. A listener that throws is logged, and doesn't affect other listeners or the session.

A 'warning' has a message, and rpcError when it came from an <rpc-error> of severity warning. A reply for a message-id nobody is waiting for is a warning, not an error.

A 'message' has direction ('send' or 'receive') and xml, the whole message after the same redaction as trace logging. Attach and remove it whenever you like. The hello exchange is over before connect() resolves, so to see the hellos, pass logger to connect() instead.

Closing ​

client.close() calls client.session.close(): it sends <close-session>, waits up to timeouts.close (5 seconds) for the reply, and closes the connection. client.session.state is 'open', 'closing' or 'closed'. An RPC on a closed session rejects with a SessionClosedError.

Tracing and timing ​

To log every message, or time each RPC through diagnostics_channel, see Logging and tracing.

Guards ​

client.session.addRpcGuard(guard) checks every operation before rpc() sends it, including those sent by client.ops and client.content. A guard refuses by throwing: rpc() then rejects with that error and sends nothing. It returns a function that removes the guard.

ts
const READ_ONLY = new Set([
  'get', 'get-config', 'get-data', 'get-schema',
]);

const removeGuard = client.session.addRpcGuard((op) => {
  if (!READ_ONLY.has(op.name)) {
    throw new Error(`Refusing <${op.name}> on a read-only device`);
  }
});

const refused = await client.content
  .set('/ietf-system:system/location', 'rack 4')
  .catch((err) => err.message);
removeGuard();

// 'Transaction failed at lock: Refusing <lock> on a read-only device'
refused;

The <close-session> sent by close() is never guarded.

Vendor RPCs ​

A vendor RPC, or any RPC the client has no method for, goes through client.session.rpc().

Writing the request ​

Give the RPC element its YANG module's namespace. An element without one is sent in the NETCONF base namespace, which is right for <get> or <lock> but not for most vendor RPCs. These two send the same request:

Other device
import { parseXml, x } from '@node-net/netconf';

const NS = 'urn:ietf:params:xml:ns:yang:ietf-system';

// Built with x()
await client.session.rpc(
  x('system-restart', { xmlns: NS })
);

// From XML text
await client.session.rpc(`<system-restart xmlns="${NS}"/>`);

Values are escaped for you: x('command', userInput) can't inject XML. A parameter in a different module from the RPC needs its own xmlns:

ts
import { x } from '@node-net/netconf';

const NCM = 'urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring';

const getSchema = x('get-schema', { xmlns: NCM },
  x('identifier', 'ietf-interfaces'),
  x('format', 'yang'),
);

const reply = await client.session.rpc(getSchema);

// The reply's <data> is in the monitoring namespace, not NETCONF's
const source = reply.element.child('data', NCM)?.text();
// 'module ietf-interfaces {'
source?.split('\n')[0];

To start from XML you already have, such as an example from the vendor's documentation, use parseXml() and pass the element. A plain string passed to x() as a child is sent as escaped text, not XML.

What a raw RPC skips ​

rpc() sends what you give it. It doesn't check capabilities, so a server that doesn't support the RPC replies with an RpcError (usually operation-not-supported), rather than the client refusing it with a CapabilityError. Content quirks such as subtreeFilter don't apply either, but session quirks and guards do.

The <rpc> element itself, with its message-id, is always the session's. To send something other than a well-formed <rpc>, such as for testing a server, use the framed message channel.

Calling it by path ​

An RPC defined in a YANG module the server lists can also be called by its path, with JSON input and typed JSON output: client.content.invoke('/ex:restart', { after: 10 }). The same call invokes YANG 1.1 actions. See Actions and RPCs by path.

Calling it by name ​

If you call a vendor RPC often, define it in a device profile as an XML template with parameters, and call it by name:

Other device
const params = { command: 'show version' };
const version = await client.ops.device.call('cli', params);

A profile operation is listed in client.ops.list, can be run with client.ops.run(), and becomes a command in the CLI, with its mutates flag deciding whether a read-only target allows it. To add a typed method instead, write an extension.

Released under the MIT Licence.