Node.js / TypeScript · recipe
Connect to an OPC UA server in Node.js
Create a client, connect the transport, then create a session. node-opcua separates those two steps deliberately, and you must close both in reverse order. Read the namespace array immediately: it tells you what the server implements.
| Stack | node-opcua |
|---|---|
| Version | 2.181.1 |
The code
const { OPCUAClient } = require("node-opcua");
const URL = "opc.tcp://opcua.umati.app:4840";
(async () => {
const client = OPCUAClient.create({
endpointMustExist: false,
connectionStrategy: { maxRetry: 3, initialDelay: 1000, maxDelay: 10000 },
});
await client.connect(URL);
const session = await client.createSession();
console.log("connected to", URL);
const ns = await session.readNamespaceArray();
ns.forEach((uri, i) => console.log(` ns=${i} ${uri}`));
await session.close();
await client.disconnect();
})();
What it prints
connected to opc.tcp://opcua.umati.app:4840
ns=0 http://opcfoundation.org/UA/
ns=1 urn:umati:sample-server
ns=2 http://opcfoundation.org/UA/DI/
ns=3 http://opcfoundation.org/UA/Machinery/
ns=4 http://opcfoundation.org/UA/MachineTool/
Notes
- Connect and createSession are separate calls, and so are close and disconnect. Leaking a session leaves the server holding resources until its timeout.
- `connectionStrategy` gives you retry and backoff for free. Configure it rather than writing your own loop.
- `endpointMustExist: false` lets you connect when the server advertises a hostname you cannot resolve, which is common behind NAT.
- readNamespaceArray caches the mapping on the session, which later calls use to resolve `nsu=` references.
What breaks first
The connection fails because the server advertises an endpoint URL you cannot reach
Set endpointMustExist to false so the client uses the URL you dialled, or fix the server's advertised hostname.
BadTcpEndpointUrlInvalidSet endpointMustExist to false so the client uses the URL you dialled, or fix the server's advertised hostname.
Other recipes in this stack
Concepts on this page
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.