OPC UA Client for Node.js
node-opcua-client is the client-side module of a comprehensive OPC UA SDK written entirely in JavaScript and Node.js, providing robust connectivity to OPC UA servers. Currently at version 2.169.0, the library exhibits a rapid and consistent release cadence, often featuring multiple patch and minor releases per month to introduce new features, performance enhancements, and bug fixes. Key differentiators include its pure Node.js implementation, broad support for various OPC UA specifications (including OPC UA 1.05 compliance), and a strong emphasis on performance through optimizations in data type handling, transport, and secure channel operations. The project maintains an open-source MIT license but offers commercial support, advanced documentation, and value-added extensions through Sterfive SAS, catering to professional and industrial applications.
Common errors
-
Error: connect ECONNREFUSED ::1:4840
cause The OPC UA client failed to establish a network connection to the server. This typically means the server is not running, is configured on a different IP address/port, or a firewall is blocking the connection.fixVerify that the OPC UA server application is running and listening on the specified `endpointUrl` (e.g., `opc.tcp://localhost:4840`). Check firewall rules on both the client and server machines. Use `telnet` or `nc` to manually test network reachability to the server's IP and port. -
StatusCode: BadSecurityChecksFailed
cause The client's connection request was rejected due to security policy mismatches, or the server did not trust the client's application certificate.fixEnsure the client's application certificate (usually generated automatically or found in a 'PKI/own/certs' folder) is copied to the server's trusted client certificates folder. Alternatively, set `securityMode: MessageSecurityMode.None` and `securityPolicy: SecurityPolicy.None` in `OPCUAClient.create` for unsecure connections (not recommended for production). -
Error: Failed to create session (StatusCode: BadUserAccessDenied)
cause The client successfully connected to the server, but the server rejected the session activation, often due to invalid user credentials, an unsupported user identity token, or insufficient user rights.fixIf using username/password authentication, verify the credentials are correct and the server supports this user identity token type on the chosen endpoint. If connecting anonymously, ensure the server's endpoint allows anonymous user access. -
StatusCode: BadNodeIdUnknown
cause The requested NodeId does not exist on the OPC UA server's address space, or its identifier string is malformed (e.g., incorrect namespace index or string identifier).fixDouble-check the NodeId string for typos (e.g., `ns=X;i=Y` for numeric, `ns=X;s=StringId` for string). Use an OPC UA client browser tool (like UA Expert) to verify the exact NodeId and its attributes on the target server. -
Error: The connection may have been rejected by server, Err = (Invalid message header detected)
cause A significant time discrepancy between the client and server machines can cause connection rejections, as OPC UA relies on synchronized timestamps for secure communication and certificate validation.fixEnsure the system clocks on both the client and the OPC UA server machines are synchronized, ideally using NTP (Network Time Protocol). A time difference of more than a few minutes can lead to handshake failures.
Warnings
- breaking Version 2.168.0 initiated a full migration of core packages from external utility libraries like `async` and `lodash` to native modern JavaScript patterns. While primarily internal, applications relying on internal types, structures, or indirect behaviors derived from these previous patterns might experience breaking changes if not strictly adhering to the public API.
- gotcha While node-opcua-client is open-source under the MIT license, comprehensive documentation (e.g., 'NodeOPCUA by Example') and technical support for advanced topics are primarily available to registered members of the NodeOPCUA Subscription or through professional services from Sterfive SAS. Open-source users may find limitations in self-serve resources for complex issues.
- gotcha OPC UA security relies heavily on X.509 certificates. Improper certificate configuration, issues with trust list management, or misconfigured security policies/modes are common sources of connection failures (e.g., 'BadSecurityChecksFailed'). This is especially true when dealing with self-signed certificates or specific server implementations.
- gotcha When an OPC UA server operates behind NAT, Docker port-mapping, or a reverse proxy, explicit configuration for 'advertised endpoints' is often necessary. Without it (since v2.165.0), clients might incorrectly discover the server's internal network address instead of its externally accessible one, leading to connection failures.
- gotcha Occasional issues with session reconnection and subscription recovery can occur after network interruptions or server restarts. Clients might fail to re-establish sessions or subscriptions, leading to a loss of real-time data updates, even if the underlying connection appears to be re-established.
Install
-
npm install node-opcua-client -
yarn add node-opcua-client -
pnpm add node-opcua-client
Imports
- OPCUAClient
const OPCUAClient = require('node-opcua-client').OPCUAClient;import { OPCUAClient } from 'node-opcua-client'; - ClientSession
import { ClientSession } from 'node-opcua-client/dist/schemas';import { ClientSession } from 'node-opcua-client'; - MessageSecurityMode, SecurityPolicy, AttributeIds
import * as opcua from 'node-opcua-client'; const mode = opcua.MessageSecurityMode.None;
import { MessageSecurityMode, SecurityPolicy, AttributeIds } from 'node-opcua-client';
Quickstart
import {
OPCUAClient,
MessageSecurityMode,
SecurityPolicy,
AttributeIds
} from "node-opcua-client";
async function main() {
// Use process.env.OPCUA_SERVER_ENDPOINT_URL for flexibility, fallback to localhost
const endpointUrl = process.env.OPCUA_SERVER_ENDPOINT_URL ?? "opc.tcp://localhost:4840";
// Create an OPC UA client instance
const client = OPCUAClient.create({
endpointUrl: endpointUrl,
securityMode: MessageSecurityMode.None, // No security for simplicity (dev/test)
securityPolicy: SecurityPolicy.None, // No security policy
connectionStrategy: {
maxRetry: 10,
initialDelay: 2000,
maxDelay: 10 * 1000
}
});
try {
// Connect the client to the OPC UA server
await client.connect(endpointUrl);
console.log("Client connected to endpoint:", endpointUrl);
// Create a session with the server
const session = await client.createSession();
console.log("Session created with ID:", session.sessionId.toString());
// Define the NodeId to read (e.g., Server_ServerStatus_CurrentTime)
const nodeIdToRead = "ns=0;i=2258";
// Read the value of the specified node
const dataValue = await session.read({
nodeId: nodeIdToRead,
attributeId: AttributeIds.Value
});
console.log(`Value of ${nodeIdToRead}: ${dataValue.value.value}`);
// Close the session and disconnect the client
await session.close();
console.log("Session closed.");
await client.disconnect();
console.log("Client disconnected.");
} catch (err) {
console.error("An error occurred during OPC UA operations:", err);
process.exit(1);
}
}
main();