{"id":15727,"library":"node-opcua-client","title":"OPC UA Client for Node.js","description":"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.","status":"active","version":"2.169.0","language":"javascript","source_language":"en","source_url":"git://github.com/node-opcua/node-opcua","tags":["javascript","OPCUA","opcua","m2m","iot","opc ua","internet of things","typescript"],"install":[{"cmd":"npm install node-opcua-client","lang":"bash","label":"npm"},{"cmd":"yarn add node-opcua-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-opcua-client","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses ES Module syntax and ships TypeScript types. While CommonJS might work, ESM is the recommended and optimized approach for modern Node.js development, especially since v2.168.0's internal modernization.","wrong":"const OPCUAClient = require('node-opcua-client').OPCUAClient;","symbol":"OPCUAClient","correct":"import { OPCUAClient } from 'node-opcua-client';"},{"note":"Import core classes directly from the main package. Avoid importing from internal paths like 'dist/schemas' as these are not part of the public API and can change without notice.","wrong":"import { ClientSession } from 'node-opcua-client/dist/schemas';","symbol":"ClientSession","correct":"import { ClientSession } from 'node-opcua-client';"},{"note":"Named imports are preferred for specific enums and constants, providing better tree-shaking and clarity. Direct object access from a wildcard import is less efficient.","wrong":"import * as opcua from 'node-opcua-client'; const mode = opcua.MessageSecurityMode.None;","symbol":"MessageSecurityMode, SecurityPolicy, AttributeIds","correct":"import { MessageSecurityMode, SecurityPolicy, AttributeIds } from 'node-opcua-client';"}],"quickstart":{"code":"import {\n    OPCUAClient,\n    MessageSecurityMode,\n    SecurityPolicy,\n    AttributeIds\n} from \"node-opcua-client\";\n\nasync function main() {\n    // Use process.env.OPCUA_SERVER_ENDPOINT_URL for flexibility, fallback to localhost\n    const endpointUrl = process.env.OPCUA_SERVER_ENDPOINT_URL ?? \"opc.tcp://localhost:4840\";\n    \n    // Create an OPC UA client instance\n    const client = OPCUAClient.create({\n        endpointUrl: endpointUrl,\n        securityMode: MessageSecurityMode.None, // No security for simplicity (dev/test)\n        securityPolicy: SecurityPolicy.None, // No security policy\n        connectionStrategy: {\n            maxRetry: 10,\n            initialDelay: 2000,\n            maxDelay: 10 * 1000\n        }\n    });\n\n    try {\n        // Connect the client to the OPC UA server\n        await client.connect(endpointUrl);\n        console.log(\"Client connected to endpoint:\", endpointUrl);\n\n        // Create a session with the server\n        const session = await client.createSession();\n        console.log(\"Session created with ID:\", session.sessionId.toString());\n\n        // Define the NodeId to read (e.g., Server_ServerStatus_CurrentTime)\n        const nodeIdToRead = \"ns=0;i=2258\"; \n        \n        // Read the value of the specified node\n        const dataValue = await session.read({\n            nodeId: nodeIdToRead,\n            attributeId: AttributeIds.Value\n        });\n        console.log(`Value of ${nodeIdToRead}: ${dataValue.value.value}`);\n\n        // Close the session and disconnect the client\n        await session.close();\n        console.log(\"Session closed.\");\n\n        await client.disconnect();\n        console.log(\"Client disconnected.\");\n\n    } catch (err) {\n        console.error(\"An error occurred during OPC UA operations:\", err);\n        process.exit(1);\n    }\n}\n\nmain();","lang":"typescript","description":"Demonstrates how to connect to an OPC UA server, create a session, and read a value from a well-known NodeId (Server_ServerStatus_CurrentTime)."},"warnings":[{"fix":"Review your codebase for any non-public API usages, especially those that might have implicitly relied on `async` or `lodash` internal structures. Test thoroughly after upgrading.","message":"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.","severity":"breaking","affected_versions":">=2.168.0"},{"fix":"Be aware of the support model; consider a NodeOPCUA Membership for critical production applications or when extensive documentation and direct support are required. Rely on community forums or Stack Overflow for general questions.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure client and server certificates are correctly generated and mutually trusted. Place client certificates in the server's trust list and vice-versa. Verify `securityMode` and `securityPolicy` settings in `OPCUAClient.create` align with the server's configuration. For development, `MessageSecurityMode.None` and `SecurityPolicy.None` can bypass certificate issues.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If running an OPC UA server behind a proxy or NAT, configure its 'advertised endpoints' to expose the correct external IP address and port that clients should use for connection. Refer to the server's documentation or node-opcua server documentation for details on this configuration.","message":"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.","severity":"gotcha","affected_versions":">=2.165.0"},{"fix":"Implement robust error handling and retry logic around `createSession` and subscription creation. Consider periodically checking session status and actively recreating subscriptions if `keepalive_failure` or `session_closed` events are received. Ensure client application logic can handle transient disconnections and re-initialization.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify 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.","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.","error":"Error: connect ECONNREFUSED ::1:4840"},{"fix":"Ensure 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).","cause":"The client's connection request was rejected due to security policy mismatches, or the server did not trust the client's application certificate.","error":"StatusCode: BadSecurityChecksFailed"},{"fix":"If 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.","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.","error":"Error: Failed to create session (StatusCode: BadUserAccessDenied)"},{"fix":"Double-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.","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).","error":"StatusCode: BadNodeIdUnknown"},{"fix":"Ensure 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.","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.","error":"Error: The connection may have been rejected by server, Err = (Invalid message header detected)"}],"ecosystem":"npm"}