Node.js / TypeScript · recipe

Decode custom structures in Node.js

node-opcua reads the server's DataTypeDefinitions and can construct extension objects for you. Get the type's constructor from the session's data type manager, and you get named fields instead of a byte array.

Stacknode-opcua
Version2.181.1

The code

const { OPCUAClient, AttributeIds } = require("node-opcua");

(async () => {
  const client = OPCUAClient.create({ endpointMustExist: false });
  await client.connect("opc.tcp://opcua.umati.app:4840");
  const session = await client.createSession();

  // populate the session's data type manager from the server
  await session.extractNamespaceDataType();

  const dv = await session.read({
    nodeId: "ns=4;i=7001",
    attributeId: AttributeIds.Value,
  });

  const v = dv.value.value;
  console.log("decoded as:", v.constructor.name);
  console.log(JSON.stringify(v, null, 2));

  await session.close();
  await client.disconnect();
})();

What it prints

decoded as: ProductionJobType
{
  "identifier": "JOB-2026-0912",
  "state": 2,
  "partsPlanned": 500,
  "partsProduced": 431
}

Notes

  • Call extractNamespaceDataType() after creating the session and before reading structures, or you get an opaque ExtensionObject.
  • If decoding still fails, the server may publish only a legacy binary type dictionary rather than DataTypeDefinition attributes. That is an interoperability gap between the two mechanisms.
  • Unions and optional fields are the usual breaking point. Test them explicitly.
  • Field names arrive camelCased in JavaScript even though the model declares them PascalCased.

What breaks first

The structured value decodes to raw bytes instead of an object BadDataEncodingUnsupported
Extract the server's data types first. If the server offers only a type dictionary, you need a client that parses dictionaries or a change on the server.
Other recipes in this stack

Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.

Free download
OPC UA Troubleshooting & Integration Checklist
The field-tested checklist engineers use to diagnose certificates, ports and namespace problems fast, plus a Python (asyncua) client template.
Get the free checklist →
Free, no course, no login