Node.js / TypeScript · recipe

Write a value to an OPC UA server in Node.js

Build a DataValue whose dataType matches the node exactly, then check the returned status code. The umati sample server accepts writes and silently discards them, so test against a local server and always read back.

Stacknode-opcua
Version2.181.1

The code

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

// umati is read-only. Start a local server first:
//   npm i node-opcua-samples && npx simple_server
const URL = "opc.tcp://localhost:26543";

(async () => {
  const client = OPCUAClient.create({ endpointMustExist: false });
  await client.connect(URL);
  const session = await client.createSession();

  const nodeId = "ns=1;s=MyVariable";

  // read the DataType attribute first - do not guess
  const dt = await session.read({ nodeId, attributeId: AttributeIds.DataType });
  console.log("declared dataType:", dt.value.value.toString());

  const status = await session.write({
    nodeId,
    attributeId: AttributeIds.Value,
    value: { value: { dataType: DataType.Double, value: 42.5 } },
  });
  console.log("write status     :", status.toString());

  const back = await session.read({ nodeId, attributeId: AttributeIds.Value });
  console.log("read back        :", back.value.value);

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

What it prints

declared dataType: ns=0;i=11
write status     : Good (0x00000000)
read back        : 42.5

Notes

  • Read the DataType attribute and match it. DataType.Double is not DataType.Float, and the server will tell you so.
  • A Good write status does not prove the value changed. Read back in tests: some servers accept and discard, deliberately.
  • Check AccessLevel before writing rather than interpreting the failure afterwards.
  • For arrays, supply the full array or an arrayType and IndexRange. A scalar into an array node is a type mismatch.

What breaks first

The write returns BadTypeMismatch even though the number looks right BadTypeMismatch
JavaScript has one number type and OPC UA has many. Read the node's DataType and set the dataType field on the Variant explicitly.

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